Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Web Technology by (47.6k 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.

2 Answers

0 votes
by (106k points)

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:

var id = "56e6dd2eb4494ed008d595bd"; 

UserModel.findById(id, function (err, user) { ... } );

Functionally, it's the same as calling:

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

0 votes
by (50.2k points)

findOne function receives a value to search a document by their _id key. This value is mainly subject to casting, so it can be a hex string or a proper ObjectId.

Related questions

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

Browse Categories

...