Collin McGuire
Collin McGuire

Reputation: 724

MongoDB native driver for Node.js is not returning a result when querying '_id'

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

Answers (2)

Soaple
Soaple

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

JohnnyHK
JohnnyHK

Reputation: 311935

The correct syntax is:

collection.findOne({ _id : new mongodb.ObjectID('50738ebbe3d87c6beaddb6f2') }, 
  function(err, result){
    res.send(result);
    console.log(result);
  }
);

Upvotes: 1

Related Questions