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

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

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

我100%肯定,我的doc._id是一个完全匹配的doc _id,我正在寻找收集,但我得到一个空数据库查询响应。

我已经尝试过使用文档中的其他键,它返回文档就好了。 只有当我尝试使用mongo ID。

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

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

这将我的string转换成mongo ObjectId并匹配db中的_id!

以下是发现问题的例子:

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

用这个:

 ObjectId = require('mongodb').ObjectID; 

然后当你尝试通过_idfind一个集合中的对象时,使用这个:

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

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

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

希望,这个工程。