MongoDB native driver for Node.js is not returning a result when querying '_id'
Problem
I am trying to query my database for a matching '_id' but the results are coming back null, but in the mongodb shell it is coming back with the correct results. Here is the code I am using.
var collection = new mongodb.Collection(client, 'products');
collection.findOne({ _id : 50738ebbe3d87c6beaddb6f2 }, function(err, result){
res.send(result);
console.log(result);
});
I've also tried using,
"ObjectId('50738ebbe3d87c6beaddb6f2')"
but that also come back 'null'.
Problem courtesy of: Collin McGuire
Solution
The correct syntax is:
collection.findOne({ _id : new mongodb.ObjectID('50738ebbe3d87c6beaddb6f2') },
function(err, result){
res.send(result);
console.log(result);
}
);
Solution courtesy of: JohnnyHK
Discussion
View additional discussion.