MongoDB 通过 Mongoose JS - 什么是 findByID?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12483632/
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
MongoDB via Mongoose JS - What is findByID?
提问by Legendre
I am writing a NodeJS server with ExpressJS, PassportJS, MongoDB and MongooseJS. I just managed to get PassportJS to use user data obtained via Mongoose to authenticate.
我正在用 ExpressJS、PassportJS、MongoDB 和 MongooseJS 编写 NodeJS 服务器。我只是设法让 PassportJS 使用通过 Mongoose 获得的用户数据进行身份验证。
But to make it work, I had to use a "findById" function like below.
但是为了使它工作,我必须使用如下所示的“findById”函数。
var UserModel = db.model('User',UserSchema);
UserModel.findById(id, function (err, user) { < SOME CODE > } );
UserModel
is a Mongoose model. I declare the schema, UserSchema
earlier. So I suppose UserModel.findById()
is a method of the Mongoose model?
UserModel
是猫鼬模型。我UserSchema
更早地声明了模式。所以我想UserModel.findById()
是猫鼬模型的一种方法?
Question
题
What does findById
do and is there documentation on it? I googled around a bit but didn't find anything.
有什么作用findById
,是否有相关文档?我用谷歌搜索了一下,但没有找到任何东西。
回答by JohnnyHK
findById
is a convenience method on the model that's provided by Mongoose to find a document by its _id. The documentation for it can be found here.
findById
是 Mongoose 提供的模型上的一种便捷方法,用于通过其 _id 查找文档。可以在此处找到它的文档。
Example:
例子:
// Search by ObjectId
var id = "56e6dd2eb4494ed008d595bd";
UserModel.findById(id, function (err, user) { ... } );
Functionally, it's the same as calling:
在功能上,它与调用相同:
UserModel.findOne({_id: id}, function (err, user) { ... });
Note that Mongoose will cast the provided id
value to the type of _id
as defined in the schema (defaulting to ObjectId).
请注意,Mongoose 会将提供的id
值转换_id
为架构中定义的类型(默认为 ObjectId)。
回答by Dasikely
If the schema of id is not of type ObjectIdyou cannot operate with function : findbyId()
如果 id 的架构不是ObjectId类型,则无法使用函数进行操作: findbyId()
回答by Bonnie Varghese
As opposed to find() which can return 1 or more documents, findById() can only return 0 or 1 document. Document(s) can be thought of as record(s).
与 find() 可以返回 1 个或多个文档相反, findById() 只能返回 0 个或 1 个文档。文档可以被认为是记录。
回答by vkarpov15
I'm the maintainer of Mongoose. findById()
is a built-in method on Mongoose models. findById(id)
is equivalent to findOne({ _id: id })
, with one caveat: findById()
with 0 params is equivalent to findOne({ _id: null })
.
我是猫鼬的维护者。findById()
是猫鼬模型的内置方法。findById(id)
等价于findOne({ _id: id })
,但有一个警告:findById()
0 params 等价于findOne({ _id: null })
。
You can read more about findById()
on the Mongoose docsand this findById()
tutorial.
您可以阅读有关findById()
Mongoose 文档和本findById()
教程的更多信息。