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?
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 }).
findOne() - if query matches, first document is returned, otherwise null. find() - no matter the number of documents matched, a cursor is returned, never null.
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.
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.
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); };
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With