Query

Connection

Model

QueryCursor

AggregationCursor

Virtualtype

Array

DocumentArrayPath


Parameters
  • [options] «Object»
  • [model] «Object»
  • [conditions] «Object»
  • [collection] «Object» Mongoose collection

Query constructor used for building queries. You do not need to instantiate a directly. Instead use Model functions like Model.find().

Example:


Parameters
  • js «String|Function» javascript string or function
Returns:
  • «Query» this

Specifies a javascript function or expression to pass to MongoDBs query system.

Example

  1. query.$where('this.comments.length === 10 || this.name.length === 5')
  2. // or
  3. query.$where(function () {
  4. return this.comments.length === 10 || this.name.length === 5;
  5. })

NOTE:

Only use $where when you have a condition that cannot be met using other MongoDB operators like $lt. Be sure to read about all of its caveats before using.


Query.prototype.Symbol.asyncIterator()

Returns an asyncIterator for use with This function only works for find() queries. You do not need to call this function explicitly, the JavaScript runtime will call it for you.

Example

  1. for await (const doc of Model.aggregate([{ $sort: { name: 1 } }])) {
  2. console.log(doc.name);
  3. }

Node.js 10.x supports async iterators natively without any flags. You can enable async iterators in Node.js 8.x using the .

Note: This function is not if Symbol.asyncIterator is undefined. If Symbol.asyncIterator is undefined, that means your Node.js version does not support async iterators.


Parameters
  • [path] «String»
  • val «Array»

Specifies an $all query condition.

When called with one argument, the most recent path passed to where() is used.

Example:

  1. MyModel.find().where('pets').all(['dog', 'cat', 'ferret']);
  2. // Equivalent:
  3. MyModel.find().all('pets', ['dog', 'cat', 'ferret']);

Parameters
  • [v] «Boolean» Enable/disable allowDiskUse. If called with 0 arguments, sets allowDiskUse: true
Returns:
  • «Query» this

Sets the allowDiskUse option, which allows the MongoDB server to use more than 100 MB for this query’s sort(). This option can let you work around QueryExceededMemoryLimitNoDiskUseAllowed errors from the MongoDB server.

Note that this option requires MongoDB server >= 4.4. Setting this option is a no-op for MongoDB 4.2 and earlier.

Calling query.allowDiskUse(v) is equivalent to query.setOptions({ allowDiskUse: v })

Example:

  1. await query.find().sort({ name: 1 }).allowDiskUse(true);
  2. // Equivalent:
  3. await query.find().sort({ name: 1 }).allowDiskUse();

Parameters
  • array «Array» array of conditions
Returns:
  • «Query» this

Specifies arguments for a $and condition.

Example

  1. query.and([{ color: 'green' }, { status: 'ok' }])

Query.prototype.batchSize()

Parameters
  • val «Number»

Specifies the batchSize option.

Example

  1. query.batchSize(100)

Note

Cannot be used with distinct()


Parameters
  • val «Object»
  • Upper «[Array]» Right Coords
Returns:
  • «Query» this

Specifies a $box condition

Example

  1. const lowerLeft = [40.73083, -73.99756]
  2. const upperRight= [40.741404, -73.988135]
  3. query.where('loc').within().box(lowerLeft, upperRight)
  4. query.box({ ll : lowerLeft, ur : upperRight })

Query.prototype.cast()

Parameters
  • [model] «Model» the model to cast to. If not set, defaults to this.model

  • [obj] «Object»

Returns:
  • «Object»

Casts this query to the schema of model

Note

If obj is present, it is cast instead of this query.


Parameters
  • [reject] «Function»
Returns:
  • «Promise»

Executes the query returning a Promise which will be resolved with either the doc(s) or rejected with the error. Like .then(), but only takes a rejection handler.

More about Promise catch() in JavaScript.


Query.prototype.center()

DEPRECATED Alias for

Deprecated. Use circle instead.


Query.prototype.centerSphere()

Parameters
  • [path] «String»
  • val «Object»
Returns:
  • «Query» this

DEPRECATED Specifies a $centerSphere condition

Deprecated. Use instead.

Example

  1. const area = { center: [50, 50], radius: 10 };
  2. query.where('loc').within().centerSphere(area);

Query.prototype.circle()

Parameters
  • [path] «String»
  • area «Object»
Returns:
  • «Query» this

Specifies a $center or $centerSphere condition.

Example

  1. const area = { center: [50, 50], radius: 10, unique: true }
  2. query.where('loc').within().circle(area)
  3. // alternatively
  4. query.circle('loc', area);
  5. // spherical calculations
  6. const area = { center: [50, 50], radius: 10, unique: true, spherical: true }
  7. query.where('loc').within().circle(area)
  8. // alternatively
  9. query.circle('loc', area);

Parameters
  • value «Object»
Returns:
  • «Query» this

Adds a collation to this op (MongoDB 3.4 and up)


Parameters
  • val «String»

Specifies the comment option.

Example

  1. query.comment('login query')

Note

Cannot be used with distinct()


Query.prototype.count()

Parameters
  • [filter] «Object» count documents that match this object

  • [callback] «Function» optional params are (error, count)

Returns:
  • «Query» this

Specifies this query as a count query.

This method is deprecated. If you want to count the number of documents in a collection, e.g. count({}), use the instead. Otherwise, use the countDocuments() function instead.

Passing a callback executes the query.

This function triggers the following middleware.

  • count()

Example:

  1. const countQuery = model.where({ 'color': 'black' }).count();
  2. query.count({ color: 'black' }).count(callback)
  3. query.count({ color: 'black' }, callback)
  4. query.where('color', 'black').count(function (err, count) {
  5. if (err) return handleError(err);
  6. console.log('there are %d kittens', count);
  7. })

Parameters
  • [filter] «Object» mongodb selector

  • [callback] «Function» optional params are (error, count)

Returns:
  • «Query» this

Specifies this query as a countDocuments() query. Behaves like count(), except it always does a full collection scan when passed an empty filter {}.

There are also minor differences in how countDocuments() handles $where and a couple geospatial operators. versus count().

Passing a callback executes the query.

This function triggers the following middleware.

  • countDocuments()

Example:

  1. const countQuery = model.where({ 'color': 'black' }).countDocuments();
  2. query.countDocuments({ color: 'black' }).count(callback);
  3. query.countDocuments({ color: 'black' }, callback);
  4. query.where('color', 'black').countDocuments(function(err, count) {
  5. if (err) return handleError(err);
  6. console.log('there are %d kittens', count);
  7. });

The countDocuments() function is similar to count(), but there are a few operators that countDocuments() does not support. Below are the operators that count() supports but countDocuments() does not, and the suggested replacement:


Parameters
  • [options] «Object»
Returns:
  • «QueryCursor»

Returns a wrapper around a mongodb driver cursor. A QueryCursor exposes a Streams3 interface, as well as a .next() function.

The .cursor() function triggers pre find hooks, but not post find hooks.

Example

  1. // There are 2 ways to use a cursor. First, as a stream:
  2. Thing.
  3. find({ name: /^hello/ }).
  4. cursor().
  5. on('data', function(doc) { console.log(doc); }).
  6. on('end', function() { console.log('Done!'); });
  7. // Or you can use `.next()` to manually get the next doc in the stream.
  8. // `.next()` returns a promise, so you can use promises or callbacks.
  9. const cursor = Thing.find({ name: /^hello/ }).cursor();
  10. cursor.next(function(error, doc) {
  11. console.log(doc);
  12. });
  13. // Because `.next()` returns a promise, you can use co
  14. // to easily iterate through all documents without loading them
  15. // all into memory.
  16. co(function*() {
  17. const cursor = Thing.find({ name: /^hello/ }).cursor();
  18. for (let doc = yield cursor.next(); doc != null; doc = yield cursor.next()) {
  19. console.log(doc);
  20. }
  21. });

Valid options

  • transform: optional function which accepts a mongoose document. The return value of the function will be emitted on data and returned by .next().

Query.prototype.deleteMany()

Parameters
  • [filter] «Object|Query» mongodb selector

  • [options] «Object» optional see Query.prototype.setOptions()

  • [callback] «Function» optional params are (error, mongooseDeleteResult)

Returns:
  • «Query» this

