- Query
- Query
- Query()
- Query.prototype.$where()
- Query.prototype.Symbol.asyncIterator()
- Query.prototype.all()
- Query.prototype.allowDiskUse()
- Query.prototype.and()
- Query.prototype.batchSize()
- Query.prototype.box()
- Query.prototype.cast()
- Query.prototype.catch()
- Query.prototype.center()
- Query.prototype.centerSphere()
- Query.prototype.circle()
- Query.prototype.collation()
- Query.prototype.comment()
- Query.prototype.count()
- Query.prototype.countDocuments()
- Query.prototype.cursor()
- Query.prototype.deleteMany()
- Query.prototype.deleteOne()
- Query.prototype.distinct()
- Query.prototype.elemMatch()
- Query.prototype.equals()
- Query.prototype.error()
- Query.prototype.estimatedDocumentCount()
- Query.prototype.exec()
- Query.prototype.exists()
- Query.prototype.explain()
- Query.prototype.find()
- Query.prototype.findOne()
- Query.prototype.findOneAndDelete()
- Query.prototype.findOneAndRemove()
- Query.prototype.findOneAndReplace()
- Query.prototype.findOneAndUpdate()
- Query.prototype.geometry()
- Query.prototype.get()
- Query.prototype.getFilter()
- Query.prototype.getOptions()
- Query.prototype.getPopulatedPaths()
- Query.prototype.getQuery()
- Query.prototype.getUpdate()
- Query.prototype.gt()
- Query.prototype.gte()
- Query.prototype.hint()
- Query.prototype.in()
- Query.prototype.intersects()
- Query.prototype.j()
- Query
Query
Query
- Query()
- Query.prototype.$where()
- Query.prototype.Symbol.asyncIterator()
- Query.prototype.all()
- Query.prototype.allowDiskUse()
- Query.prototype.and()
- Query.prototype.batchSize()
- Query.prototype.box()
- Query.prototype.cast()
- Query.prototype.catch()
- Query.prototype.center()
- Query.prototype.centerSphere()
- Query.prototype.circle()
- Query.prototype.collation()
- Query.prototype.comment()
- Query.prototype.count()
- Query.prototype.countDocuments()
- Query.prototype.cursor()
- Query.prototype.deleteMany()
- Query.prototype.deleteOne()
- Query.prototype.distinct()
- Query.prototype.elemMatch()
- Query.prototype.equals()
- Query.prototype.error()
- Query.prototype.estimatedDocumentCount()
- Query.prototype.exec()
- Query.prototype.exists()
- Query.prototype.explain()
- Query.prototype.find()
- Query.prototype.findOne()
- Query.prototype.findOneAndDelete()
- Query.prototype.findOneAndRemove()
- Query.prototype.findOneAndReplace()
- Query.prototype.findOneAndUpdate()
- Query.prototype.geometry()
- Query.prototype.get()
- Query.prototype.getFilter()
- Query.prototype.getOptions()
- Query.prototype.getPopulatedPaths()
- Query.prototype.getQuery()
- Query.prototype.getUpdate()
- Query.prototype.gt()
- Query.prototype.gte()
- Query.prototype.hint()
- Query.prototype.in()
- Query.prototype.intersects()
- Query.prototype.j()
- Query.prototype.lean()
- Query.prototype.limit()
- Query.prototype.lt()
- Query.prototype.lte()
- Query.prototype.map()
- Query.prototype.maxDistance()
- Query.prototype.maxScan()
- Query.prototype.maxTimeMS()
- Query.prototype.maxscan()
- Query.prototype.merge()
- Query.prototype.mod()
- Query.prototype.model
- Query.prototype.mongooseOptions()
- Query.prototype.ne()
- Query.prototype.near()
- Query.prototype.nearSphere()
- Query.prototype.nin()
- Query.prototype.nor()
- Query.prototype.or()
- Query.prototype.orFail()
- Query.prototype.polygon()
- Query.prototype.populate()
- Query.prototype.post()
- Query.prototype.pre()
- Query.prototype.projection()
- Query.prototype.read()
- Query.prototype.readConcern()
- Query.prototype.regex()
- Query.prototype.remove()
- Query.prototype.replaceOne()
- Query.prototype.select()
- Query.prototype.selected()
- Query.prototype.selectedExclusively()
- Query.prototype.selectedInclusively()
- Query.prototype.session()
- Query.prototype.set()
- Query.prototype.setOptions()
- Query.prototype.setQuery()
- Query.prototype.setUpdate()
- Query.prototype.size()
- Query.prototype.skip()
- Query.prototype.slaveOk()
- Query.prototype.slice()
- Query.prototype.snapshot()
- Query.prototype.sort()
- Query.prototype.tailable()
- Query.prototype.then()
- Query.prototype.toConstructor()
- Query.prototype.update()
- Query.prototype.updateMany()
- Query.prototype.updateOne()
- Query.prototype.use$geoWithin
- Query.prototype.w()
- Query.prototype.where()
- Query.prototype.within()
- Query.prototype.writeConcern()
- Query.prototype.wtimeout()
- Query()
- Query.prototype.$where()
- Query.prototype.Symbol.asyncIterator()
- Query.prototype.all()
- Query.prototype.allowDiskUse()
- Query.prototype.and()
- Query.prototype.batchSize()
- Query.prototype.box()
- Query.prototype.cast()
- Query.prototype.catch()
- Query.prototype.center()
- Query.prototype.centerSphere()
- Query.prototype.circle()
- Query.prototype.collation()
- Query.prototype.comment()
- Query.prototype.count()
- Query.prototype.countDocuments()
- Query.prototype.cursor()
- Query.prototype.deleteMany()
- Query.prototype.deleteOne()
- Query.prototype.distinct()
- Query.prototype.elemMatch()
- Query.prototype.equals()
- Query.prototype.error()
- Query.prototype.estimatedDocumentCount()
- Query.prototype.exec()
- Query.prototype.exists()
- Query.prototype.explain()
- Query.prototype.find()
- Query.prototype.findOne()
- Query.prototype.findOneAndDelete()
- Query.prototype.findOneAndRemove()
- Query.prototype.findOneAndReplace()
- Query.prototype.findOneAndUpdate()
- Query.prototype.geometry()
- Query.prototype.get()
- Query.prototype.getFilter()
- Query.prototype.getOptions()
- Query.prototype.getPopulatedPaths()
- Query.prototype.getQuery()
- Query.prototype.getUpdate()
- Query.prototype.gt()
- Query.prototype.gte()
- Query.prototype.hint()
- Query.prototype.in()
- Query.prototype.intersects()
- Query.prototype.j()
- Query.prototype.lean()
- Query.prototype.limit()
- Query.prototype.lt()
- Query.prototype.lte()
- Query.prototype.map()
- Query.prototype.maxDistance()
- Query.prototype.maxScan()
- Query.prototype.maxTimeMS()
- Query.prototype.maxscan()
- Query.prototype.merge()
- Query.prototype.mod()
- Query.prototype.model
- Query.prototype.mongooseOptions()
- Query.prototype.ne()
- Query.prototype.near()
- Query.prototype.nearSphere()
- Query.prototype.nin()
- Query.prototype.nor()
- Query.prototype.or()
- Query.prototype.orFail()
- Query.prototype.polygon()
- Query.prototype.populate()
- Query.prototype.post()
- Query.prototype.pre()
- Query.prototype.projection()
- Query.prototype.read()
- Query.prototype.readConcern()
- Query.prototype.regex()
- Query.prototype.remove()
- Query.prototype.replaceOne()
- Query.prototype.select()
- Query.prototype.selected()
- Query.prototype.selectedExclusively()
- Query.prototype.selectedInclusively()
- Query.prototype.session()
- Query.prototype.set()
- Query.prototype.setOptions()
- Query.prototype.setQuery()
- Query.prototype.setUpdate()
- Query.prototype.size()
- Query.prototype.skip()
- Query.prototype.slaveOk()
- Query.prototype.slice()
- Query.prototype.snapshot()
- Query.prototype.sort()
- Query.prototype.tailable()
- Query.prototype.then()
- Query.prototype.toConstructor()
- Query.prototype.update()
- Query.prototype.updateMany()
- Query.prototype.updateOne()
- Query.prototype.use$geoWithin
- Query.prototype.w()
- Query.prototype.where()
- Query.prototype.within()
- Query.prototype.writeConcern()
- Query.prototype.wtimeout()
Query()
Parameters
- [options] «Object»
- [model] «Object»
- [conditions] «Object»
- [collection] «Object» Mongoose collection
Query constructor used for building queries. You do not need to instantiate a Query directly. Instead use Model functions like Model.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
- js «String|Function» javascript string or function
Returns:
- «Query» this
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 ofits caveats before using.
Query.prototype.Symbol.asyncIterator()
Returns an asyncIterator for use with for/await/of loops 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
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. If Symbol.asyncIterator is undefined, that means your Node.js version does not support async iterators.
Query.prototype.all()
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:
MyModel.find().where('pets').all(['dog', 'cat', 'ferret']);
// Equivalent:
MyModel.find().all('pets', ['dog', 'cat', 'ferret']);
Query.prototype.allowDiskUse()
Parameters
- [v] «Boolean» Enable/disable
allowDiskUse. If called with 0 arguments, setsallowDiskUse: 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:
await query.find().sort({ name: 1 }).allowDiskUse(true);
// Equivalent:
await query.find().sort({ name: 1 }).allowDiskUse();
Query.prototype.and()
Parameters
- array «Array» array of conditions
Returns:
- «Query» this
Specifies arguments for a $and condition.
Example
query.and([{ color: 'green' }, { status: 'ok' }])
Query.prototype.batchSize()
Parameters
- val «Number»
Specifies the batchSize option.
Example
query.batchSize(100)
Note
Cannot be used with distinct()
Query.prototype.box()
Parameters
- val «Object»
- Upper «[Array]» Right Coords
Returns:
- «Query» this
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
-
[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.
Query.prototype.catch()
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 circle
Deprecated. Use circle instead.
Query.prototype.centerSphere()
Parameters
- [path] «String»
- val «Object»
Returns:
- «Query» this
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
- [path] «String»
- area «Object»
Returns:
- «Query» this
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.collation()
Parameters
- value «Object»
Returns:
- «Query» this
Adds a collation to this op (MongoDB 3.4 and up)
Query.prototype.comment()
Parameters
- val «String»
Specifies the comment option.
Example
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 estimatedDocumentCount() function instead. Otherwise, use the countDocuments() function instead.
Passing a callback executes the query.
This function triggers the following middleware.
count()
Example:
const countQuery = model.where({ 'color': 'black' }).count();
query.count({ color: 'black' }).count(callback)
query.count({ color: 'black' }, callback)
query.where('color', 'black').count(function (err, count) {
if (err) return handleError(err);
console.log('there are %d kittens', count);
})
Query.prototype.countDocuments()
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:
const countQuery = model.where({ 'color': 'black' }).countDocuments();
query.countDocuments({ color: 'black' }).count(callback);
query.countDocuments({ color: 'black' }, callback);
query.where('color', 'black').countDocuments(function(err, count) {
if (err) return handleError(err);
console.log('there are %d kittens', count);
});
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:
$where:$expr$near:$geoWithinwith$center$nearSphere:$geoWithinwith$centerSphere
Query.prototype.cursor()
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
// 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.
co(function*() {
const cursor = Thing.find({ name: /^hello/ }).cursor();
for (let doc = yield cursor.next(); doc != null; doc = yield cursor.next()) {
console.log(doc);
}
});
Valid options
transform: optional function which accepts a mongoose document. The return value of the function will be emitted ondataand 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
await Character.deleteMany({ name: /Stark/, age: { $gte: 18 } });
// Using callbacks:
Character.deleteMany({ name: /Stark/, age: { $gte: 18 } }, callback);
This function calls the MongoDB driver‘s Collection#deleteMany() function. The returned promise resolves to an object that contains 3 properties:
ok:1if no errors occurreddeletedCount: the number of documents deletedn: the number of documents deleted. Equal todeletedCount.
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
-
[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 deleteOne() operation. Works like remove, except it deletes at most one document regardless of the single option.
This function triggers deleteOne middleware.
Example
await Character.deleteOne({ name: 'Eddard Stark' });
// Using callbacks:
Character.deleteOne({ name: 'Eddard Stark' }, callback);
This function calls the MongoDB driver‘s Collection#deleteOne() function. The returned promise resolves to an object that contains 3 properties:
ok:1if no errors occurreddeletedCount: the number of documents deletedn: the number of documents deleted. Equal todeletedCount.
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
- [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
distinct(field, conditions, callback)
distinct(field, conditions)
distinct(field, callback)
distinct(field)
distinct(callback)
distinct()
Query.prototype.elemMatch()
Parameters
- path «String|Object|Function»
- filter «Object|Function»
Returns:
- «Query» this
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
- val «Object»
Returns:
- «Query» this
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
- 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:
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
-
[options] «Object» passed transparently to the MongoDB driver
-
[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:
await Model.find().estimatedDocumentCount();
Query.prototype.exec()
Parameters
- [operation] «String|Function»
- [callback] «Function» optional params depend on the function being called
Returns:
- «Promise»
Executes the query
Examples:
const promise = query.exec();
const promise = query.exec('update');
query.exec(callback);
query.exec('find', callback);
Query.prototype.exists()
Parameters
- [path] «String»
- val «Boolean»
Returns:
- «Query» this
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
- [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:
const query = new Query();
const res = await query.find({ a: 1 }).explain('queryPlanner');
console.log(res);
Query.prototype.find()
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
// Using async/await
const arr = await Movie.find({ year: { $gte: 1980, $lte: 1989 } });
// Using callbacks
Movie.find({ year: { $gte: 1980, $lte: 1989 } }, function(err, arr) {});
Query.prototype.findOne()
Parameters
-
[filter] «Object» mongodb selector
-
[projection] «Object» optional fields to return
-
[options] «Object» see
setOptions() -
[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:
conditionsis optional, and ifconditionsis null or undefined, mongoose will send an emptyfindOnecommand to MongoDB, which will return an arbitrary document. If you‘re querying by_id, useModel.findById()instead.
This function triggers the following middleware.
findOne()
Example
const query = Kitten.where({ color: 'white' });
query.findOne(function (err, kitten) {
if (err) return handleError(err);
if (kitten) {
// doc may be null if no document matched
}
});
Query.prototype.findOneAndDelete()
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 transactions docs.
-
[options.strict] «Boolean|String» overwrites the schema‘s strict mode option
-
[callback] «Function» optional params are (error, document)
Returns:
- «Query» this
Issues a MongoDB findOneAndDelete 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 updatemaxTimeMS: puts a time limit on the query - requires mongodb >= 2.6.0rawResult: if true, resolves to the raw result from the MongoDB driver
Callback Signature
function(error, doc) {
// error: any errors that occurred
// doc: the document before updates are applied if `new: false`, or after updates if `new = true`
}
Examples
A.where().findOneAndDelete(conditions, options, callback) // executes
A.where().findOneAndDelete(conditions, options) // return Query
A.where().findOneAndDelete(conditions, callback) // executes
A.where().findOneAndDelete(conditions) // returns Query
A.where().findOneAndDelete(callback) // executes
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 transactions docs.
-
[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 updatemaxTimeMS: puts a time limit on the query - requires mongodb >= 2.6.0rawResult: if true, resolves to the raw result from the MongoDB driver
Callback Signature
function(error, doc) {
// error: any errors that occurred
// doc: the document before updates are applied if `new: false`, or after updates if `new = true`
}
Examples
A.where().findOneAndRemove(conditions, options, callback) // executes
A.where().findOneAndRemove(conditions, options) // return Query
A.where().findOneAndRemove(conditions, callback) // executes
A.where().findOneAndRemove(conditions) // returns Query
A.where().findOneAndRemove(callback) // executes
A.where().findOneAndRemove() // returns Query
Query.prototype.findOneAndReplace()
Parameters
- [filter] «Object»
- [replacement] «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 transactions docs.
-
[options.strict] «Boolean|String» overwrites the schema‘s strict mode option
-
[options.new=false] «Boolean» By default,
findOneAndUpdate()returns the document as it was beforeupdatewas applied. If you setnew: true,findOneAndUpdate()will instead give you the object afterupdatewas 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 the Mongoose lean tutorial. -
[options.session=null] «ClientSession» The session associated with this query. See transactions docs.
-
[options.strict] «Boolean|String» overwrites the schema‘s strict mode option
-
[options.omitUndefined=false] «Boolean» If true, delete any properties whose value is
undefinedwhen casting an update. In other words, if this is set, Mongoose will deletebazfrom the update inModel.updateOne({}, { foo: 'bar', baz: undefined })before sending the update to the server. -
[options.timestamps=null] «Boolean» If set to
falseand 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
newoption.returnOriginal: falseis equivalent tonew: true. -
[callback] «Function» optional params are (error, document)
Returns:
- «Query» this
Issues a MongoDB findOneAndReplace 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 updatemaxTimeMS: puts a time limit on the query - requires mongodb >= 2.6.0rawResult: if true, resolves to the raw result from the MongoDB driver
Callback Signature
function(error, doc) {
// error: any errors that occurred
// doc: the document before updates are applied if `new: false`, or after updates if `new = true`
}
Examples
A.where().findOneAndReplace(filter, replacement, options, callback); // executes
A.where().findOneAndReplace(filter, replacement, options); // return Query
A.where().findOneAndReplace(filter, replacement, callback); // executes
A.where().findOneAndReplace(filter); // returns Query
A.where().findOneAndReplace(callback); // executes
A.where().findOneAndReplace(); // returns Query
Query.prototype.findOneAndUpdate()
Parameters
- [filter] «Object|Query»
- [doc] «Object»
-
[options] «Object»
-
[options.rawResult] «Boolean» if true, returns the raw result from the MongoDB driver
-
[options.strict] «Boolean|String» overwrites the schema‘s strict mode option
-
[options.session=null] «ClientSession» The session associated with this query. See transactions docs.
-
[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 beforeupdatewas applied. If you setnew: true,findOneAndUpdate()will instead give you the object afterupdatewas 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 the Mongoose lean tutorial. -
[options.session=null] «ClientSession» The session associated with this query. See transactions docs.
-
[options.strict] «Boolean|String» overwrites the schema‘s strict mode option
-
[options.omitUndefined=false] «Boolean» If true, delete any properties whose value is
undefinedwhen casting an update. In other words, if this is set, Mongoose will deletebazfrom the update inModel.updateOne({}, { foo: 'bar', baz: undefined })before sending the update to the server. -
[options.timestamps=null] «Boolean» If set to
falseand 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
newoption.returnOriginal: falseis equivalent tonew: true. -
[callback] «Function» optional params are (error, doc), unless
rawResultis 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 updatemaxTimeMS: puts a time limit on the query - requires mongodb >= 2.6.0runValidators: if true, runs update validators on this command. Update validators validate the update operation against the model‘s schema.setDefaultsOnInsert: if this andupsertare 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 MongoDB’s$setOnInsertoperator.rawResult: if true, returns the raw result from the MongoDB drivercontext(string) if set to ‘query’ andrunValidatorsis on,thiswill refer to the query in custom validator functions that update validation runs. Does nothing ifrunValidatorsis false.
Callback Signature
function(error, doc) {
// error: any errors that occurred
// doc: the document before updates are applied if `new: false`, or after updates if `new = true`
}
Examples
query.findOneAndUpdate(conditions, update, options, callback) // executes
query.findOneAndUpdate(conditions, update, options) // returns Query
query.findOneAndUpdate(conditions, update, callback) // executes
query.findOneAndUpdate(conditions, update) // returns Query
query.findOneAndUpdate(update, callback) // returns Query
query.findOneAndUpdate(update) // returns Query
query.findOneAndUpdate(callback) // executes
query.findOneAndUpdate() // returns Query
Query.prototype.geometry()
Parameters
- object «Object» Must contain a
typeproperty which is a String and acoordinatesproperty which is an Array. See the examples.
Returns:
- «Query» this
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. - type {String} - coordinates {Array}
Query.prototype.get()
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:
const query = Model.updateOne({}, { $set: { name: 'Jean-Luc Picard' } });
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:
const query = new Query();
query.find({ a: 1 }).where('b').gt(2);
query.getFilter(); // { a: 1, b: { $gt: 2 } }
Query.prototype.getOptions()
Returns:
- «Object» the options
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:
- «Array» an array of strings representing populated paths
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:
- «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:
const query = new Query();
query.find({ a: 1 }).where('b').gt(2);
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:
const query = new Query();
query.update({}, { $set: { a: 5 } });
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
Thing.find().where('age').gt(21)
// or
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.
Query.prototype.hint()
Parameters
- val «Object» a hint object
Returns:
- «Query» this
Sets query hints.
Example
query.hint({ indexA: 1, indexB: -1})
Note
Cannot be used with distinct()
Query.prototype.in()
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
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.j()
Parameters
- val «boolean»
Returns:
(本文超出站点单文档体积上限,已截断)
