What is the difference between Model.find() and Query.prototype.find() in Mongoose? They both seem to do the same thing, return a Query instance. Is there any difference between them at all? Should I use one vs the other? My apologies if questions seem too simple. I'm not new to programming but new to JavaScript.
-
1Does this answer your question? [difference between Query and Model mongoose](https://stackoverflow.com/questions/53437031/difference-between-query-and-model-mongoose) – Mathieu Guyot Apr 07 '23 at 13:03
1 Answers
From the queries documentation, we know:
Mongoose models provide several static helper functions for CRUD operations. Each of these functions returns a mongoose
Query
object.
Model.find()
method is just a wrapper for Query.prototype.find()
method. These methods like Model.deleteOne()
,
Model.find()
that are often used on the Model encapsulate several method calls on the query object, which is more convenient to use
Model.find()
source code, see 7.1.1/lib/model.js#L2045
Model.find = function find(conditions, projection, options) {
_checkContext(this, 'find');
if (typeof arguments[0] === 'function' || typeof arguments[1] === 'function' || typeof arguments[2] === 'function' || typeof arguments[3] === 'function') {
throw new MongooseError('Model.find() no longer accepts a callback');
}
const mq = new this.Query({}, {}, this, this.$__collection);
mq.select(projection);
mq.setOptions(options);
return mq.find(conditions);
};
this.Query
is the subclass of the Query
class, see 7.1.1/lib/model.js#L4620
const Query = require('./query');
// ...
model.Query = function() {
Query.apply(this, arguments);
};
Object.setPrototypeOf(model.Query.prototype, Query.prototype);
How does the inheritance work? See Pseudoclassical inheritance using Object.setPrototypeOf()
It creates a query instance and calls Query.prototype.select() and Query.prototype.setOptions() to set the projection
and options
for query. In the end, call Query.prototype.find() method.

- 88,126
- 95
- 281
- 483
-
"*`this.Query` is the `Query` class*" - actually it's a subclass of `Query` – Bergi May 16 '23 at 08:37