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


Question

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?

1
23
1/10/2013 10:22:01 AM

Accepted Answer

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);
};
42
5/18/2015 3:28:41 PM

findById(id) is almost equivalent to findOne({ _id: id }).
If you want to query by a document's _id, use findById() instead of findOne().

Both functions trigger findOne(), the only difference is how they treat undefined.
If you use findOne(), you'll see that findOne(undefined) and findOne({ _id: undefined }) are equivalent to findOne({}) and return arbitrary documents.
However, mongoose translates findById(undefined) into findOne({ _id: null }).

See https://mongoosejs.com/docs/api.html#model_Model.findById

Here's the source:

Model.findById = function findById(id, projection, options, callback) {
  if (typeof id === 'undefined') {
    id = null;
  }

  if (callback) {
    callback = this.$wrapCallback(callback);
  }

  return this.findOne({_id: id}, projection, options, callback);
};

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon