Home > Blockchain >  What benefit of using mongoose.Types.ObjectId instead of req.params.id to compare with the _id in Mo
What benefit of using mongoose.Types.ObjectId instead of req.params.id to compare with the _id in Mo

Time:04-12

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

CodePudding user response:

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

CodePudding user response:

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

  • Related