Reputation: 724
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'.
Upvotes: 0
Views: 484
Reputation: 51
This will works fine.
You can use BSON for get ObjectID from HEX string.
var mongodb = require('mongodb');
var BSON = mongodb.BSONNative;
var o_id = BSON.ObjectID.createFromHexString(theidID);
collection.findOne({'_id' : o_id}, function(err, document) {
console.log(document);
});
Upvotes: 0
Reputation: 311935
The correct syntax is:
collection.findOne({ _id : new mongodb.ObjectID('50738ebbe3d87c6beaddb6f2') },
function(err, result){
res.send(result);
console.log(result);
}
);
Upvotes: 1