【问题标题】:Querying a MongoDB based on Mongo ID in a node.js app在 node.js 应用程序中根据 Mongo ID 查询 MongoDB
【发布时间】:2012-10-07 13:28:57
【问题描述】:

我正在使用 node.js 和 mongodb,我正在尝试使用以下命令根据 mongo 生成的 ID 查询数据库:

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

我 100% 确定我的 doc._id 与我在集合中寻找的 doc _id 完全匹配,但我从 db 查询中得到一个空响应。

我已经尝试使用文档中的其他键进行此操作,它返回文档就好了。只有当我尝试使用 mongo ID 时。

【问题讨论】:

  • doc._id 是 ObjectId 的字符串表示形式还是实际的 ObjectId?

标签: javascript node.js mongodb express mongodb-query


【解决方案1】:

MongoDb 是一个对象而不是字符串。要转换我使用的字符串:

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

这会将我的字符串转换为 mongo ObjectId 并匹配 db 中的 _id!

【讨论】:

    【解决方案2】:

    以下是发现问题的示例:

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

    【讨论】:

      【解决方案3】:

      使用这个:

      ObjectId = require('mongodb').ObjectID;
      

      然后,当您尝试通过 _id 在集合中查找对象时,请使用:

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

      【讨论】:

        【解决方案4】:

        首先我们需要从mongodb库中获取ObjectID,并需要按照以下方式创建新实例,这样你就可以得到字符串的ObjectID。如果您在代码中使用 es6,则此代码

        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' } ]
        

        【讨论】:

          【解决方案5】:

          首先,确保您已在 MongoDB 配置中添加了所有必需的模块:

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

          然后,当您尝试通过 _id 在集合中查找对象时,请使用:

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

          希望,这行得通。

          【讨论】:

            猜你喜欢
            • 2022-06-10
            • 2023-03-24
            • 1970-01-01
            • 2021-09-03
            • 2012-08-12
            • 2016-08-25
            • 2023-03-23
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多