Why we pass document ID to mongoose.Types.ObjectId(documentId) instead of directly passing string id

Viewed 30

So when creating or finding (based on reference) documents in mongodb using mongoose we use two methods to pass object id. One is simply passing the id in form of string and the other is by the mongoose.Types.ObjectId(documentId). What's the difference between them? For better understanding see these two examples:

Option 1:

const articles = await Article.find({user: userId})

Option 2:

const articles = await Article.find({user: mongoose.Types.ObjectId(userId)}

So, do we really need to first pass it to mongoose.Types.ObjectId?

PS: I know that passing to the mongoose.types.objectId will throw an error in case if id is not an object id of MongoDB. I'm seeking if there is any other benefit of this approach or not.

0 Answers
Related