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

后端 未结 5 1166
夕颜
夕颜 2020-12-10 02:57

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         


        
5条回答
  •  我在风中等你
    2020-12-10 03:51

    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;
         }
    
       });
    

提交回复
热议问题