node.js mongodb通过_id node-mongodb-nativeselect文档

我试图通过IDselect一个文件

我试过了:

collection.update({ "_id": { "$oid": + theidID } } collection.update({ "_id": theidID } collection.update({ "_id.$oid": theidID }} 

还试过:

 collection.update({ _id: new ObjectID(theidID ) } 

这给了我一个错误500 …

 var mongo = require('mongodb') var BSON = mongo.BSONPure; var o_id = new BSON.ObjectID(theidID ); collection.update({ _id: o_id } 

这些都没有工作。 如何通过_idselect?

 var mongo = require('mongodb'); var o_id = new mongo.ObjectID(theidID); collection.update({'_id': o_id}); 

这是为我工作的方法。

 var ObjectId = require('mongodb').ObjectID; var get_by_id = function(id, callback) { console.log("find by: "+ id); get_collection(function(collection) { collection.findOne({"_id": new ObjectId(id)}, function(err, doc) { callback(doc); }); }); } 

使用native_parser:false

 var BSON = require('mongodb').BSONPure; var o_id = BSON.ObjectID.createFromHexString(theidID); 

使用native_parser:true

 var BSON = require('mongodb').BSONNative; var o_id = BSON.ObjectID.createFromHexString(theidID); 

现在你可以使用这个:

 var ObjectID = require('mongodb').ObjectID; var o_id = new ObjectID("yourObjectIdString"); .... collection.update({'_id': o_id}); 

你可以在这里看到文档

答案取决于你作为id传入的variablestypes。 我通过查询并将我的account_id存储为._id属性来提取对象ID。 使用这种方法,你只需使用mongo id进行查询。

 // begin account-manager.js var MongoDB = require('mongodb').Db; var dbPort = 27017; var dbHost = '127.0.0.1'; var dbName = 'sample_db'; db = new MongoDB(dbName, new Server(dbHost, dbPort, {auto_reconnect: true}), {w: 1}); var accounts = db.collection('accounts'); exports.getAccountById = function(id, callback) { accounts.findOne({_id: id}, function(e, res) { if (e) { callback(e) } else { callback(null, res) } }); } // end account-manager.js // my test file var AM = require('../app/server/modules/account-manager'); it("should find an account by id", function(done) { AM.getAllRecords(function(error, allRecords){ console.log(error,'error') if(error === null) { console.log(allRecords[0]._id) // console.log('error is null',"record one id", allRecords[0]._id) AM.getAccountById( allRecords[0]._id, function(e,response){ console.log(response,"response") if(response) { console.log("testing " + allRecords[0].name + " is equal to " + response.name) expect(response.name).toEqual(allRecords[0].name); done(); } } ) } }) 

});