Express MongoDB Find() Based On _id Field
So In my express app, I am trying to find() based on my _id field. See my MongoDB record below. { '_id': { '$oid': '58c2a5bdf36d281631b3714a' },
Solution 1:
db.collection('articles')
.find( {"_id.$oid": id} )
.
or even more specific:
db.collection('articles')
.findOne( {"_id.$oid": id} )
.
EDIT:
Converting string into ObjectId type before querying
var ObjectID = require('mongodb').ObjectID;
db.collection('articles')
.findOne( {"_id.$oid": new ObjectID(id)})
.
Reference: If i have a mongo document id as a string how do I query for it as an _id?
Solution 2:
for me "_id.$oid"
didn't work. I had to use "_id"
as shown in following code snippet.
const { ObjectId } = require('mongodb');
...
collection.findOne({ "_id": ObjectId(req.params['id']) })
.then(...)
Post a Comment for "Express MongoDB Find() Based On _id Field"