Declare and/or execute this query as a deleteMany() operation. Works like remove, except it deletes every document that matches filter in the collection, regardless of the value of single.

This function triggers deleteMany middleware.

Example

  1. await Character.deleteMany({ name: /Stark/, age: { $gte: 18 } });
  2. // Using callbacks:
  3. Character.deleteMany({ name: /Stark/, age: { $gte: 18 } }, callback);

This function calls the MongoDB driver’s . The returned promise resolves to an object that contains 3 properties:

  • ok: 1 if no errors occurred
  • deletedCount: the number of documents deleted
  • n: the number of documents deleted. Equal to deletedCount.

Example

  1. const res = await Character.deleteMany({ name: /Stark/, age: { $gte: 18 } });
  2. // `0` if no docs matched the filter, number of docs deleted otherwise
  3. res.deletedCount;

Parameters
  • [filter] «Object|Query» mongodb selector

  • [options] «Object» optional see

  • [callback] «Function» optional params are (error, mongooseDeleteResult)

Returns:
  • «Query» this

Declare and/or execute this query as a deleteOne() operation. Works like remove, except it deletes at most one document regardless of the single option.

This function triggers deleteOne middleware.

Example

  1. await Character.deleteOne({ name: 'Eddard Stark' });
  2. // Using callbacks:
  3. Character.deleteOne({ name: 'Eddard Stark' }, callback);

This function calls the MongoDB driver’s Collection#deleteOne() function. The returned resolves to an object that contains 3 properties:

  • ok: 1 if no errors occurred
  • deletedCount: the number of documents deleted
  • n: the number of documents deleted. Equal to deletedCount.

Example

  1. const res = await Character.deleteOne({ name: 'Eddard Stark' });
  2. // `1` if MongoDB deleted a doc, `0` if no docs matched the filter `{ name: ... }`
  3. res.deletedCount;

Query.prototype.distinct()

Parameters
  • [field] «String»
  • [filter] «Object|Query»
  • [callback] «Function» optional params are (error, arr)
Returns:
  • «Query» this

Declares or executes a distinct() operation.

Passing a callback executes the query.

This function does not trigger any middleware.

Example

  1. distinct(field, conditions, callback)
  2. distinct(field, conditions)
  3. distinct(field, callback)
  4. distinct(field)
  5. distinct(callback)
  6. distinct()

Parameters
  • path «String|Object|Function»
  • filter «Object|Function»
Returns:
  • «Query» this

Specifies an $elemMatch condition

Example

  1. query.elemMatch('comment', { author: 'autobot', votes: {$gte: 5}})
  2. query.where('comment').elemMatch({ author: 'autobot', votes: {$gte: 5}})
  3. query.elemMatch('comment', function (elem) {
  4. elem.where('author').equals('autobot');
  5. elem.where('votes').gte(5);
  6. })
  7. query.where('comment').elemMatch(function (elem) {
  8. elem.where({ author: 'autobot' });
  9. elem.where('votes').gte(5);
  10. })

Query.prototype.equals()

Parameters
  • val «Object»
Returns:
  • «Query» this

Specifies the complementary comparison value for paths specified with where()

Example

  1. User.where('age').equals(49);
  2. // is the same as
  3. User.where('age', 49);

Parameters
  • err «Error|null» if set, exec() will fail fast before sending the query to MongoDB
Returns:
  • «Query» this

Gets/sets the error flag on this query. If this flag is not null or undefined, the exec() promise will reject without executing.

Example:

  1. Query().error(); // Get current error value
  2. Query().error(null); // Unset the current error
  3. Query().error(new Error('test')); // `exec()` will resolve with test
  4. Schema.pre('find', function() {
  5. if (!this.getQuery().userId) {
  6. this.error(new Error('Not allowed to query without setting userId'));
  7. }
  8. });

Note that query casting runs after hooks, so cast errors will override custom errors.

Example:

  1. const TestSchema = new Schema({ num: Number });
  2. const TestModel = db.model('Test', TestSchema);
  3. TestModel.find({ num: 'not a number' }).error(new Error('woops')).exec(function(error) {
  4. // `error` will be a cast error because `num` failed to cast
  5. });

Parameters
  • [options] «Object» passed transparently to the

  • [callback] «Function» optional params are (error, count)

Returns:
  • «Query» this

Specifies this query as a estimatedDocumentCount() query. Faster than using countDocuments() for large collections because estimatedDocumentCount() uses collection metadata rather than scanning the entire collection.

estimatedDocumentCount() does not accept a filter. Model.find({ foo: bar }).estimatedDocumentCount() is equivalent to Model.find().estimatedDocumentCount()

This function triggers the following middleware.

  • estimatedDocumentCount()

Example:

  1. await Model.find().estimatedDocumentCount();

Parameters
  • [operation] «String|Function»
  • [callback] «Function» optional params depend on the function being called
Returns:
  • «Promise»

Executes the query

Examples:

  1. const promise = query.exec();
  2. const promise = query.exec('update');
  3. query.exec(callback);
  4. query.exec('find', callback);

Query.prototype.exists()

Parameters
  • [path] «String»
  • val «Boolean»
Returns:
  • «Query» this

Specifies an $exists condition

Example

  1. // { name: { $exists: true }}
  2. Thing.where('name').exists()
  3. Thing.where('name').exists(true)
  4. Thing.find().exists('name')
  5. // { name: { $exists: false }}
  6. Thing.where('name').exists(false);
  7. Thing.find().exists('name', false);

Parameters
  • [verbose] «String» The verbosity mode. Either ‘queryPlanner’, ‘executionStats’, or ‘allPlansExecution’. The default is ‘queryPlanner’
Returns:
  • «Query» this

Sets the explain option, which makes this query return detailed execution stats instead of the actual query result. This method is useful for determining what index your queries use.

Calling query.explain(v) is equivalent to query.setOptions({ explain: v })

Example:

  1. const query = new Query();
  2. const res = await query.find({ a: 1 }).explain('queryPlanner');
  3. console.log(res);

Parameters
  • [filter] «Object|ObjectId» mongodb selector. If not specified, returns all documents.

  • [callback] «Function»

Returns:
  • «Query» this

Find all documents that match selector. The result will be an array of documents.

If there are too many documents in the result to fit in memory, use Query.prototype.cursor()

Example

  1. // Using async/await
  2. const arr = await Movie.find({ year: { $gte: 1980, $lte: 1989 } });
  3. // Using callbacks
  4. Movie.find({ year: { $gte: 1980, $lte: 1989 } }, function(err, arr) {});

Parameters
  • [filter] «Object» mongodb selector

  • [projection] «Object» optional fields to return

  • [options] «Object» see

  • [callback] «Function» optional params are (error, document)

Returns:
  • «Query» this

Declares the query a findOne operation. When executed, the first found document is passed to the callback.

Passing a callback executes the query. The result of the query is a single document.

  • Note: conditions is optional, and if conditions is null or undefined, mongoose will send an empty findOne command to MongoDB, which will return an arbitrary document. If you’re querying by _id, use Model.findById() instead.

This function triggers the following middleware.

  • findOne()

Example

  1. const query = Kitten.where({ color: 'white' });
  2. query.findOne(function (err, kitten) {
  3. if (err) return handleError(err);
  4. if (kitten) {
  5. // doc may be null if no document matched
  6. }
  7. });

Parameters
  • [conditions] «Object»
  • [options] «Object»

  • [options.rawResult] «Boolean» if true, returns the

  • [options.session=null] «ClientSession» The session associated with this query. See transactions docs.

  • [options.strict] «Boolean|String» overwrites the schema’s

  • [callback] «Function» optional params are (error, document)

Returns:
  • «Query» this

Issues a MongoDB command.

Finds a matching document, removes it, and passes the found document (if any) to the callback. Executes if callback is passed.

This function triggers the following middleware.

  • findOneAndDelete()

This function differs slightly from Model.findOneAndRemove() in that findOneAndRemove() becomes a MongoDB findAndModify() command, as opposed to a findOneAndDelete() command. For most mongoose use cases, this distinction is purely pedantic. You should use findOneAndDelete() unless you have a good reason not to.

Available options

  • sort: if multiple docs are found by the conditions, sets the sort order to choose which doc to update
  • maxTimeMS: puts a time limit on the query - requires mongodb >= 2.6.0
  • rawResult: if true, resolves to the raw result from the MongoDB driver

