在node.js应用程序中查询基于Mongo ID的MongoDB

use*_*242 13 javascript mongodb node.js express mongodb-query

我正在使用node.js和mongodb,我正在尝试使用以下内容基于mongo生成的ID查询数据库:

    collection.findOne( {_id:doc._id} , function(err, item) {});
Run Code Online (Sandbox Code Playgroud)

我100%确定我的doc._id与我在集合中寻找的doc _id完全匹配,但我从db查询中获得了null响应.

我已经尝试使用文档中的其他键,它返回文档就好了.只有当我尝试使用mongo ID时才会这样.

use*_*242 15

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

    var id = require('mongodb').ObjectID(doc._id);
Run Code Online (Sandbox Code Playgroud)

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


小智 14

用这个:

ObjectId = require('mongodb').ObjectID;
Run Code Online (Sandbox Code Playgroud)

然后,当您尝试通过_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;
     }

   });
Run Code Online (Sandbox Code Playgroud)


Amo*_*rni 9

以下是发现问题的示例:

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)); 
        });
  });
});
Run Code Online (Sandbox Code Playgroud)


KAR*_*N.A 5

首先我们需要ObjectIDmongodb库中获取,并需要通过以下方式创建新实例,以便您将获得字符串的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' } ]
Run Code Online (Sandbox Code Playgroud)