Mongoose v8.14.1: Query (original) (raw)


Query()

Parameters:

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

Example:

const query = MyModel.find(); // `query` is an instance of `Query`
query.setOptions({ lean : true });
query.collection(MyModel.collection);
query.where('age').gte(21).exec(callback);

// You can instantiate a query directly. There is no need to do
// this unless you're an advanced user with a very good reason to.
const query = new mongoose.Query();

Query.prototype.$where()

Parameters:
Returns:
See:

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

Example:

query.$where('this.comments.length === 10 || this.name.length === 5')

// or

query.$where(function () {
  return this.comments.length === 10 || this.name.length === 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.all()

Parameters:
See:

Specifies an $all query condition.

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

Example:

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

Query.prototype.allowDiskUse()

Parameters:
Returns:

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:

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

Query.prototype.and()

Parameters:
Returns:
See:

Specifies arguments for a $and condition.

Example:

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

Query.prototype.batchSize()

Parameters:
See:

Specifies the batchSize option.

Example:

query.batchSize(100)

Note:

Cannot be used with distinct()


Query.prototype.box()

Parameters:
Returns:
See:

Specifies a $box condition

Example:

const lowerLeft = [40.73083, -73.99756]
const upperRight= [40.741404,  -73.988135]

query.where('loc').within().box(lowerLeft, upperRight)
query.box({ ll : lowerLeft, ur : upperRight })

Query.prototype.cast()

Parameters:
Returns:

Casts this query to the schema of model

Note:

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


Query.prototype.catch()

Parameters:
Returns:

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~

DEPRECATED Alias for circle

Deprecated. Use circle instead.


Query.prototype.centerSphere()

~DEPRECATED~

Parameters:
Returns:
See:

DEPRECATED Specifies a $centerSphere condition

Deprecated. Use circle instead.

Example:

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

Query.prototype.circle()

Parameters:
Returns:
See:

Specifies a $center or $centerSphere condition.

Example:

const area = { center: [50, 50], radius: 10, unique: true }
query.where('loc').within().circle(area)
// alternatively
query.circle('loc', area);

// spherical calculations
const area = { center: [50, 50], radius: 10, unique: true, spherical: true }
query.where('loc').within().circle(area)
// alternatively
query.circle('loc', area);

Query.prototype.clone()

Returns:

Make a copy of this query so you can re-execute it.

Example:

const q = Book.findOne({ title: 'Casino Royale' });
await q.exec();
await q.exec(); // Throws an error because you can't execute a query twice

await q.clone().exec(); // Works

Query.prototype.collation()

Parameters:
Returns:
See:

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


Parameters:
See:

Specifies the comment option.

Example:

query.comment('login query')

Note:

Cannot be used with distinct()


Query.prototype.countDocuments()

Parameters:
Returns:
See:

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().

This function triggers the following middleware.

Example:

const countQuery = model.where({ 'color': 'black' }).countDocuments();

query.countDocuments({ color: 'black' }).count().exec();

await query.countDocuments({ color: 'black' });

query.where('color', 'black').countDocuments().exec();

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


Query.prototype.cursor()

Parameters:
Returns:
See:

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:

// There are 2 ways to use a cursor. First, as a stream:
Thing.
  find({ name: /^hello/ }).
  cursor().
  on('data', function(doc) { console.log(doc); }).
  on('end', function() { console.log('Done!'); });

// Or you can use `.next()` to manually get the next doc in the stream.
// `.next()` returns a promise, so you can use promises or callbacks.
const cursor = Thing.find({ name: /^hello/ }).cursor();
cursor.next(function(error, doc) {
  console.log(doc);
});

// Because `.next()` returns a promise, you can use co
// to easily iterate through all documents without loading them
// all into memory.
const cursor = Thing.find({ name: /^hello/ }).cursor();
for (let doc = await cursor.next(); doc != null; doc = await cursor.next()) {
  console.log(doc);
}

Valid options


Query.prototype.deleteMany()

Parameters:
Returns:
See:

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:

await Character.deleteMany({ name: /Stark/, age: { $gte: 18 } });

This function calls the MongoDB driver's Collection#deleteMany() function. The returned promise resolves to an object that contains 2 properties:

Example:

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

Query.prototype.deleteOne()

Parameters:
Returns:
See:

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

This function triggers deleteOne middleware.

Example:

await Character.deleteOne({ name: 'Eddard Stark' });

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

Example:

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

Query.prototype.distinct()

Parameters:
Returns:
See:

Declares or executes a distinct() operation.

This function does not trigger any middleware.

Example:

distinct(field, conditions, options)
distinct(field, conditions)
distinct(field)
distinct()

Query.prototype.elemMatch()

Parameters:
Returns:
See:

Specifies an $elemMatch condition

Example:

query.elemMatch('comment', { author: 'autobot', votes: {$gte: 5}})

query.where('comment').elemMatch({ author: 'autobot', votes: {$gte: 5}})

query.elemMatch('comment', function (elem) {
  elem.where('author').equals('autobot');
  elem.where('votes').gte(5);
})

query.where('comment').elemMatch(function (elem) {
  elem.where({ author: 'autobot' });
  elem.where('votes').gte(5);
})

Query.prototype.equals()

Parameters:
Returns:

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

Example:

User.where('age').equals(49);

// is the same as

User.where('age', 49);

Query.prototype.error()

Parameters:
Returns:

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

Example:

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

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

Example:

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

Query.prototype.estimatedDocumentCount()

Parameters:
Returns:
See:

Specifies this query as a estimatedDocumentCount() query. Faster than using countDocuments() for large collections becauseestimatedDocumentCount() 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.

Example:

await Model.find().estimatedDocumentCount();

Query.prototype.exec()

Parameters:
Returns:

Executes the query

Example:

const promise = query.exec();
const promise = query.exec('update');

Query.prototype.exists()

Parameters:
Returns:
See:

Specifies an $exists condition

Example:

// { name: { $exists: true }}
Thing.where('name').exists()
Thing.where('name').exists(true)
Thing.find().exists('name')

// { name: { $exists: false }}
Thing.where('name').exists(false);
Thing.find().exists('name', false);

Query.prototype.explain()

Parameters:
Returns:

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:

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

Query.prototype.finally()

Parameters:
Returns:

Query.prototype.find()

Parameters:
Returns:

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, useQuery.prototype.cursor()

Example:

const arr = await Movie.find({ year: { <span class="katex"><span class="katex-mathml"><math xmlns="http://www.w3.org/1998/Math/MathML"><semantics><mrow><mi>g</mi><mi>t</mi><mi>e</mi><mo>:</mo><mn>1980</mn><mo separator="true">,</mo></mrow><annotation encoding="application/x-tex">gte: 1980, </annotation></semantics></math></span><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:0.8095em;vertical-align:-0.1944em;"></span><span class="mord mathnormal" style="margin-right:0.03588em;">g</span><span class="mord mathnormal">t</span><span class="mord mathnormal">e</span><span class="mspace" style="margin-right:0.2778em;"></span><span class="mrel">:</span><span class="mspace" style="margin-right:0.2778em;"></span></span><span class="base"><span class="strut" style="height:0.8389em;vertical-align:-0.1944em;"></span><span class="mord">1980</span><span class="mpunct">,</span></span></span></span>lte: 1989 } });

Query.prototype.findById()

Parameters:
Returns:
See:

Finds a single document by its _id field. findById(id) is equivalent tofindOne({ _id: id }).

The id is cast based on the Schema before sending the command.

This function triggers the following middleware.


Query.prototype.findByIdAndDelete()

Parameters:
Returns:
See:

Issue a MongoDB findOneAndDelete() command by a document's _id field. In other words, findByIdAndDelete(id) is a shorthand forfindOneAndDelete({ _id: id }).

This function triggers the following middleware.


Query.prototype.findByIdAndUpdate()

Parameters:
Returns:
See:

Issues a mongodb findOneAndUpdate command by a document's _id field.findByIdAndUpdate(id, ...) is equivalent to findOneAndUpdate({ _id: id }, ...).

Finds a matching document, updates it according to the update arg, passing any options, and returns the found document (if any).

This function triggers the following middleware.


Query.prototype.findOne()

Parameters:
Returns:
See:

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

The result of the query is a single document, or null if no document was found.

This function triggers the following middleware.

Example:

const query = Kitten.where({ color: 'white' });
const kitten = await query.findOne();

Query.prototype.findOneAndDelete()

Parameters:
Returns:
See:

Issues a MongoDB findOneAndDelete command.

Finds a matching document, removes it, and returns the found document (if any).

This function triggers the following middleware.

Available options

Example:

A.where().findOneAndDelete(conditions, options)  // return Query
A.where().findOneAndDelete(conditions) // returns Query
A.where().findOneAndDelete()           // returns Query

Query.prototype.findOneAndReplace()

Parameters:
Returns:

Issues a MongoDB findOneAndReplace command.

Finds a matching document, removes it, and returns the found document (if any).

This function triggers the following middleware.

Available options

Example:

A.where().findOneAndReplace(filter, replacement, options); // return Query
A.where().findOneAndReplace(filter); // returns Query
A.where().findOneAndReplace(); // returns Query

Query.prototype.findOneAndUpdate()

Parameters:
Returns:
See:

Issues a mongodb findOneAndUpdate() command.

Finds a matching document, updates it according to the update arg, passing any options, and returns the found document (if any).

This function triggers the following middleware.

Available options

Example:

query.findOneAndUpdate(filter, update, options);  // returns Query
query.findOneAndUpdate(filter, update);           // returns Query
// Note that `Query#findOneAndUpdate()` with 1 arg treats the first arg as the `update`, NOT the `filter`.
query.findOneAndUpdate(update);                   // returns Query
query.findOneAndUpdate();                         // returns Query

Query.prototype.geometry()

Parameters:
Returns:
See:

Specifies a $geometry condition

Example:

const polyA = [[[ 10, 20 ], [ 10, 40 ], [ 30, 40 ], [ 30, 20 ]]]
query.where('loc').within().geometry({ type: 'Polygon', coordinates: polyA })

// or
const polyB = [[ 0, 0 ], [ 1, 1 ]]
query.where('loc').within().geometry({ type: 'LineString', coordinates: polyB })

// or
const polyC = [ 0, 0 ]
query.where('loc').within().geometry({ type: 'Point', coordinates: polyC })

// or
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.


Query.prototype.get()

Parameters:
Returns:

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:

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

Query.prototype.getFilter()

Returns:

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

Example:

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

Query.prototype.getOptions()

Returns:

Gets query options.

Example:

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

Query.prototype.getPopulatedPaths()

Returns:

Gets a list of paths to be populated by this query

Example:

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

Example:

 // Deep populate
 const q = L1.find().populate({
   path: 'level2',
   populate: { path: 'level3' }
 });
 q.getPopulatedPaths(); // ['level2', 'level2.level3']

Query.prototype.getQuery()

Returns:

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:

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

Query.prototype.getUpdate()

Returns:

Returns the current update operations as a JSON object.

Example:

const query = new Query();
query.updateOne({}, { $set: { a: 5 } });
query.getUpdate(); // { $set: { a: 5 } }

Query.prototype.gt()

Parameters:
See:

Specifies a $gt query condition.

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

Example:

Thing.find().where('age').gt(21);

// or
Thing.find().gt('age', 21);

Query.prototype.gte()

Parameters:
See:

Specifies a $gte query condition.

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


Query.prototype.hint()

Parameters:
Returns:
See:

Sets query hints.

Example:

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

Note:

Cannot be used with distinct()


Query.prototype.in()

Parameters:
See:

Specifies an $in query condition.

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


Query.prototype.intersects()

Parameters:
Returns:
See:

Declares an intersects query for geometry().

Example:

query.where('path').intersects().geometry({
  type: 'LineString',
  coordinates: [[180.0, 11.0], [180, 9.0]]
});

query.where('path').intersects({
  type: 'LineString',
  coordinates: [[180.0, 11.0], [180, 9.0]]
});

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.isPathSelectedInclusive()

Parameters:
Returns:

Wrapper function to call isPathSelectedInclusive on a query.


Query.prototype.j()

Parameters:
Returns:
See:

Requests acknowledgement that this operation has been persisted to MongoDB's on-disk journal. This option is only valid for operations that write to the database:

Defaults to the schema's writeConcern.j option

Example:

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

Query.prototype.lean()

Parameters:
Returns:

Query.prototype.limit()

Parameters:

Specifies the maximum number of documents the query will return.

Example:

query.limit(20);

Note:

Cannot be used with distinct()


Query.prototype.lt()

Parameters:
See:

Specifies a $lt query condition.

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


Query.prototype.lte()

Parameters:
See:

Specifies a $lte query condition.

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


Query.prototype.maxDistance()

Parameters:
See:

Specifies a maxDistance query condition.

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


Query.prototype.maxTimeMS()

Parameters:
Returns:

Sets the maxTimeMSoption. 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:

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

Query.prototype.merge()

Parameters:
Returns:

Merges another Query or conditions object into this one.

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


Query.prototype.mod()

Parameters:
Returns:
See:

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

Example:

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

Query.prototype.model

Type:

The model this query is associated with.

Example:

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

Query.prototype.mongooseOptions()

Parameters:
Returns:

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

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.


Query.prototype.ne()

Parameters:
See:

Specifies a $ne query condition.

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


Query.prototype.near()

Parameters:
Returns:
See:

Specifies a $near or $nearSphere condition

These operators return documents sorted by distance.

Example:

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

Query.prototype.nearSphere()

~DEPRECATED~

See:

DEPRECATED Specifies a $nearSphere condition

Example:

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

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

Example:

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

Query.prototype.nin()

Parameters:
See:

Specifies an $nin query condition.

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


Query.prototype.nor()

Parameters:
Returns:
See:

Specifies arguments for a $nor condition.

Example:

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

Query.prototype.or()

Parameters:
Returns:
See:

Specifies arguments for an $or condition.

Example:

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

Query.prototype.orFail()

Parameters:
Returns:

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:

// Throws if no doc returned
await Model.findOne({ foo: 'bar' }).orFail();

// Throws if no document was updated. Note that `orFail()` will still
// throw if the only document that matches is `{ foo: 'bar', name: 'test' }`,
// because `orFail()` will throw if no document was _updated_, not
// if no document was _found_.
await Model.updateOne({ foo: 'bar' }, { name: 'test' }).orFail();

// Throws "No docs found!" error if no docs match `{ foo: 'bar' }`
await Model.find({ foo: 'bar' }).orFail(new Error('No docs found!'));

// Throws "Not found" error if no document was found
await Model.findOneAndUpdate({ foo: 'bar' }, { name: 'test' }).
  orFail(() => Error('Not found'));

Query.prototype.polygon()

Parameters:
Returns:
See:

Specifies a $polygon condition

Example:

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

Query.prototype.populate()

Parameters:
Returns:
See:

Specifies paths which should be populated with other documents.

Example:

let book = await Book.findOne().populate('authors');
book.title; // 'Node.js in Action'
book.authors[0].name; // 'TJ Holowaychuk'
book.authors[1].name; // 'Nathan Rajlich'

let books = await Book.find().populate({
  path: 'authors',
  // `match` and `sort` apply to the Author model,
  // not the Book model. These options do not affect
  // which documents are in `books`, just the order and
  // contents of each book document's `authors`.
  match: { name: new RegExp('.*h.*', 'i') },
  sort: { name: -1 }
});
books[0].title; // 'Node.js in Action'
// Each book's `authors` are sorted by name, descending.
books[0].authors[0].name; // 'TJ Holowaychuk'
books[0].authors[1].name; // 'Marc Harter'

books[1].title; // 'Professional AngularJS'
// Empty array, no authors' name has the letter 'h'
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.


Query.prototype.post()

Parameters:
Returns:

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

Example:

const q1 = Question.find({ answer: 42 });
q1.post(function middleware() {
  console.log(this.getFilter());
});
await q1.exec(); // Prints "{ answer: 42 }"

// Doesn't print anything, because `middleware()` is only
// registered on `q1`.
await Question.find({ answer: 42 });

Query.prototype.pre()

Parameters:
Returns:

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

Example:

const q1 = Question.find({ answer: 42 });
q1.pre(function middleware() {
  console.log(this.getFilter());
});
await q1.exec(); // Prints "{ answer: 42 }"

// Doesn't print anything, because `middleware()` is only
// registered on `q1`.
await Question.find({ answer: 42 });

Query.prototype.projection()

Parameters:
Returns:

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:

const q = Model.find();
q.projection(); // null

q.select('a b');
q.projection(); // { a: 1, b: 1 }

q.projection({ c: 1 });
q.projection(); // { c: 1 }

q.projection(null);
q.projection(); // null

Query.prototype.read()

Parameters:
Returns:
See:

Determines the MongoDB nodes from which to read.

Preferences:

primary - (default) Read from primary only. Operations will produce an error if primary is unavailable. Cannot be combined with tags.
secondary            Read from secondary if available, otherwise error.
primaryPreferred     Read from primary if available, otherwise a secondary.
secondaryPreferred   Read from a secondary if available, otherwise read from the primary.
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

p   primary
pp  primaryPreferred
s   secondary
sp  secondaryPreferred
n   nearest

Example:

new Query().read('primary')
new Query().read('p')  // same as primary

new Query().read('primaryPreferred')
new Query().read('pp') // same as primaryPreferred

new Query().read('secondary')
new Query().read('s')  // same as secondary

new Query().read('secondaryPreferred')
new Query().read('sp') // same as secondaryPreferred

new Query().read('nearest')
new Query().read('n')  // same as nearest

// read from secondaries with matching tags
new Query().read('s', [{ dc:'sf', s: 1 },{ dc:'ma', s: 2 }])

Read more about how to use read preferences here.


Query.prototype.readConcern()

Parameters:
Returns:
See:

Sets the readConcern option for the query.

Example:

new Query().readConcern('local')
new Query().readConcern('l')  // same as local

new Query().readConcern('available')
new Query().readConcern('a')  // same as available

new Query().readConcern('majority')
new Query().readConcern('m')  // same as majority

new Query().readConcern('linearizable')
new Query().readConcern('lz') // same as linearizable

new Query().readConcern('snapshot')
new Query().readConcern('s')  // same as snapshot

Read Concern Level:

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).
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).
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.
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.
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

l   local
a   available
m   majority
lz  linearizable
s   snapshot

Read more about how to use read concern here.


Query.prototype.regex()

Parameters:
See:

Specifies a $regex query condition.

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


Query.prototype.replaceOne()

Parameters:
Returns:
See:

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

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

Example:

const res = await Person.replaceOne({ _id: 24601 }, { name: 'Jean Valjean' });
res.acknowledged; // Indicates if this write result was acknowledged. If not, then all other members of this result will be undefined.
res.matchedCount; // Number of documents that matched the filter
res.modifiedCount; // Number of documents that were modified
res.upsertedCount; // Number of documents that were upserted
res.upsertedId; // Identifier of the inserted document (if an upsert took place)

This function triggers the following middleware.


Query.prototype.sanitizeProjection()

Parameters:
Returns:
See:

Sets this query's sanitizeProjection option. If set, sanitizeProjection does two things:

  1. Enforces that projection values are numbers, not strings.
  2. Prevents using + syntax to override properties that are deselected by default.

With sanitizeProjection(), you can pass potentially untrusted user data to .select().

Example

const userSchema = new Schema({
  name: String,
  password: { type: String, select: false }
});
const UserModel = mongoose.model('User', userSchema);
const { _id } = await UserModel.create({ name: 'John', password: 'secret' })

// The MongoDB server has special handling for string values that start with '$'
// in projections, which can lead to unexpected leaking of sensitive data.
let doc = await UserModel.findOne().select({ name: '$password' });
doc.name; // 'secret'
doc.password; // undefined

// With `sanitizeProjection`, Mongoose forces all projection values to be numbers
doc = await UserModel.findOne().sanitizeProjection(true).select({ name: '$password' });
doc.name; // 'John'
doc.password; // undefined

// By default, Mongoose supports projecting in `password` using `+password`
doc = await UserModel.findOne().select('+password');
doc.password; // 'secret'

// With `sanitizeProjection`, Mongoose prevents projecting in `password` and other
// fields that have `select: false` in the schema.
doc = await UserModel.findOne().sanitizeProjection(true).select('+password');
doc.password; // undefined

Query.prototype.schemaLevelProjections()

Parameters:
Returns:
See:

Enable or disable schema level projections for this query. Enabled by default. Set to false to include fields with select: false in the query result by default.

Example:

const userSchema = new Schema({
  email: { type: String, required: true },
  passwordHash: { type: String, select: false, required: true }
});
const UserModel = mongoose.model('User', userSchema);

const doc = await UserModel.findOne().orFail().schemaLevelProjections(false);

// Contains password hash, because `schemaLevelProjections()` overrides `select: false`
doc.passwordHash;

Query.prototype.select()

Parameters:
Returns:
See:

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 schema level.

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:

// include a and b, exclude other fields
query.select('a b');
// Equivalent syntaxes:
query.select(['a', 'b']);
query.select({ a: 1, b: 1 });

// exclude c and d, include other fields
query.select('-c -d');

// Use `+` to override schema-level `select: false` without making the
// projection inclusive.
const schema = new Schema({
  foo: { type: String, select: false },
  bar: String
});
// ...
query.select('+foo'); // Override foo's `select: false` without excluding `bar`

// or you may use object notation, useful when
// you have keys already prefixed with a "-"
query.select({ a: 1, b: 1 });
query.select({ c: 0, d: 0 });

Additional calls to select can override the previous selection:
query.select({ a: 1, b: 1 }).select({ b: 0 }); // selection is now { a: 1 }
query.select({ a: 0, b: 0 }).select({ b: 1 }); // selection is now { a: 0 }

Query.prototype.selected()

Returns:

Determines if field selection has been made.


Query.prototype.selectedExclusively()

Returns:

Determines if exclusive field selection has been made.

query.selectedExclusively(); // false
query.select('-name');
query.selectedExclusively(); // true
query.selectedInclusively(); // false

Query.prototype.selectedInclusively()

Returns:

Determines if inclusive field selection has been made.

query.selectedInclusively(); // false
query.select('name');
query.selectedInclusively(); // true

Query.prototype.session()

Parameters:
Returns:
See:

Sets the MongoDB sessionassociated with this query. Sessions are how you mark a query as part of atransaction.

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

Example:

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

Query.prototype.set()

Parameters:
Returns:

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:

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

Query.prototype.setOptions()

Parameters:
Returns:

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: updateOne(), updateMany(), replaceOne(), findOneAndUpdate(), and findByIdAndUpdate():

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

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

The following options are for find(), findOne(), findOneAndUpdate(), findOneAndDelete(), updateOne(), and deleteOne():

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

The following options are for all operations:


Query.prototype.setQuery()

Parameters:
Returns:

Sets the query conditions to the provided JSON object.

Example:

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

Query.prototype.setUpdate()

Parameters:
Returns:

Sets the current update operation to new value.

Example:

const query = new Query();
query.updateOne({}, { $set: { a: 5 } });
query.setUpdate({ $set: { b: 6 } });
query.getUpdate(); // { $set: { b: 6 } }

Query.prototype.size()

Parameters:
See:

Specifies a $size query condition.

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

Example:

const docs = await MyModel.where('tags').size(0).exec();
assert(Array.isArray(docs));
console.log('documents with 0 tags', docs);

Query.prototype.skip()

Parameters:
See:

Specifies the number of documents to skip.

Example:

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

Note:

Cannot be used with distinct()


Query.prototype.slice()

Parameters:
Returns:
See:

Specifies a $slice projection for an array.

Example:

query.slice('comments', 5); // Returns the first 5 comments
query.slice('comments', -5); // Returns the last 5 comments
query.slice('comments', [10, 5]); // Returns the first 5 comments after the 10-th
query.where('comments').slice(5); // Returns the first 5 comments
query.where('comments').slice([-10, 5]); // Returns the first 5 comments after the 10-th to last

Note: If the absolute value of the number of elements to be sliced is greater than the number of elements in the array, all array elements will be returned.

 // Given `arr`: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
 query.slice('arr', 20); // Returns [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
 query.slice('arr', -20); // Returns [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

Note: If the number of elements to skip is positive and greater than the number of elements in the array, an empty array will be returned.

 // Given `arr`: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
 query.slice('arr', [20, 5]); // Returns []

Note: If the number of elements to skip is negative and its absolute value is greater than the number of elements in the array, the starting position is the start of the array.

 // Given `arr`: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
 query.slice('arr', [-20, 5]); // Returns [1, 2, 3, 4, 5]

Query.prototype.sort()

Parameters:
Returns:
See:

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:

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

// equivalent
query.sort('field -test');

// also possible is to use a array with array key-value pairs
query.sort([['field', 'asc']]);

Note:

Cannot be used with distinct()


Query.prototype.tailable()

Parameters:
See:

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

Example:

query.tailable(); // true
query.tailable(true);
query.tailable(false);

// Set both `tailable` and `awaitData` options
query.tailable({ awaitData: true });

Note:

Cannot be used with distinct()


Query.prototype.then()

Parameters:
Returns:

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

More about then() in JavaScript.


Query.prototype.toConstructor()

Returns:

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

Example:

// Create a query for adventure movies and read from the primary
// node in the replica-set unless it is down, in which case we'll
// read from a secondary node.
const query = Movie.find({ tags: 'adventure' }).read('primaryPreferred');

// create a custom Query constructor based off these settings
const Adventure = query.toConstructor();

// further narrow down our query results while still using the previous settings
await Adventure().where({ name: /^Life/ }).exec();

// since Adventure is a stand-alone constructor we can also add our own
// helper methods and getters without impacting global queries
Adventure.prototype.startsWith = function (prefix) {
  this.where({ name: new RegExp('^' + prefix) })
  return this;
}
Object.defineProperty(Adventure.prototype, 'highlyRated', {
  get: function () {
    this.where({ rating: { $gt: 4.5 }});
    return this;
  }
})
await Adventure().highlyRated.startsWith('Life').exec();

Query.prototype.transform()

Parameters:
Returns:

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 transform() will run after any post hooks.

Example:

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

Query.prototype.updateMany()

Parameters:
Returns:
See:

Declare and/or execute this query as an updateMany() operation. MongoDB will update all documents that match filter (as opposed to just the first one).

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

Example:

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

// Other supported syntaxes
await Person.find({ name: /Stark$/ }).updateMany({ isDeleted: true }); // Using chaining syntax
await Person.find().updateMany({ isDeleted: true }); // Set `isDeleted` on _all_ Person documents

This function triggers the following middleware.


Query.prototype.updateOne()

Parameters:
Returns:
See:

Declare and/or execute this query as an updateOne() operation. MongoDB will update only the first document that matches filter.

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

Example:

const res = await Person.updateOne({ name: 'Jean-Luc Picard' }, { ship: 'USS Enterprise' });
res.acknowledged; // Indicates if this write result was acknowledged. If not, then all other members of this result will be undefined.
res.matchedCount; // Number of documents that matched the filter
res.modifiedCount; // Number of documents that were modified
res.upsertedCount; // Number of documents that were upserted
res.upsertedId; // Identifier of the inserted document (if an upsert took place)

// Other supported syntaxes
await Person.findOne({ name: 'Jean-Luc Picard' }).updateOne({ ship: 'USS Enterprise' }); // Using chaining syntax
await Person.updateOne({ ship: 'USS Enterprise' }); // Updates first doc's `ship` property

This function triggers the following middleware.


Query.prototype.w()

Parameters:
Returns:
See:

Sets the specified number of mongod servers, or tag set of mongod servers, that must acknowledge this write before this write is considered successful. This option is only valid for operations that write to the database:

Defaults to the schema's writeConcern.w option

Example:

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

Query.prototype.where()

Parameters:
Returns:

Specifies a path for use with chaining.

Example:

// instead of writing:
User.find({age: {$gte: 21, $lte: 65}});

// we can instead write:
User.where('age').gte(21).lte(65);

// passing query conditions is permitted
User.find().where({ name: 'vonderful' })

// chaining
User
.where('age').gte(21).lte(65)
.where('name', /^vonderful/i)
.where('friends').slice(10)
.exec()

Query.prototype.within()

Returns:
See:

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

Example:

query.where(path).within().box()
query.where(path).within().circle()
query.where(path).within().geometry()

query.where('loc').within({ center: [50,50], radius: 10, unique: true, spherical: true });
query.where('loc').within({ box: [[40.73, -73.9], [40.7, -73.988]] });
query.where('loc').within({ polygon: [[],[],[],[]] });

query.where('loc').within([], [], []) // polygon
query.where('loc').within([], []) // box
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 Query.use$geoWithin.

Note:

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


Query.prototype.writeConcern()

Parameters:
Returns:
See:

Sets the 3 write concern parameters for this query:

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

Defaults to the schema's writeConcern option

Example:

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

Query.prototype.wtimeout()

Parameters:
Returns:
See:

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:

Defaults to the schema's writeConcern.wtimeout option

Example:

// The `deleteOne()` promise won't resolve until this `deleteOne()` has
// propagated to at least `w = 2` members of the replica set. If it takes
// longer than 1 second, this `deleteOne()` will fail.
await mongoose.model('Person').
  deleteOne({ name: 'Ned Stark' }).
  w(2).
  wtimeout(1000);

Query.prototypeSymbol.asyncIterator

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

Example:

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

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

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


Query.prototypeSymbol.toStringTag

Returns:

Returns a string representation of this query.

More about toString() in JavaScript.

Example:

const q = Model.find();
console.log(q); // Prints "Query { find }"

Query.use$geoWithin

Type:
See:

Flag to opt out of using $geoWithin.

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.