Callback Signature

  1. function(error, doc) {
  2. // error: any errors that occurred
  3. // doc: the document before updates are applied if `new: false`, or after updates if `new = true`
  4. }

Examples

  1. A.where().findOneAndDelete(conditions, options, callback) // executes
  2. A.where().findOneAndDelete(conditions, options) // return Query
  3. A.where().findOneAndDelete(conditions, callback) // executes
  4. A.where().findOneAndDelete(conditions) // returns Query
  5. A.where().findOneAndDelete(callback) // executes
  6. A.where().findOneAndDelete() // returns Query

Query.prototype.findOneAndRemove()

Parameters
  • [conditions] «Object»
  • [options] «Object»

  • [options.rawResult] «Boolean» if true, returns the raw result from the MongoDB driver

  • [options.session=null] «ClientSession» The session associated with this query. See .

  • [options.strict] «Boolean|String» overwrites the schema’s strict mode option

  • [callback] «Function» optional params are (error, document)

Returns:
  • «Query» this

Issues a mongodb findAndModify remove command.

Finds a matching document, removes it, passing the found document (if any) to the callback. Executes if callback is passed.

This function triggers the following middleware.

  • findOneAndRemove()

Available options

  • sort: if multiple docs are found by the conditions, sets the sort order to choose which doc to update
  • maxTimeMS: puts a time limit on the query - requires mongodb >= 2.6.0
  • rawResult: if true, resolves to the raw result from the MongoDB driver

Callback Signature

  1. function(error, doc) {
  2. // error: any errors that occurred
  3. // doc: the document before updates are applied if `new: false`, or after updates if `new = true`
  4. }

Examples

  1. A.where().findOneAndRemove(conditions, options, callback) // executes
  2. A.where().findOneAndRemove(conditions, options) // return Query
  3. A.where().findOneAndRemove(conditions, callback) // executes
  4. A.where().findOneAndRemove(conditions) // returns Query
  5. A.where().findOneAndRemove(callback) // executes
  6. A.where().findOneAndRemove() // returns Query

Query.prototype.findOneAndReplace()

Parameters
  • [filter] «Object»
  • [replacement] «Object»
  • [options.rawResult] «Boolean» if true, returns the raw result from the MongoDB driver

  • [options.session=null] «ClientSession» The session associated with this query. See .

  • [options.strict] «Boolean|String» overwrites the schema’s strict mode option

  • [options.new=false] «Boolean» By default, findOneAndUpdate() returns the document as it was before update was applied. If you set new: true, findOneAndUpdate() will instead give you the object after update was applied.

  • [options.lean] «Object» if truthy, mongoose will return the document as a plain JavaScript object rather than a mongoose document. See and the Mongoose lean tutorial.

  • [options.session=null] «ClientSession» The session associated with this query. See .

  • [options.strict] «Boolean|String» overwrites the schema’s strict mode option

  • [options.omitUndefined=false] «Boolean» If true, delete any properties whose value is undefined when casting an update. In other words, if this is set, Mongoose will delete baz from the update in Model.updateOne({}, { foo: 'bar', baz: undefined }) before sending the update to the server.

  • [options.timestamps=null] «Boolean» If set to false and are enabled, skip timestamps for this update. Note that this allows you to overwrite timestamps. Does nothing if schema-level timestamps are not set.

  • [options.returnOriginal=null] «Boolean» An alias for the new option. returnOriginal: false is equivalent to new: true.

  • [callback] «Function» optional params are (error, document)

Returns:
  • «Query» this

Issues a MongoDB command.

Finds a matching document, removes it, and passes the found document (if any) to the callback. Executes if callback is passed.

This function triggers the following middleware.

  • findOneAndReplace()

Available options

  • sort: if multiple docs are found by the conditions, sets the sort order to choose which doc to update
  • maxTimeMS: puts a time limit on the query - requires mongodb >= 2.6.0
  • rawResult: if true, resolves to the

Callback Signature

  1. function(error, doc) {
  2. // error: any errors that occurred
  3. // doc: the document before updates are applied if `new: false`, or after updates if `new = true`
  4. }

Examples


Parameters
  • [filter] «Object|Query»
  • [doc] «Object»
  • [options] «Object»

  • [options.rawResult] «Boolean» if true, returns the

  • [options.strict] «Boolean|String» overwrites the schema’s strict mode option

  • [options.session=null] «ClientSession» The session associated with this query. See .

  • [options.multipleCastError] «Boolean» by default, mongoose only returns the first error that occurred in casting the query. Turn on this option to aggregate all the cast errors.

  • [options.new=false] «Boolean» By default, findOneAndUpdate() returns the document as it was before update was applied. If you set new: true, findOneAndUpdate() will instead give you the object after update was applied.

  • [options.lean] «Object» if truthy, mongoose will return the document as a plain JavaScript object rather than a mongoose document. See Query.lean() and .

  • [options.session=null] «ClientSession» The session associated with this query. See transactions docs.

  • [options.strict] «Boolean|String» overwrites the schema’s

  • [options.omitUndefined=false] «Boolean» If true, delete any properties whose value is undefined when casting an update. In other words, if this is set, Mongoose will delete baz from the update in Model.updateOne({}, { foo: 'bar', baz: undefined }) before sending the update to the server.

  • [options.timestamps=null] «Boolean» If set to false and schema-level timestamps are enabled, skip timestamps for this update. Note that this allows you to overwrite timestamps. Does nothing if schema-level timestamps are not set.

  • [options.returnOriginal=null] «Boolean» An alias for the new option. returnOriginal: false is equivalent to new: true.

  • [callback] «Function» optional params are (error, doc), unless rawResult is used, in which case params are (error, writeOpResult)

Returns:
  • «Query» this

Issues a mongodb findAndModify update command.

Finds a matching document, updates it according to the update arg, passing any options, and returns the found document (if any) to the callback. The query executes if callback is passed.

This function triggers the following middleware.

  • findOneAndUpdate()

Available options

  • new: bool - if true, return the modified document rather than the original. defaults to false (changed in 4.0)
  • upsert: bool - creates the object if it doesn’t exist. defaults to false.
  • fields: {Object|String} - Field selection. Equivalent to .select(fields).findOneAndUpdate()
  • sort: if multiple docs are found by the conditions, sets the sort order to choose which doc to update
  • maxTimeMS: puts a time limit on the query - requires mongodb >= 2.6.0
  • runValidators: if true, runs update validators on this command. Update validators validate the update operation against the model’s schema.
  • setDefaultsOnInsert: if this and upsert are true, mongoose will apply the specified in the model’s schema if a new document is created. This option only works on MongoDB >= 2.4 because it relies on MongoDB’s $setOnInsert operator.
  • rawResult: if true, returns the
  • (string) if set to ‘query’ and runValidators is on, this will refer to the query in custom validator functions that update validation runs. Does nothing if runValidators is false.

Callback Signature

  1. function(error, doc) {
  2. // error: any errors that occurred
  3. // doc: the document before updates are applied if `new: false`, or after updates if `new = true`
  4. }

Examples

  1. query.findOneAndUpdate(conditions, update, options, callback) // executes
  2. query.findOneAndUpdate(conditions, update, options) // returns Query
  3. query.findOneAndUpdate(conditions, update, callback) // executes
  4. query.findOneAndUpdate(conditions, update) // returns Query
  5. query.findOneAndUpdate(update, callback) // returns Query
  6. query.findOneAndUpdate(update) // returns Query
  7. query.findOneAndUpdate(callback) // executes
  8. query.findOneAndUpdate() // returns Query

Parameters
  • object «Object» Must contain a type property which is a String and a coordinates property which is an Array. See the examples.
Returns:
  • «Query» this

Specifies a $geometry condition

Example

  1. const polyA = [[[ 10, 20 ], [ 10, 40 ], [ 30, 40 ], [ 30, 20 ]]]
  2. query.where('loc').within().geometry({ type: 'Polygon', coordinates: polyA })
  3. // or
  4. const polyB = [[ 0, 0 ], [ 1, 1 ]]
  5. query.where('loc').within().geometry({ type: 'LineString', coordinates: polyB })
  6. // or
  7. const polyC = [ 0, 0 ]
  8. query.where('loc').within().geometry({ type: 'Point', coordinates: polyC })
  9. // or
  10. query.where('loc').intersects().geometry({ type: 'Point', coordinates: polyC })

