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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 12:50:21  来源:igfitidea点击:

MongoDB via Mongoose JS - What is findByID?

mongodbmongoose

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

UserModelis a Mongoose model. I declare the schema, UserSchemaearlier. So I suppose UserModel.findById()is a method of the Mongoose model?

UserModel是猫鼬模型。我UserSchema更早地声明了模式。所以我想UserModel.findById()是猫鼬模型的一种方法?

Question

What does findByIddo and is there documentation on it? I googled around a bit but didn't find anything.

有什么作用findById,是否有相关文档?我用谷歌搜索了一下,但没有找到任何东西。

回答by JohnnyHK

findByIdis 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 idvalue to the type of _idas 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()教程的更多信息。