Javascript node.js mongodb 通过 _id 选择文档 node-mongodb-native
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4902569/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
node.js mongodb select document by _id node-mongodb-native
提问by Mark
I'm trying to select a document by id
我正在尝试通过 id 选择文档
I've tried:
我试过了:
collection.update({ "_id": { "$oid": + theidID } }
collection.update({ "_id": theidID }
collection.update({ "_id.$oid": theidID }}
Also tried:
还试过:
collection.update({ _id: new ObjectID(theidID ) }
This gives me an error 500...
这给了我一个错误 500 ...
var mongo = require('mongodb')
var BSON = mongo.BSONPure;
var o_id = new BSON.ObjectID(theidID );
collection.update({ _id: o_id }
None of these work. How to select by _id?
这些都不起作用。如何通过_id选择?
回答by KingPin
var mongo = require('mongodb');
var o_id = new mongo.ObjectID(theidID);
collection.update({'_id': o_id});
回答by ncoronges
This the approach that worked for me.
这是对我有用的方法。
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);
});
});
}
回答by nktssh
回答by Raphael Schweikert
With native_parser:false:
与native_parser:false:
var BSON = require('mongodb').BSONPure;
var o_id = BSON.ObjectID.createFromHexString(theidID);
With native_parser:true:
与native_parser:true:
var BSON = require('mongodb').BSONNative;
var o_id = BSON.ObjectID.createFromHexString(theidID);
回答by Yarik
I just used this code in Node.js app in controller file, and it works:
我刚刚在控制器文件中的 Node.js 应用程序中使用了这段代码,它可以工作:
var ObjectId = require('mongodb').ObjectId;
...
User.findOne({_id:ObjectId("5abf2eaa1068113f1e")})
.exec(function(err,data){
// do stuff
})
do not forget to install "mongodb" before, and if you are using encryption of your passwords with bcrypt with "presave", be sure that you will not encrypt password after each modification of the record in DB.
之前不要忘记安装“mongodb”,如果您使用带有“presave”的bcrypt加密密码,请确保在每次修改DB中的记录后都不会加密密码。
回答by antelove
/* get id */
const id = request.params.id; // string "5d88733be8e32529c8b21f11"
/* set object id */
const ObjectId = require('mongodb').ObjectID;
/* filter */
collection.update({
"_id": ObjectId(id)
} )
回答by Roger Perez
This is what worked for me. Using mongoDB
这对我有用。使用 mongoDB
const mongoDB = require('mongodb')
const mongoDB = require('mongodb')
Then at the bottom where I am making my express get call.
然后在底部,我正在拨打我的快递电话。
router.get('/users/:id', (req, res) => {
const id = req.params.id;
var o_id = new mongoDB.ObjectID(id);
const usersCollection = database.collection('users');
usersCollection.findOne({
_id: o_id
})
.then(userFound => {
if (!userFound){
return res.status(404).end();
}
// console.log(json(userFound));
return res.status(200).json(userFound)
})
.catch(err => console.log(err));
});`
回答by jmontross
The answer depends upon the variable type you are passing in as the id. I pulled an object id by doing a query and storing my account_id as the ._id attribute. Using this method you simply query using the mongo id.
答案取决于您作为 id 传入的变量类型。我通过执行查询并将我的 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();
}
}
)
}
})
});
});
回答by Diego Mauricio Guerrero
If you use Mongosee, you can simplify the function
如果使用Mongosee,可以简化功能
FindById:
FindById:
this replace in mongodb: "_id" : ObjectId("xyadsdd434434343"),
mongodb 中的这个替换: "_id" : ObjectId("xyadsdd434434343"),
example:
// find adventure by id and execute
Adventure.findById('xyadsdd434434343', function (err, adventure) {});