The argument is assigned to the most recent path passed to where().

NOTE:

geometry() must come after either intersects() or within().

The object argument must contain type and coordinates properties. - type {String} - coordinates {Array}


Parameters
  • path «String|Object» path or object of key/value pairs to get
Returns:
  • «Query» this

For update operations, returns the value of a path in the update’s $set. Useful for writing getters/setters that can work with both update operations and save().

Example:

  1. const query = Model.updateOne({}, { $set: { name: 'Jean-Luc Picard' } });
  2. query.get('name'); // 'Jean-Luc Picard'

Query.prototype.getFilter()

Returns:
  • «Object» current query filter

Returns the current query filter (also known as conditions) as a POJO.

Example:

  1. const query = new Query();
  2. query.find({ a: 1 }).where('b').gt(2);
  3. query.getFilter(); // { a: 1, b: { $gt: 2 } }

Returns:
  • «Object» the options

Gets query options.

Example:

  1. const query = new Query();
  2. query.limit(10);
  3. query.setOptions({ maxTimeMS: 1000 })
  4. query.getOptions(); // { limit: 10, maxTimeMS: 1000 }

Returns:
  • «Array» an array of strings representing populated paths

Gets a list of paths to be populated by this query

Example:

  1. bookSchema.pre('findOne', function() {
  2. let keys = this.getPopulatedPaths(); // ['author']
  3. });
  4. ...
  5. Book.findOne({}).populate('author');

Example:

  1. // Deep populate
  2. const q = L1.find().populate({
  3. path: 'level2',
  4. populate: { path: 'level3' }
  5. });
  6. q.getPopulatedPaths(); // ['level2', 'level2.level3']

Query.prototype.getQuery()

Returns:
  • «Object» current query filter

Returns the current query filter. Equivalent to getFilter().

You should use getFilter() instead of getQuery() where possible. getQuery() will likely be deprecated in a future release.

Example:

  1. const query = new Query();
  2. query.find({ a: 1 }).where('b').gt(2);
  3. query.getQuery(); // { a: 1, b: { $gt: 2 } }

Query.prototype.getUpdate()

Returns:
  • «Object» current update operations

Returns the current update operations as a JSON object.

Example:

  1. const query = new Query();
  2. query.update({}, { $set: { a: 5 } });
  3. query.getUpdate(); // { $set: { a: 5 } }

Query.prototype.gt()

Parameters
  • [path] «String»
  • val «Number»

Specifies a $gt query condition.

When called with one argument, the most recent path passed to where() is used.

Example

  1. Thing.find().where('age').gt(21)
  2. // or
  3. Thing.find().gt('age', 21)

Query.prototype.gte()

Parameters
  • [path] «String»
  • val «Number»

Specifies a $gte query condition.

When called with one argument, the most recent path passed to where() is used.


Parameters
  • val «Object» a hint object
Returns:
  • «Query» this

Sets query hints.

Example

  1. query.hint({ indexA: 1, indexB: -1})

Note

Cannot be used with distinct()


Parameters
  • [path] «String»
  • val «Array»

Specifies an $in query condition.

When called with one argument, the most recent path passed to where() is used.


Query.prototype.intersects()

Parameters
  • [arg] «Object»
Returns:
  • «Query» this

Declares an intersects query for geometry().

Example

  1. query.where('path').intersects().geometry({
  2. type: 'LineString'
  3. , coordinates: [[180.0, 11.0], [180, 9.0]]
  4. })
  5. query.where('path').intersects({
  6. type: 'LineString'
  7. , coordinates: [[180.0, 11.0], [180, 9.0]]
  8. })

NOTE:

MUST be used after where().

NOTE:

In Mongoose 3.7, intersects changed from a getter to a function. If you need the old syntax, use this.


Query.prototype.j()

Parameters
  • val «boolean»
Returns:
  • «Query» this

Requests acknowledgement that this operation has been persisted to MongoDB’s on-disk journal.

  • deleteOne()
  • deleteMany()
  • findOneAndDelete()
  • findOneAndReplace()
  • findOneAndUpdate()
  • remove()
  • update()
  • updateOne()
  • updateMany()

Defaults to the schema’s

Example:

  1. await mongoose.model('Person').deleteOne({ name: 'Ned Stark' }).j(true);

Query.prototype.lean()

Parameters
  • bool «Boolean|Object» defaults to true
Returns:
  • «Query» this

Sets the lean option.

Documents returned from queries with the lean option enabled are plain javascript objects, not . They have no save method, getters/setters, virtuals, or other Mongoose features.

Example:

  1. new Query().lean() // true
  2. new Query().lean(true)
  3. new Query().lean(false)
  4. const docs = await Model.find().lean();
  5. docs[0] instanceof mongoose.Document; // false

, especially when combined with cursors.

If you need virtuals, getters/setters, or defaults with lean(), you need to use a plugin. See:


Parameters
  • val «Number»

Specifies the maximum number of documents the query will return.

Example

  1. query.limit(20)

Note

Cannot be used with distinct()


Query.prototype.lt()

Parameters
  • [path] «String»
  • val «Number»

Specifies a $lt query condition.

When called with one argument, the most recent path passed to where() is used.


Parameters
  • [path] «String»
  • val «Number»

Specifies a $lte query condition.

When called with one argument, the most recent path passed to where() is used.


Query.prototype.map()

Parameters
  • fn «Function» function to run to transform the query result
Returns:
  • «Query» this

Runs a function fn and treats the return value of fn as the new value for the query to resolve to.

Any functions you pass to map() will run after any post hooks.

Example:

  1. const res = await MyModel.findOne().map(res => {
  2. // Sets a `loadedAt` property on the doc that tells you the time the
  3. // document was loaded.
  4. return res == null ?
  5. res :
  6. Object.assign(res, { loadedAt: new Date() });
  7. });

Parameters
  • [path] «String»
  • val «Number»

Specifies a maxDistance query condition.

When called with one argument, the most recent path passed to where() is used.


Query.prototype.maxScan()

Parameters
  • val «Number»

Specifies the maxScan option.

Example

  1. query.maxScan(100)

Note

Cannot be used with distinct()


Parameters
  • [ms] «Number» The number of milliseconds
Returns:
  • «Query» this

Sets the maxTimeMS option. This will tell the MongoDB server to abort if the query or write op has been running for more than ms milliseconds.

Calling query.maxTimeMS(v) is equivalent to query.setOptions({ maxTimeMS: v })

Example:

  1. const query = new Query();
  2. // Throws an error 'operation exceeded time limit' as long as there's
  3. // >= 1 doc in the queried collection
  4. const res = await query.find({ $where: 'sleep(1000) || true' }).maxTimeMS(100);

DEPRECATED Alias of maxScan


Parameters
  • source «Query|Object»
Returns:
  • «Query» this

Merges another Query or conditions object into this one.

When a Query is passed, conditions, field selection and options are merged.


Parameters
  • [path] «String»
  • val «Array» must be of length 2, first element is divisor, 2nd element is remainder.
Returns:
  • «Query» this

Specifies a $mod condition, filters documents for documents whose path property is a number that is equal to remainder modulo divisor.

Example

  1. // All find products whose inventory is odd
  2. Product.find().where('inventory').mod([2, 1]);
  3. // This syntax is a little strange, but supported.
  4. Product.find().where('inventory').mod(2, 1);

Query.prototype.model

Type:
  • «property»

The model this query is associated with.

Example:

  1. const q = MyModel.find();
  2. q.model === MyModel; // true

Query.prototype.mongooseOptions()

Parameters
  • options «Object» if specified, overwrites the current options
Returns:
  • «Object» the options

