lucid-mongo icon indicating copy to clipboard operation
lucid-mongo copied to clipboard

How to get element with custom _id?

Open lukaszflorczak opened this issue 7 years ago • 3 comments

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 avatar Jan 24 '18 21:01 lukaszflorczak

@lukaszflorczak default model will automatic parse primaryKey to bjson.ObjectID you can manual remove automatic parse by

static get ObjectIDs () { return [] }

duyluonglc avatar Jan 28 '18 18:01 duyluonglc

@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

lukaszflorczak avatar Feb 03 '18 17:02 lukaszflorczak

@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?

datlmrikkeisoft avatar May 30 '19 04:05 datlmrikkeisoft