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

Amol M Kulkarni picture Amol M Kulkarni · Jan 10, 2013 · Viewed 22.1k times · Source

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?

Answer

JohnnyHK picture JohnnyHK · Jan 10, 2013

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