Getter/setter around the current mongoose-specific options for this query Below are the current Mongoose-specific options.

  • populate: an array representing what paths will be populated. Should have one entry for each call to
  • lean: if truthy, Mongoose will not hydrate any documents that are returned from this query. See for more information.
  • strict: controls how Mongoose handles keys that aren’t in the schema for updates. This option is true by default, which means Mongoose will silently strip any paths in the update that aren’t in the schema. See the strict mode docs for more information.
  • strictQuery: controls how Mongoose handles keys that aren’t in the schema for the query filter. This option is false by default for backwards compatibility, which means Mongoose will allow Model.find({ foo: 'bar' }) even if foo is not in the schema. See the for more information.
  • useFindAndModify: used to work around the findAndModify() deprecation warning
  • omitUndefined: delete any properties whose value is undefined when casting an update. In other words, if this is set, Mongoose will delete baz from the update in Model.updateOne({}, { foo: 'bar', baz: undefined }) before sending the update to the server.
  • nearSphere: use $nearSphere instead of near(). See the

Mongoose maintains a separate object for internal options because Mongoose sends Query.prototype.options to the MongoDB server, and the above options are not relevant for the MongoDB server.


Parameters
  • [path] «String»
  • val «any»

Specifies a $ne query condition.

When called with one argument, the most recent path passed to where() is used.


Query.prototype.near()

Parameters
  • [path] «String»
  • val «Object»
Returns:
  • «Query» this

Specifies a $near or $nearSphere condition

These operators return documents sorted by distance.

Example

  1. query.where('loc').near({ center: [10, 10] });
  2. query.where('loc').near({ center: [10, 10], maxDistance: 5 });
  3. query.where('loc').near({ center: [10, 10], maxDistance: 5, spherical: true });
  4. query.near('loc', { center: [10, 10], maxDistance: 5 });

DEPRECATED Specifies a $nearSphere condition

Example

  1. query.where('loc').nearSphere({ center: [10, 10], maxDistance: 5 });

Deprecated. Use query.near() instead with the spherical option set to true.

Example

  1. query.where('loc').near({ center: [10, 10], spherical: true });

Parameters
  • [path] «String»
  • val «Array»

Specifies an $nin query condition.

When called with one argument, the most recent path passed to where() is used.


Query.prototype.nor()

Parameters
  • array «Array» array of conditions
Returns:
  • «Query» this

Specifies arguments for a $nor condition.

Example

  1. query.nor([{ color: 'green' }, { status: 'ok' }])

Parameters
  • array «Array» array of conditions
Returns:
  • «Query» this

Specifies arguments for an $or condition.

Example

  1. query.or([{ color: 'red' }, { status: 'emergency' }])

Query.prototype.orFail()

Parameters
  • [err] «Function|Error» optional error to throw if no docs match filter. If not specified, orFail() will throw a DocumentNotFoundError
Returns:
  • «Query» this

Make this query throw an error if no documents match the given filter. This is handy for integrating with async/await, because orFail() saves you an extra if statement to check if no document was found.

Example:

  1. // Throws if no doc returned
  2. await Model.findOne({ foo: 'bar' }).orFail();
  3. // Throws if no document was updated
  4. await Model.updateOne({ foo: 'bar' }, { name: 'test' }).orFail();
  5. // Throws "No docs found!" error if no docs match `{ foo: 'bar' }`
  6. await Model.find({ foo: 'bar' }).orFail(new Error('No docs found!'));
  7. // Throws "Not found" error if no document was found
  8. await Model.findOneAndUpdate({ foo: 'bar' }, { name: 'test' }).
  9. orFail(() => Error('Not found'));

Parameters
  • [path] «String|Array»

  • [coordinatePairs…] «Array|Object»

Returns:
  • «Query» this

Specifies a $polygon condition

Example

  1. query.where('loc').within().polygon([10,20], [13, 25], [7,15])
  2. query.polygon('loc', [10,20], [13, 25], [7,15])

Parameters
  • path «Object|String» either the path to populate or an object specifying all parameters

  • [select] «Object|String» Field selection for the population query

  • [model] «Model» The model you wish to use for population. If not specified, populate will look up the model by the name in the Schema’s ref field.

  • [match] «Object» Conditions for the population query

  • [options] «Object» Options for the population query (sort, etc)

  • [options.path=null] «String» The path to populate.

  • [options.retainNullValues=false] «boolean» by default, Mongoose removes null and undefined values from populated arrays. Use this option to make populate() retain null and undefined array entries.

  • [options.getters=false] «boolean» if true, Mongoose will call any getters defined on the localField. By default, Mongoose gets the raw value of localField. For example, you would need to set this option to true if you wanted to add a lowercase getter to your localField.

  • [options.clone=false] «boolean» When you do BlogPost.find().populate('author'), blog posts with the same author will share 1 copy of an author doc. Enable this option to make Mongoose clone populated docs before assigning them.

  • [options.match=null] «Object|Function» Add an additional filter to the populate query. Can be a filter object containing , or a function that returns a filter object.

  • [options.transform=null] «Function» Function that Mongoose will call on every populated document that allows you to transform the populated document.

  • [options.options=null] «Object» Additional options like limit and lean.

Returns:
  • «Query» this

Specifies paths which should be populated with other documents.

Example:

  1. let book = await Book.findOne().populate('authors');
  2. book.title; // 'Node.js in Action'
  3. book.authors[0].name; // 'TJ Holowaychuk'
  4. book.authors[1].name; // 'Nathan Rajlich'
  5. let books = await Book.find().populate({
  6. path: 'authors',
  7. // `match` and `sort` apply to the Author model,
  8. // not the Book model. These options do not affect
  9. // which documents are in `books`, just the order and
  10. // contents of each book document's `authors`.
  11. match: { name: new RegExp('.*h.*', 'i') },
  12. sort: { name: -1 }
  13. });
  14. books[0].title; // 'Node.js in Action'
  15. // Each book's `authors` are sorted by name, descending.
  16. books[0].authors[0].name; // 'TJ Holowaychuk'
  17. books[0].authors[1].name; // 'Marc Harter'
  18. books[1].title; // 'Professional AngularJS'
  19. // Empty array, no authors' name has the letter 'h'
  20. books[1].authors; // []

Paths are populated after the query executes and a response is received. A separate query is then executed for each path specified for population. After a response for each query has also been returned, the results are passed to the callback.


Parameters
  • fn «Function»
Returns:
  • «Promise»

Add post middleware to this query instance. Doesn’t affect other queries.

Example:

  1. const q1 = Question.find({ answer: 42 });
  2. q1.post(function middleware() {
  3. console.log(this.getFilter());
  4. });
  5. await q1.exec(); // Prints "{ answer: 42 }"
  6. // Doesn't print anything, because `middleware()` is only
  7. // registered on `q1`.
  8. await Question.find({ answer: 42 });

Parameters
  • fn «Function»
Returns:
  • «Promise»

Add pre middleware to this query instance. Doesn’t affect other queries.

Example:

  1. const q1 = Question.find({ answer: 42 });
  2. q1.pre(function middleware() {
  3. console.log(this.getFilter());
  4. });
  5. await q1.exec(); // Prints "{ answer: 42 }"
  6. // Doesn't print anything, because `middleware()` is only
  7. // registered on `q1`.
  8. await Question.find({ answer: 42 });

Parameters
  • arg «Object|null»
Returns:
  • «Object» the current projection

Get/set the current projection (AKA fields). Pass null to remove the current projection.

Unlike projection(), the select() function modifies the current projection in place. This function overwrites the existing projection.

Example:

  1. const q = Model.find();
  2. q.projection(); // null
  3. q.select('a b');
  4. q.projection(); // { a: 1, b: 1 }
  5. q.projection({ c: 1 });
  6. q.projection(); // { c: 1 }
  7. q.projection(null);
  8. q.projection(); // null

Query.prototype.read()

Parameters
  • pref «String» one of the listed preference options or aliases

  • [tags] «Array» optional tags for this query

Returns:
  • «Query» this

Determines the MongoDB nodes from which to read.

Preferences:

  1. primary - (default) Read from primary only. Operations will produce an error if primary is unavailable. Cannot be combined with tags.
  2. secondary Read from secondary if available, otherwise error.
  3. primaryPreferred Read from primary if available, otherwise a secondary.
  4. secondaryPreferred Read from a secondary if available, otherwise read from the primary.
  5. nearest All operations read from among the nearest candidates, but unlike other modes, this option will include both the primary and all secondaries in the random selection.

Aliases

