Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

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

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.



This post first appeared on Node.js Recipes, please read the originial post: here

Share the post

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

×

Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription

×