Querying a MongoDB based on Mongo ID in a node.js app


Question

I'm using a node.js and mongodb, and I'm trying to query the database based on the mongo generated ID using the following:

    collection.findOne( {_id:doc._id} , function(err, item) {});

I am 100% certain that my doc._id is an exact match to the doc _id that I am looking for in the collection, and yet I get a null response from the db query.

I have tried this using other keys in the document and it returns the document just fine. It's only when I try to use the mongo ID.

1
13
10/7/2018 6:03:07 PM

Use this:

ObjectId = require('mongodb').ObjectID;

Then when you try to find an object in collection by _id use this:

 console.log("find by: "+ id);
 database.collection("userRegister").findOne({_id: new ObjectId(id)}, 
   function(err, res) { 

     if (err) console.log(err);

     if(res!=null){
       console.log(res)
       return false;
     }

     if(res==null){
       callback({'status':_error,'flag':'notexist','message':_userNotExist});
       return false;
     }

   });
14
9/18/2017 5:53:27 AM

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon