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

时间:2012-10-07 13:28:58

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

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

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

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

我已经使用文档中的其他键尝试了这个并且它返回文档就好了。只有在我尝试使用mongo ID时才会这样。

5 个答案:

答案 0 :(得分:14)

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

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

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

答案 1 :(得分:13)

使用此:

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

   });

答案 2 :(得分: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)); 
        });
  });
});

答案 3 :(得分:1)

首先,确保您已在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 );
    });
});

希望,这有效。

答案 4 :(得分:1)

首先我们需要从ObjectID库中获取mongodb,并且需要按照以下方式创建新实例。这样您将获得字符串的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' } ]