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.
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
is a Mongoose model. I declare the schema, UserSchema
earlier. So I suppose UserModel.findById()
is a method of the Mongoose model?
Question
What does findById
do and is there documentation on it? I googled around a bit but didn't find anything.
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.
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).
Source: Stackoverflow.com