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

后端 未结 5 1165
夕颜
夕颜 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:39

    Following is the example which spots the issue:

    var mongo = require('mongodb'),
        Server = mongo.Server,
        Db = mongo.Db,
        ObjectID = require('mongodb').ObjectID;
    var MongoClient = require('mongodb').MongoClient
    
    //let id = your _id, smth like '6dg27sh2sdhsdhs72hsdfs2sfs'...
    var obj_id = new ObjectID('52cbd028e9f43a090ca0c1af');
    var justId = '52cbd028e9f43a090ca0c1af'; // <== This will not work
    
    MongoClient.connect('mongodb://127.0.0.1:27017/YourDbName', function(err, db) {
        console.log('err'  +  err);
        db.collection('YourCollectionName', function(error, collection) {
            //collection.find({_id:justId}),function(err, docs) { // <== This will not work
            collection.findOne({_id:obj_id},function(err, docs) {
              console.log("Printing docs from Array. count " + JSON.stringify(docs)); 
            });
      });
    });
    

提交回复
热议问题