什么是 findByID?

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

但是为了使它工作,我必须使用“ findById”函数,如下所示。

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


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

UserModel是猫鼬模型。我在前面声明了模式 UserSchema。所以我认为 UserModel.findById()是猫鼬模型的一种方法?

提问

findById是做什么的? 有相关的文档吗? 我在谷歌上搜索了一下,但是没有找到任何东西。

143540 次浏览

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.

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).

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).

If the schema of id is not of type ObjectId you cannot operate with function : findbyId()

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 }).

You can read more about findById() on the Mongoose docs and this findById() tutorial.