MongoDB 通过 Mongoose JS - 什么是 findByID? [英] MongoDB via Mongoose JS - What is findByID?

查看:28
本文介绍了MongoDB 通过 Mongoose JS - 什么是 findByID?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在用 ExpressJS、PassportJS、MongoDB 和 MongooseJS 编写一个 NodeJS 服务器.我只是设法让 PassportJS 使用通过 Mongoose 获得的用户数据进行身份验证.

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.

但是为了让它工作,我必须使用如下所示的findById"函数.

But to make it work, I had to use a "findById" function like below.

var UserModel = db.model('User',UserSchema);

UserModel.findById(id, function (err, user) { < SOME CODE > } );

UserModel 是一个猫鼬模型.我之前声明了架构,UserSchema.所以我想 UserModel.findById() 是 Mongoose 模型的一个方法?

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

问题

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

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

推荐答案

findById 是 Mongoose 提供的模型上的一种便捷方法,用于通过 _id 查找文档.它的文档可以在这里找到.

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.

示例:

// Search by ObjectId
var id = "56e6dd2eb4494ed008d595bd";
UserModel.findById(id, function (err, user) { ... } );

功能上,与调用相同:

UserModel.findOne({_id: id}, function (err, user) { ... });

请注意,Mongoose 会将提供的 id 值转换为架构中定义的 _id 类型(默认为 ObjectId).

Note that Mongoose will cast the provided id value to the type of _id as defined in the schema (defaulting to ObjectId).

这篇关于MongoDB 通过 Mongoose JS - 什么是 findByID?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