Consider we are searching a document from MongoDB based on the _id value. Which one of the following code is efficient ?
ModelObj.findById(IdValue).exec(callback);ModelObj.findOne({ '_id': IdValue}).exec(callback);
I feel ModelObj.findById() is efficient, but what are the supportive reasons or How is it efficient?
4 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); }; 0findById(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 }).
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); }; findById(id) is just syntactic sugar of the find({_id : id}) or findOne({_id: id})
Using .findOne makes the database look through its records checking each bson document to find the relevant variable and then check the value, if mongo knows its looking for the internally indexed _id field it doesn't have to look through each document
1