Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDB via Mongoose JS - What is findByID?

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.

like image 913
Legendre Avatar asked Sep 18 '12 19:09

Legendre


People also ask

What does findById return Mongoose?

Return value findById returns the document where the _id field matches the specified id . If the document is not found, the function returns null .

What is the difference between find findOne and findById Apis in Mongoose?

Difference between findById() & findOne(): The main difference between these two methods is how MongoDB handles the undefined value of id. If you use findOne({ _id: undefined }) it will return arbitrary documents. However, mongoose translates findById(undefined) into findOne({ _id: null }).

How do you use Find ID?

MongoDB provides a function with the name findById() which is used to retrieve the document matching the 'id' as specified by the user. In order to use findById in MongoDB, find() function is used. If no document is found matching the specified 'id', it returns null.

What is autoIndex in Mongoose?

Also note, that autoIndex does not mean that you create an index for every field. Instead, it means: Mongoose automatically calls createIndex for each defined index in your schema.


2 Answers

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

like image 196
JohnnyHK Avatar answered Sep 22 '22 15:09

JohnnyHK


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

like image 28
Dasikely Avatar answered Sep 21 '22 15:09

Dasikely