node.js 在 Node 中通过“_id”搜索 MongoDB 条目的正确方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17545311/
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
Correct way to search for MongoDB entries by '_id' in Node
提问by JVG
I'm using MongoDb(as part of MongoJS) in Node. Here is the documentation for MongoJS.
我使用MongoDb(作为其一部分MongoJS)的Node。这是 MongoJS 的文档。
I'm trying to do a call within Node based on an entry's _idfield. When using vanilla MongoDBfrom the console, I can do:
我正在尝试根据条目的_id字段在 Node 内进行调用。MongoDB从控制台使用香草时,我可以这样做:
db.products.find({"_id":ObjectId("51d151c6b918a71d170000c7")})
db.products.find({"_id":ObjectId("51d151c6b918a71d170000c7")})
and it correctly returns my entry. However, when I do the same thing in Node, like:
它正确地返回了我的条目。但是,当我在 Node 中做同样的事情时,比如:
db.products.find({"_id": ObjectId("51d151c6b918a71d170000c7")}, function (err, record) {
// Do stuff
});
I get ReferenceError: ObjectId is not defined.
我明白了ReferenceError: ObjectId is not defined。
What is the correct protocol for doing this?
这样做的正确协议是什么?
回答by Chris
You need to require the ObjectId function before using it:
在使用它之前,您需要需要 ObjectId 函数:
var ObjectId = require('mongodb').ObjectID;
回答by ofir_aghai
if you are using mongoose you can try this:
如果你使用猫鼬,你可以试试这个:
var mongoose = require('mongoose')
usersSchema = mongoose.model('users'),
mongoose.Types.ObjectId("<object_id>")
usersSchema.find({"_id": mongoose.Types.ObjectId("<object_id>")}, function (err, record) {
// Do stuff
});
回答by Israel Ortiz Cortés
You can also destructure your ObjectId and MongoClient to optimize your code and make it more readable.
您还可以解构 ObjectId 和 MongoClient 以优化代码并使其更具可读性。
const { MongoClient, ObjectId } = require('mongodb');
回答by Amol
If you are using MongoJS, you can do:
如果您使用的是 MongoJS,则可以执行以下操作:
var ObjectId = mongojs.ObjectId;
Then,
然后,
db.users.find({"_id": ObjectId(id)}, function(err, user){...}
回答by Nick Taras
Here's another way to utilise objectId when using mongoose.
这是使用 mongoose 时利用 objectId 的另一种方法。
// at the top of the file
const Mongoose = require('mongoose')
const ObjectId = Mongoose.Types.ObjectId;
// when using mongo to collect data
Mongoose.model('users', userSchema).findOne({ _id:
ObjectId('xyz') }, function (err, user) {
console.log(user)
return handle(req, res)
})
})

