Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Web Technology by (50.2k points)

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.

1 Answer

0 votes
by (12.7k points)
edited by

findById is a convenience method in the model that had been provided by the Mongoose to find a document using its _id. The documentation for that can be seen 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 the Mongoose will cast the provided id value to the type of _id as defined in the schema (defaulting to ObjectId).

Want to learn MongoDB from the experts, Check out this MongoDB Training in Sydney to enhance your Knowledge!

Related questions

0 votes
2 answers
0 votes
2 answers
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer

Browse Categories

...