Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between Model.findOne() & Model.findById() in Mongoose?

Consider we are searching a document from MongoDB based on the _id value. Which one of the following code is efficient ?

  1. ModelObj.findById(IdValue).exec(callback);

  2. ModelObj.findOne({ '_id': IdValue}).exec(callback);

I feel ModelObj.findById() is efficient, but what are the supportive reasons or How is it efficient?

like image 776
Amol M Kulkarni Avatar asked Jan 10 '13 10:01

Amol M Kulkarni


People also ask

What is the difference between findById and findOne?

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

What is the difference between find and findOne in mongoose?

findOne() - if query matches, first document is returned, otherwise null. find() - no matter the number of documents matched, a cursor is returned, never null.

Is findById faster than findOne?

Outside the context of your use case, findOne is likely insignificantly faster when provided valid ObjectIds, in the sense that passing an invalid ID through . findOne({ _id }) will not ensure _id is a valid ObjectId.

What is findOne in mongoose?

Mongoose | findOne() Function The findOne() function is used to find one document according to the condition. If multiple documents match the condition, then it returns the first document satisfying the condition.


1 Answers

findById is just a convenience function that does exactly the same thing as the findOne call you show.

Here's the source:

Model.findById = function findById (id, fields, options, callback) {   return this.findOne({ _id: id }, fields, options, callback); }; 
like image 108
JohnnyHK Avatar answered Sep 21 '22 16:09

JohnnyHK