Najmul Huda Eimon
Najmul Huda Eimon

Reputation: 3

Why we use ObjectId(id) in Mongodb?

What is the purpose of using Object Id here?

app.get('/product/:id', async(req, res) => {
  const id = req.params.id;
  const query = { _id: ObjectId(id) };
  const product = await productCollection.findOne(query);
  res.send(product);
})

Upvotes: 0

Views: 1152

Answers (1)

Martinez
Martinez

Reputation: 1130

The field name _id is reserved for use as a primary key; its value must be unique in the collection, is immutable, and may be of any type other than an array as default mongo use it as ObjectId.

So the purpose you parse the id it because id its a String and in you database _id it not a string it an ObjectId.

Note: if you are using mongoose you don't need to parse the id to ObjectId cause mongoose auto cast that field to ObjectId

Upvotes: 1

Related Questions