Example:

  1. new Query().read('primary')
  2. new Query().read('p') // same as primary
  3. new Query().read('primaryPreferred')
  4. new Query().read('pp') // same as primaryPreferred
  5. new Query().read('secondary')
  6. new Query().read('s') // same as secondary
  7. new Query().read('secondaryPreferred')
  8. new Query().read('sp') // same as secondaryPreferred
  9. new Query().read('nearest')
  10. new Query().read('n') // same as nearest
  11. // read from secondaries with matching tags
  12. new Query().read('s', [{ dc:'sf', s: 1 },{ dc:'ma', s: 2 }])

Query.prototype.readConcern()

Parameters
  • level «String» one of the listed read concern level or their aliases
Returns:
  • «Query» this

Sets the readConcern option for the query.

Example:

  1. new Query().readConcern('local')
  2. new Query().readConcern('l') // same as local
  3. new Query().readConcern('available')
  4. new Query().readConcern('a') // same as available
  5. new Query().readConcern('majority')
  6. new Query().readConcern('m') // same as majority
  7. new Query().readConcern('linearizable')
  8. new Query().readConcern('lz') // same as linearizable
  9. new Query().readConcern('snapshot')
  10. new Query().readConcern('s') // same as snapshot

Read Concern Level:

  1. local MongoDB 3.2+ The query returns from the instance with no guarantee guarantee that the data has been written to a majority of the replica set members (i.e. may be rolled back).
  2. available MongoDB 3.6+ The query returns from the instance with no guarantee guarantee that the data has been written to a majority of the replica set members (i.e. may be rolled back).
  3. majority MongoDB 3.2+ The query returns the data that has been acknowledged by a majority of the replica set members. The documents returned by the read operation are durable, even in the event of failure.
  4. linearizable MongoDB 3.4+ The query returns data that reflects all successful majority-acknowledged writes that completed prior to the start of the read operation. The query may wait for concurrently executing writes to propagate to a majority of replica set members before returning results.
  5. snapshot MongoDB 4.0+ Only available for operations within multi-document transactions. Upon transaction commit with write concern "majority", the transaction operations are guaranteed to have read from a snapshot of majority-committed data.

Aliases

  1. l local
  2. a available
  3. m majority
  4. lz linearizable
  5. s snapshot

Read more about how to use read concern .


Parameters
  • [path] «String»
  • val «String|RegExp»

Specifies a $regex query condition.

When called with one argument, the most recent path passed to where() is used.


Query.prototype.remove()

Parameters
  • [filter] «Object|Query» mongodb selector

  • [callback] «Function» optional params are (error, mongooseDeleteResult)

Returns:
  • «Query» this

Declare and/or execute this query as a remove() operation. remove() is deprecated, you should use or deleteMany() instead.

This function does not trigger any middleware

Example

  1. Character.remove({ name: /Stark/ }, callback);

This function calls the MongoDB driver’s Collection#remove() function. The returned resolves to an object that contains 3 properties:

  • ok: 1 if no errors occurred
  • deletedCount: the number of documents deleted
  • n: the number of documents deleted. Equal to deletedCount.

Example

  1. const res = await Character.remove({ name: /Stark/ });
  2. // Number of docs deleted
  3. res.deletedCount;

Note

Calling remove() creates a Mongoose query, and a query does not execute until you either pass a callback, call , or call Query#exec().

  1. // not executed
  2. const query = Character.remove({ name: /Stark/ });
  3. // executed
  4. Character.remove({ name: /Stark/ }).remove(callback);
  5. // executed without a callback
  6. Character.exec();

Query.prototype.replaceOne()

Parameters
  • [filter] «Object»
  • [doc] «Object» the update command

  • [options] «Object»

  • [options.multipleCastError] «Boolean» by default, mongoose only returns the first error that occurred in casting the query. Turn on this option to aggregate all the cast errors.

  • [options.omitUndefined=false] «Boolean» If true, delete any properties whose value is undefined when casting an update. In other words, if this is set, Mongoose will delete baz from the update in Model.updateOne({}, { foo: 'bar', baz: undefined }) before sending the update to the server.

  • [options.strict] «Boolean|String» overwrites the schema’s strict mode option

  • [options.upsert=false] «Boolean» if true, and no documents found, insert a new document

  • [options.writeConcern=null] «Object» sets the for replica sets. Overrides the schema-level write concern

  • [options.timestamps=null] «Boolean» If set to false and are enabled, skip timestamps for this update. Does nothing if schema-level timestamps are not set.

  • [callback] «Function» params are (error, writeOpResult)

Returns:
  • «Query» this

Declare and/or execute this query as a replaceOne() operation. Same as update(), except MongoDB will replace the existing document and will not accept any operators ($set, etc.)

Note replaceOne will not fire update middleware. Use pre('replaceOne') and post('replaceOne') instead.

Example:

  1. const res = await Person.replaceOne({ _id: 24601 }, { name: 'Jean Valjean' });
  2. res.n; // Number of documents matched
  3. res.nModified; // Number of documents modified

This function triggers the following middleware.

  • replaceOne()

Query.prototype.select()

Parameters
  • arg «Object|String|Array<String>»
Returns:
  • «Query» this

Specifies which document fields to include or exclude (also known as the query “projection”)

When using string syntax, prefixing a path with - will flag that path as excluded. When a path does not have the - prefix, it is included. Lastly, if a path is prefixed with +, it forces inclusion of the path, which is useful for paths excluded at the .

A projection must be either inclusive or exclusive. In other words, you must either list the fields to include (which excludes all others), or list the fields to exclude (which implies all other fields are included). The _id field is the only exception because MongoDB includes it by default.

Example

  1. // include a and b, exclude other fields
  2. query.select('a b');
  3. // Equivalent syntaxes:
  4. query.select(['a', 'b']);
  5. query.select({ a: 1, b: 1 });
  6. // exclude c and d, include other fields
  7. query.select('-c -d');
  8. // Use `+` to override schema-level `select: false` without making the
  9. // projection inclusive.
  10. const schema = new Schema({
  11. foo: { type: String, select: false },
  12. bar: String
  13. });
  14. // ...
  15. query.select('+foo'); // Override foo's `select: false` without excluding `bar`
  16. // or you may use object notation, useful when
  17. // you have keys already prefixed with a "-"
  18. query.select({ a: 1, b: 1 });
  19. query.select({ c: 0, d: 0 });

Returns:
  • «Boolean»

Determines if field selection has been made.


Query.prototype.selectedExclusively()

Returns:
  • «Boolean»

Determines if exclusive field selection has been made.

  1. query.selectedExclusively() // false
  2. query.select('-name')
  3. query.selectedExclusively() // true
  4. query.selectedInclusively() // false

Returns:
  • «Boolean»

Determines if inclusive field selection has been made.

  1. query.selectedInclusively() // false
  2. query.select('name')
  3. query.selectedInclusively() // true

Query.prototype.session()

Parameters
  • [session] «ClientSession» from await conn.startSession()
Returns:
  • «Query» this

Sets the associated with this query. Sessions are how you mark a query as part of a transaction.

Calling session(null) removes the session from this query.

Example:

  1. const s = await mongoose.startSession();
  2. await mongoose.model('Person').findOne({ name: 'Axl Rose' }).session(s);

Parameters
  • path «String|Object» path or object of key/value pairs to set

  • [val] «Any» the value to set

Returns:
  • «Query» this

Adds a $set to this query’s update without changing the operation. This is useful for query middleware so you can add an update regardless of whether you use updateOne(), updateMany(), findOneAndUpdate(), etc.

Example:

  1. // Updates `{ $set: { updatedAt: new Date() } }`
  2. new Query().updateOne({}, {}).set('updatedAt', new Date());
  3. new Query().updateMany({}, {}).set({ updatedAt: new Date() });

Query.prototype.setOptions()

Parameters
  • options «Object»
Returns:
  • «Query» this

Sets query options. Some options only make sense for certain operations.

Options:

The following options are only for find():

The following options are only for write operations: update(), updateOne(), updateMany(), replaceOne(), findOneAndUpdate(), and findByIdAndUpdate():

  • writeConcern
  • : If timestamps is set in the schema, set this option to false to skip timestamps for that particular update. Has no effect if timestamps is not enabled in the schema options.
  • omitUndefined: delete any properties whose value is undefined when casting an update. In other words, if this is set, Mongoose will delete baz from the update in Model.updateOne({}, { foo: 'bar', baz: undefined }) before sending the update to the server.
  • overwriteDiscriminatorKey: allow setting the discriminator key in the update. Will use the correct discriminator schema if the update changes the discriminator key.
  • overwrite: replace the entire document

