lucid-mongo
lucid-mongo copied to clipboard
How to get element with custom _id?
Hi. I have products with custom, unique 6-chars ID (for example 123456
).
I added test product by MongoDB console:
db.products.insertOne({ _id: "123456", name: "Test Product" })
My Adonis files:
// routes.js
Route.group(() => {
Route.get('products/:id', 'ProductController.show')
}).prefix('v1')
// show method from ProductController.js
async show ({params, response}) {
const product = await Product.where('_id', params.id).fetch()
return response.json(product)
}
When I try to send a GET request http://127.0.0.1:3333/v1/products/123456
I get an error:
Argument passed in must be a single String of 12 bytes or a string of 24 hex characters
If I try to find it by Mongo console (db.products.find({_id: "123456"})
) it works fine.
How can I use in controller/router custom _id
?
@lukaszflorczak default model will automatic parse primaryKey to bjson.ObjectID you can manual remove automatic parse by
static get ObjectIDs () { return [] }
@duyluonglc I added it in my Product Model, but in ProductController I have this code:
let id = params.id + ''
let product = await Product.findBy('_id', id)
and it still returns error:
Argument passed in must be a single String of 12 bytes or a string of 24 hex characters
@duyluonglc I added it in my Product Model, but in ProductController I have this code:
let id = params.id + '' let product = await Product.findBy('_id', id)
and it still returns error:
Argument passed in must be a single String of 12 bytes or a string of 24 hex characters
Hi. I also set like you but still got error. Did you resolve it?