skip to Main Content

For example

await Smartphones.findOne({_id: req.params.id})
await Smartphones.findOne({_id: ObjectId(req.params.id)})

To me it seem both return object, but I don’t if it have any benefit of using ObjectId when comparing

2

Answers


  1. If you are using ObjectId(req.params.id) it will try to parse the "req.params.id" value to mongoDB Object Id, if its unable to parse it throws an error as "req.params.id" is not a valid mongo object id

    Login or Signup to reply.
  2. If you are using MongoDB Compass to fetch some data, you can’t use the _id as a simple string, there you should use ObjectId for getting the data. An _id in the document can be of any form except an array, and the default format is ObjectId. The ObjectId is not just a simple format in MongoDB, other than that of a format it has some use-cases too, you can refer to this link

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search