The following options are only for find(), findOne(), findById(), findOneAndUpdate(), and findByIdAndUpdate():

The following options are only for all operations except update(), updateOne(), updateMany(), remove(), deleteOne(), and deleteMany():

The following options are for findOneAndUpdate() and findOneAndRemove()

The following options are for all operations


Query.prototype.setQuery()

Parameters
  • new «Object» query conditions
Returns:
  • «undefined»

Sets the query conditions to the provided JSON object.

Example:

  1. const query = new Query();
  2. query.find({ a: 1 })
  3. query.setQuery({ a: 2 });
  4. query.getQuery(); // { a: 2 }

Parameters
  • new «Object» update operation
Returns:
  • «undefined»

Sets the current update operation to new value.

Example:

  1. const query = new Query();
  2. query.update({}, { $set: { a: 5 } });
  3. query.setUpdate({ $set: { b: 6 } });
  4. query.getUpdate(); // { $set: { b: 6 } }

Query.prototype.size()

Parameters
  • [path] «String»
  • val «Number»

Specifies a $size query condition.

When called with one argument, the most recent path passed to where() is used.

Example

  1. MyModel.where('tags').size(0).exec(function (err, docs) {
  2. if (err) return handleError(err);
  3. assert(Array.isArray(docs));
  4. console.log('documents with 0 tags', docs);
  5. })

Query.prototype.skip()

Parameters
  • val «Number»

Specifies the number of documents to skip.

Example

  1. query.skip(100).limit(20)

Note

Cannot be used with distinct()


Parameters
  • v «Boolean» defaults to true
Returns:
  • «Query» this

DEPRECATED Sets the slaveOk option.

Deprecated in MongoDB 2.2 in favor of read preferences.

Example:

  1. query.slaveOk() // true
  2. query.slaveOk(true)
  3. query.slaveOk(false)

Parameters
  • [path] «String»
  • val «Number» number/range of elements to slice
Returns:
  • «Query» this

Specifies a $slice projection for an array.

Example

  1. query.slice('comments', 5)
  2. query.slice('comments', -5)
  3. query.slice('comments', [10, 5])
  4. query.where('comments').slice(5)
  5. query.where('comments').slice([-10, 5])

Query.prototype.snapshot()

Returns:
  • «Query» this

Specifies this query as a snapshot query.

Example

  1. query.snapshot() // true
  2. query.snapshot(true)
  3. query.snapshot(false)

Note

Cannot be used with distinct()


Parameters
  • arg «Object|String»
Returns:
  • «Query» this

Sets the sort order

If an object is passed, values allowed are asc, desc, ascending, descending, 1, and -1.

If a string is passed, it must be a space delimited list of path names. The sort order of each path is ascending unless the path name is prefixed with - which will be treated as descending.

Example

  1. // sort by "field" ascending and "test" descending
  2. query.sort({ field: 'asc', test: -1 });
  3. // equivalent
  4. query.sort('field -test');

Note

Cannot be used with distinct()


Parameters
  • bool «Boolean» defaults to true

  • [opts] «Object» options to set

  • [opts.numberOfRetries] «Number» if cursor is exhausted, retry this many times before giving up

  • [opts.tailableRetryInterval] «Number» if cursor is exhausted, wait this many milliseconds before retrying

Sets the tailable option (for use with capped collections).

Example

  1. query.tailable() // true
  2. query.tailable(true)
  3. query.tailable(false)

Note

Cannot be used with distinct()


Query.prototype.then()

Parameters
  • [resolve] «Function»
  • [reject] «Function»
Returns:
  • «Promise»

Executes the query returning a Promise which will be resolved with either the doc(s) or rejected with the error.

More about .


Returns:
  • «Query» subclass-of-Query

Converts this query to a customized, reusable query constructor with all arguments and options retained.

Example

  1. // Create a query for adventure movies and read from the primary
  2. // node in the replica-set unless it is down, in which case we'll
  3. // read from a secondary node.
  4. const query = Movie.find({ tags: 'adventure' }).read('primaryPreferred');
  5. // create a custom Query constructor based off these settings
  6. const Adventure = query.toConstructor();
  7. // Adventure is now a subclass of mongoose.Query and works the same way but with the
  8. // default query parameters and options set.
  9. Adventure().exec(callback)
  10. // further narrow down our query results while still using the previous settings
  11. Adventure().where({ name: /^Life/ }).exec(callback);
  12. // since Adventure is a stand-alone constructor we can also add our own
  13. // helper methods and getters without impacting global queries
  14. Adventure.prototype.startsWith = function (prefix) {
  15. this.where({ name: new RegExp('^' + prefix) })
  16. return this;
  17. }
  18. Object.defineProperty(Adventure.prototype, 'highlyRated', {
  19. get: function () {
  20. this.where({ rating: { $gt: 4.5 }});
  21. return this;
  22. }
  23. })
  24. Adventure().highlyRated.startsWith('Life').exec(callback)

Parameters
  • [filter] «Object»
  • [doc] «Object» the update command

  • [options] «Object»

  • [options.multipleCastError] «Boolean» by default, mongoose only returns the first error that occurred in casting the query. Turn on this option to aggregate all the cast errors.

  • [options.omitUndefined=false] «Boolean» If true, delete any properties whose value is undefined when casting an update. In other words, if this is set, Mongoose will delete baz from the update in Model.updateOne({}, { foo: 'bar', baz: undefined }) before sending the update to the server.

  • [options.strict] «Boolean|String» overwrites the schema’s

  • [options.upsert=false] «Boolean» if true, and no documents found, insert a new document

  • [options.writeConcern=null] «Object» sets the write concern for replica sets. Overrides the

  • [options.timestamps=null] «Boolean» If set to false and schema-level timestamps are enabled, skip timestamps for this update. Does nothing if schema-level timestamps are not set.

  • [callback] «Function» params are (error, writeOpResult)

Returns:
  • «Query» this

Declare and/or execute this query as an update() operation.

All paths passed that are not atomic operations will become $set ops.

This function triggers the following middleware.

  • update()

Example

  1. Model.where({ _id: id }).update({ title: 'words' })
  2. // becomes
  3. Model.where({ _id: id }).update({ $set: { title: 'words' }})

Valid options:

  • upsert (boolean) whether to create the doc if it doesn’t match (false)
  • multi (boolean) whether multiple documents should be updated (false)
  • runValidators: if true, runs on this command. Update validators validate the update operation against the model’s schema.
  • setDefaultsOnInsert: if this and upsert are true, mongoose will apply the defaults specified in the model’s schema if a new document is created. This option only works on MongoDB >= 2.4 because it relies on .
  • strict (boolean) overrides the strict option for this update
  • overwrite (boolean) disables update-only mode, allowing you to overwrite the doc (false)
  • context (string) if set to ‘query’ and runValidators is on, this will refer to the query in custom validator functions that update validation runs. Does nothing if runValidators is false.
  • read
  • writeConcern

Note

Passing an empty object {} as the doc will result in a no-op unless the overwrite option is passed. Without the overwrite option set, the update operation will be ignored and the callback executed without sending the command to MongoDB so as to prevent accidently overwritting documents in the collection.

Note

The operation is only executed when a callback is passed. To force execution without a callback, we must first call update() and then execute it by using the exec() method.

  1. const q = Model.where({ _id: id });
  2. q.update({ $set: { name: 'bob' }}).update(); // not executed
  3. q.update({ $set: { name: 'bob' }}).exec(); // executed
  4. // keys that are not [atomic](https://docs.mongodb.com/manual/tutorial/model-data-for-atomic-operations/#pattern) ops become `$set`.
  5. // this executes the same command as the previous example.
  6. q.update({ name: 'bob' }).exec();
  7. // overwriting with empty docs
  8. const q = Model.where({ _id: id }).setOptions({ overwrite: true })
  9. q.update({ }, callback); // executes
  10. // multi update with overwrite to empty doc
  11. const q = Model.where({ _id: id });
  12. q.setOptions({ multi: true, overwrite: true })
  13. q.update({ });
  14. q.update(callback); // executed
  15. // multi updates
  16. Model.where()
  17. .update({ name: /^match/ }, { $set: { arr: [] }}, { multi: true }, callback)
  18. // more multi updates
  19. Model.where()
  20. .setOptions({ multi: true })
  21. .update({ $set: { arr: [] }}, callback)
  22. // single update by default
  23. Model.where({ email: 'address@example.com' })
  24. .update({ $inc: { counter: 1 }}, callback)

