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

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

    First, ensure you've added all required modules in MongoDB config:

    var mongo = require('mongodb'),
        Server = mongo.Server,
        Db = mongo.Db,
        ObjectID = require('mongodb').ObjectID;
    var BSON = require('mongodb').BSONPure;
    var server = new Server('localhost', 27017, {
        auto_reconnect: true
    });
    var db = new Db('YOUR_DB_NAME', server);
    

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

    //let id = your _id, smth like '6dg27sh2sdhsdhs72hsdfs2sfs'...
    var obj_id = BSON.ObjectID.createFromHexString(id);
    db.collection("NAME_OF_COLLECTION_WHERE_IS_YOUR_OBJECT", function(error, collection) {
        collection.findOne( {_id:obj_id} , function(err, item) {
            // console.log ( item.username );
        });
    });
    

    Hope, this works.

    0 讨论(0)
  • 2020-12-10 03:30

    The MongoDb is an object not a string. To convert my string I used:

        var id = require('mongodb').ObjectID(doc._id);
    

    This converts my string into a mongo ObjectId and matches the _id in the db!

    0 讨论(0)
  • 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)); 
            });
      });
    });
    
    0 讨论(0)
  • 2020-12-10 03:43

    First we need to get ObjectID from mongodb library and need to create new instance in following way., so that you will get the ObjectID of string. If your are using es6 in your code this code

    import { ObjectID } from 'mongodb';
    
    var emQuery = [
              {
                $match: {
                  _id: new ObjectID(tlvaltResult[0].customers.createdBy)
                }
              },
              {
                $project: {
                  _id:1,
                  emailId:1,
                  mobile:1
                }
              }
            ];
    
    console.log(emQuery,'emQuery');
    
    [ { '$match': { _id: 5ad83ff0b443435298741d3b } },
      { '$project': { _id: 1, emailId: 1, mobile: 1 } } ] 
    
    var emResult = await User.getAggregation(emQuery);
    
    console.log(emResult,'emResult');
    
    [ { _id: 5ad83ff0b443435298741d3b,
        emailId: 'superAdmin@limitlessmobile.com' } ]
    
    0 讨论(0)
  • 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;
         }
    
       });
    
    0 讨论(0)
提交回复
热议问题