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