API summary

  1. update(filter, doc, options, cb) // executes
  2. update(filter, doc, options)
  3. update(filter, doc, cb) // executes
  4. update(filter, doc)
  5. update(doc, cb) // executes
  6. update(doc)
  7. update(cb) // executes
  8. update(true) // executes
  9. update()

Parameters
  • [filter] «Object»
  • [update] «Object|Array» the update command

  • [options] «Object»

  • [options.multipleCastError] «Boolean» by default, mongoose only returns the first error that occurred in casting the query. Turn on this option to aggregate all the cast errors.

  • [options.omitUndefined=false] «Boolean» If true, delete any properties whose value is undefined when casting an update. In other words, if this is set, Mongoose will delete baz from the update in Model.updateOne({}, { foo: 'bar', baz: undefined }) before sending the update to the server.

  • [options.strict] «Boolean|String» overwrites the schema’s

  • [options.upsert=false] «Boolean» if true, and no documents found, insert a new document

  • [options.writeConcern=null] «Object» sets the write concern for replica sets. Overrides the

  • [options.timestamps=null] «Boolean» If set to false and schema-level timestamps are enabled, skip timestamps for this update. Does nothing if schema-level timestamps are not set.

  • [callback] «Function» params are (error, writeOpResult)

Returns:
  • «Query» this

Declare and/or execute this query as an updateMany() operation. Same as update(), except MongoDB will update all documents that match filter (as opposed to just the first one) regardless of the value of the multi option.

Note updateMany will not fire update middleware. Use pre('updateMany') and post('updateMany') instead.

Example:

  1. const res = await Person.updateMany({ name: /Stark$/ }, { isDeleted: true });
  2. res.n; // Number of documents matched
  3. res.nModified; // Number of documents modified

This function triggers the following middleware.

  • updateMany()

Query.prototype.updateOne()

Parameters
  • [filter] «Object»
  • [update] «Object|Array» the update command

  • [options] «Object»

  • [options.multipleCastError] «Boolean» by default, mongoose only returns the first error that occurred in casting the query. Turn on this option to aggregate all the cast errors.

  • [options.omitUndefined=false] «Boolean» If true, delete any properties whose value is undefined when casting an update. In other words, if this is set, Mongoose will delete baz from the update in Model.updateOne({}, { foo: 'bar', baz: undefined }) before sending the update to the server.

  • [options.strict] «Boolean|String» overwrites the schema’s strict mode option

  • [options.upsert=false] «Boolean» if true, and no documents found, insert a new document

  • [options.writeConcern=null] «Object» sets the for replica sets. Overrides the schema-level write concern

  • [options.timestamps=null] «Boolean» If set to false and are enabled, skip timestamps for this update. Note that this allows you to overwrite timestamps. Does nothing if schema-level timestamps are not set.

  • [callback] «Function» params are (error, writeOpResult)

Returns:
  • «Query» this

Declare and/or execute this query as an updateOne() operation. Same as update(), except it does not support the multi or overwrite options.

  • MongoDB will update only the first document that matches filter regardless of the value of the multi option.
  • Use replaceOne() if you want to overwrite an entire document rather than using operators like $set.

Note updateOne will not fire update middleware. Use pre('updateOne') and post('updateOne') instead.

Example:

  1. const res = await Person.updateOne({ name: 'Jean-Luc Picard' }, { ship: 'USS Enterprise' });
  2. res.n; // Number of documents matched
  3. res.nModified; // Number of documents modified

This function triggers the following middleware.

  • updateOne()

Query.prototype.use$geoWithin

Type:
  • «property»

Flag to opt out of using $geoWithin.

  1. mongoose.Query.use$geoWithin = false;

MongoDB 2.4 deprecated the use of $within, replacing it with $geoWithin. Mongoose uses $geoWithin by default (which is 100% backward compatible with $within). If you are running an older version of MongoDB, set this flag to false so your within() queries continue to work.


Parameters
  • val «String|number» 0 for fire-and-forget, 1 for acknowledged by one server, ‘majority’ for majority of the replica set, or .
Returns:
  • «Query» this

Sets the specified number of mongod servers, or tag set of mongod servers, that must acknowledge this write before this write is considered successful.

  • deleteOne()
  • deleteMany()
  • findOneAndDelete()
  • findOneAndReplace()
  • findOneAndUpdate()
  • remove()
  • update()
  • updateOne()
  • updateMany()

Defaults to the schema’s

Example:

  1. // The 'majority' option means the `deleteOne()` promise won't resolve
  2. // until the `deleteOne()` has propagated to the majority of the replica set
  3. await mongoose.model('Person').
  4. deleteOne({ name: 'Ned Stark' }).
  5. w('majority');

Query.prototype.where()

Parameters
  • [path] «String|Object»
  • [val] «any»
Returns:
  • «Query» this

Specifies a path for use with chaining.

Example

  1. // instead of writing:
  2. User.find({age: {$gte: 21, $lte: 65}}, callback);
  3. // we can instead write:
  4. User.where('age').gte(21).lte(65);
  5. // passing query conditions is permitted
  6. User.find().where({ name: 'vonderful' })
  7. // chaining
  8. User
  9. .where('age').gte(21).lte(65)
  10. .where('name', /^vonderful/i)
  11. .where('friends').slice(10)
  12. .exec(callback)

Returns:
  • «Query» this

Defines a $within or $geoWithin argument for geo-spatial queries.

Example

  1. query.where(path).within().box()
  2. query.where(path).within().circle()
  3. query.where(path).within().geometry()
  4. query.where('loc').within({ center: [50,50], radius: 10, unique: true, spherical: true });
  5. query.where('loc').within({ box: [[40.73, -73.9], [40.7, -73.988]] });
  6. query.where('loc').within({ polygon: [[],[],[],[]] });
  7. query.where('loc').within([], [], []) // polygon
  8. query.where('loc').within([], []) // box
  9. query.where('loc').within({ type: 'LineString', coordinates: [...] }); // geometry

MUST be used after where().

NOTE:

As of Mongoose 3.7, $geoWithin is always used for queries. To change this behavior, see .

NOTE:

In Mongoose 3.7, within changed from a getter to a function. If you need the old syntax, use .


Parameters
  • writeConcern «Object» the write concern value to set
Returns:
  • «Query» this

Sets the 3 write concern parameters for this query

  • w: Sets the specified number of mongod servers, or tag set of mongod servers, that must acknowledge this write before this write is considered successful.
  • j: Boolean, set to true to request acknowledgement that this operation has been persisted to MongoDB’s on-disk journal.
  • wtimeout: If , the maximum amount of time to wait for this write to propagate through the replica set before this operation fails. The default is 0, which means no timeout.
  • deleteOne()
  • deleteMany()
  • findOneAndDelete()
  • findOneAndReplace()
  • findOneAndUpdate()
  • remove()
  • update()
  • updateOne()
  • updateMany()

Defaults to the schema’s writeConcern option

Example:

  1. // The 'majority' option means the `deleteOne()` promise won't resolve
  2. // until the `deleteOne()` has propagated to the majority of the replica set
  3. await mongoose.model('Person').
  4. deleteOne({ name: 'Ned Stark' }).
  5. writeConcern({ w: 'majority' });

Parameters
  • ms «number» number of milliseconds to wait
Returns:
  • «Query» this

If w > 1, the maximum amount of time to wait for this write to propagate through the replica set before this operation fails. The default is 0, which means no timeout.

This option is only valid for operations that write to the database

  • deleteOne()
  • deleteMany()
  • findOneAndDelete()
  • findOneAndReplace()
  • findOneAndUpdate()
  • remove()
  • update()
  • updateOne()

Defaults to the schema’s writeConcern.wtimeout option

Example: