Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to get element with custom _id? #71

Open
lukaszflorczak opened this issue Jan 24, 2018 · 3 comments
Open

How to get element with custom _id? #71

lukaszflorczak opened this issue Jan 24, 2018 · 3 comments
Labels

Comments

@lukaszflorczak
Copy link

lukaszflorczak commented Jan 24, 2018

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?

@duyluonglc
Copy link
Owner

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

static get ObjectIDs () { return [] }

@lukaszflorczak
Copy link
Author

lukaszflorczak commented Feb 3, 2018

@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

@datlmrikkeisoft
Copy link

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

3 participants