- Model
- Model
- Model()
- Model.aggregate()
- Model.buildBulkWriteOperations()
- Model.bulkSave()
- Model.bulkWrite()
- Model.cleanIndexes()
- Model.count()
- Model.countDocuments()
- Model.create()
- Model.createCollection()
- Model.createIndexes()
- Model.deleteMany()
- Model.deleteOne()
- Model.diffIndexes()
- Model.discriminator()
- Model.distinct()
- Model.ensureIndexes()
- Model.estimatedDocumentCount()
- Model.events
- Model.exists()
- Model.find()
- Model.findById()
- Model.findByIdAndDelete()
- Model.findByIdAndRemove()
- Model.findByIdAndUpdate()
- Model.findOne()
- Model.findOneAndDelete()
- Model.findOneAndRemove()
- Model.findOneAndReplace()
- Model.findOneAndUpdate()
- Model
Model
Model
- Model()
- Model.aggregate()
- Model.buildBulkWriteOperations()
- Model.bulkSave()
- Model.bulkWrite()
- Model.cleanIndexes()
- Model.count()
- Model.countDocuments()
- Model.create()
- Model.createCollection()
- Model.createIndexes()
- Model.deleteMany()
- Model.deleteOne()
- Model.diffIndexes()
- Model.discriminator()
- Model.distinct()
- Model.ensureIndexes()
- Model.estimatedDocumentCount()
- Model.events
- Model.exists()
- Model.find()
- Model.findById()
- Model.findByIdAndDelete()
- Model.findByIdAndRemove()
- Model.findByIdAndUpdate()
- Model.findOne()
- Model.findOneAndDelete()
- Model.findOneAndRemove()
- Model.findOneAndReplace()
- Model.findOneAndUpdate()
- Model.geoSearch()
- Model.hydrate()
- Model.init()
- Model.insertMany()
- Model.inspect()
- Model.listIndexes()
- Model.mapReduce()
- Model.populate()
- Model.prototype.$where
- Model.prototype.$where()
- Model.prototype.base
- Model.prototype.baseModelName
- Model.prototype.collection
- Model.prototype.db
- Model.prototype.delete
- Model.prototype.deleteOne()
- Model.prototype.discriminators
- Model.prototype.model()
- Model.prototype.modelName
- Model.prototype.remove()
- Model.prototype.save()
- Model.prototype.schema
- Model.remove()
- Model.replaceOne()
- Model.startSession()
- Model.syncIndexes()
- Model.translateAliases()
- Model.update()
- Model.updateMany()
- Model.updateOne()
- Model.validate()
- Model.watch()
- Model.where()
- increment()
- Model()
- Model.aggregate()
- Model.buildBulkWriteOperations()
- Model.bulkSave()
- Model.bulkWrite()
- Model.cleanIndexes()
- Model.count()
- Model.countDocuments()
- Model.create()
- Model.createCollection()
- Model.createIndexes()
- Model.deleteMany()
- Model.deleteOne()
- Model.diffIndexes()
- Model.discriminator()
- Model.distinct()
- Model.ensureIndexes()
- Model.estimatedDocumentCount()
- Model.events
- Model.exists()
- Model.find()
- Model.findById()
- Model.findByIdAndDelete()
- Model.findByIdAndRemove()
- Model.findByIdAndUpdate()
- Model.findOne()
- Model.findOneAndDelete()
- Model.findOneAndRemove()
- Model.findOneAndReplace()
- Model.findOneAndUpdate()
- Model.geoSearch()
- Model.hydrate()
- Model.init()
- Model.insertMany()
- Model.inspect()
- Model.listIndexes()
- Model.mapReduce()
- Model.populate()
- Model.prototype.$where
- Model.prototype.$where()
- Model.prototype.base
- Model.prototype.baseModelName
- Model.prototype.collection
- Model.prototype.db
- Model.prototype.delete
- Model.prototype.deleteOne()
- Model.prototype.discriminators
- Model.prototype.model()
- Model.prototype.modelName
- Model.prototype.remove()
- Model.prototype.save()
- Model.prototype.schema
- Model.remove()
- Model.replaceOne()
- Model.startSession()
- Model.syncIndexes()
- Model.translateAliases()
- Model.update()
- Model.updateMany()
- Model.updateOne()
- Model.validate()
- Model.watch()
- Model.where()
- increment()
Model()
Parameters
-
doc «Object» values for initial set
-
optional «[fields]» object containing the fields that were selected in the query which returned this document. You do not need to set this parameter to ensure Mongoose handles your query projection.
-
[skipId=false] «Boolean» optional boolean. If true, mongoose doesn‘t add an
_idfield to the document.
Inherits:
A Model is a class that‘s your primary tool for interacting with MongoDB. An instance of a Model is called a Document.
In Mongoose, the term “Model” refers to subclasses of the mongoose.Model class. You should not use the mongoose.Model class directly. The mongoose.model() and connection.model() functions create subclasses of mongoose.Model as shown below.
Example:
// `UserModel` is a "Model", a subclass of `mongoose.Model`.
const UserModel = mongoose.model('User', new Schema({ name: String }));
// You can use a Model to create new documents using `new`:
const userDoc = new UserModel({ name: 'Foo' });
await userDoc.save();
// You also use a model to create queries:
const userFromDb = await UserModel.findOne({ name: 'Foo' });
Model.aggregate()
Parameters
-
[pipeline] «Array» aggregation pipeline as an array of objects
-
[callback] «Function»
Returns:
- «Aggregate»
Performs aggregations on the models collection.
If a callback is passed, the aggregate is executed and a Promise is returned. If a callback is not passed, the aggregate itself is returned.
This function triggers the following middleware.
aggregate()
Example:
// Find the max balance of all accounts
Users.aggregate([
{ $group: { _id: null, maxBalance: { $max: '$balance' }}},
{ $project: { _id: 0, maxBalance: 1 }}
]).
then(function (res) {
console.log(res); // [ { maxBalance: 98000 } ]
});
// Or use the aggregation pipeline builder.
Users.aggregate().
group({ _id: null, maxBalance: { $max: '$balance' } }).
project('-id maxBalance').
exec(function (err, res) {
if (err) return handleError(err);
console.log(res); // [ { maxBalance: 98 } ]
});
NOTE:
- Mongoose does not cast aggregation pipelines to the model‘s schema because
$projectand$groupoperators allow redefining the “shape” of the documents at any stage of the pipeline, which may leave documents in an incompatible format. You can use the mongoose-cast-aggregation plugin to enable minimal casting for aggregation pipelines. - The documents returned are plain javascript objects, not mongoose documents (since any shape of document can be returned).
More About Aggregations:
Model.buildBulkWriteOperations()
Parameters
- options «Object»
- options.skipValidation «Boolean» defaults to
false, when set to true, building the write operations will bypass validating the documents.
@param {[Document]} documents The array of documents to build write operations of
Model.bulkSave()
Parameters
- documents «[Document]»
takes an array of documents, gets the changes and inserts/updates documents in the database according to whether or not the document is new, or whether it has changes or not.
bulkSave uses bulkWrite under the hood, so it‘s mostly useful when dealing with many documents (10K+)
Model.bulkWrite()
Parameters
-
ops «Array»
-
[ops.insertOne.document] «Object» The document to insert
-
[opts.updateOne.filter] «Object» Update the first document that matches this filter
-
[opts.updateOne.update] «Object» An object containing update operators
-
[opts.updateOne.upsert=false] «Boolean» If true, insert a doc if none match
-
[opts.updateOne.timestamps=true] «Boolean» If false, do not apply timestamps to the operation
-
[opts.updateOne.collation] «Object» The MongoDB collation to use
-
[opts.updateOne.arrayFilters] «Array» The array filters used in
update -
[opts.updateMany.filter] «Object» Update all the documents that match this filter
-
[opts.updateMany.update] «Object» An object containing update operators
-
[opts.updateMany.upsert=false] «Boolean» If true, insert a doc if no documents match
filter -
[opts.updateMany.timestamps=true] «Boolean» If false, do not apply timestamps to the operation
-
[opts.updateMany.collation] «Object» The MongoDB collation to use
-
[opts.updateMany.arrayFilters] «Array» The array filters used in
update -
[opts.deleteOne.filter] «Object» Delete the first document that matches this filter
-
[opts.deleteMany.filter] «Object» Delete all documents that match this filter
-
[opts.replaceOne.filter] «Object» Replace the first document that matches this filter
-
[opts.replaceOne.replacement] «Object» The replacement document
-
[opts.replaceOne.upsert=false] «Boolean» If true, insert a doc if no documents match
filter -
[options] «Object»
-
[options.ordered=true] «Boolean» If true, execute writes in order and stop at the first error. If false, execute writes in parallel and continue until all writes have either succeeded or errored.
-
[options.session=null] «ClientSession» The session associated with this bulk write. See transactions docs.
-
[options.w=1] «String|number» The write concern. See
Query#w()for more information. -
[options.wtimeout=null] «number» The write concern timeout.
-
[options.j=true] «Boolean» If false, disable journal acknowledgement
-
[options.bypassDocumentValidation=false] «Boolean» If true, disable MongoDB server-side schema validation for all writes in this bulk.
-
[options.strict=null] «Boolean» Overwrites the
strictoption on schema. If false, allows filtering and writing fields not defined in the schema for all writes in this bulk. -
[callback] «Function» callback
function(error, bulkWriteOpResult) {}
Returns:
- «Promise» resolves to a
BulkWriteOpResultif the operation succeeds
Sends multiple insertOne, updateOne, updateMany, replaceOne, deleteOne, and/or deleteMany operations to the MongoDB server in one command. This is faster than sending multiple independent operations (e.g. if you use create()) because with bulkWrite() there is only one round trip to MongoDB.
Mongoose will perform casting on all operations you provide.
This function does not trigger any middleware, neither save(), nor update(). If you need to trigger save() middleware for every document use create() instead.
Example:
Character.bulkWrite([
{
insertOne: {
document: {
name: 'Eddard Stark',
title: 'Warden of the North'
}
}
},
{
updateOne: {
filter: { name: 'Eddard Stark' },
// If you were using the MongoDB driver directly, you'd need to do
// `update: { $set: { title: ... } }` but mongoose adds $set for
// you.
update: { title: 'Hand of the King' }
}
},
{
deleteOne: {
{
filter: { name: 'Eddard Stark' }
}
}
}
]).then(res => {
// Prints "1 1 1"
console.log(res.insertedCount, res.modifiedCount, res.deletedCount);
});
The supported operations are:
insertOneupdateOneupdateManydeleteOnedeleteManyreplaceOne
Model.cleanIndexes()
Parameters
- [callback] «Function» optional callback
Returns:
- «Promise,undefined» Returns
undefinedif callback is specified, returns a promise if no callback.
Deletes all indexes that aren‘t defined in this model’s schema. Used by syncIndexes().
The returned promise resolves to a list of the dropped indexes‘ names as an array
Model.count()
Parameters
- filter «Object»
- [callback] «Function»
Returns:
- «Query»
Counts number of documents that match filter in a database collection.
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.
Example:
Adventure.count({ type: 'jungle' }, function (err, count) {
if (err) ..
console.log('there are %d jungle adventures', count);
});
Model.countDocuments()
Parameters
- filter «Object»
- [callback] «Function»
Returns:
- «Query»
Counts number of documents matching filter in a database collection.
Example:
Adventure.countDocuments({ type: 'jungle' }, function (err, count) {
console.log('there are %d jungle adventures', count);
});
If you want to count all documents in a large collection, use the estimatedDocumentCount() function instead. If you call countDocuments({}), MongoDB will always execute a full collection scan and not use any indexes.
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
Model.create()
Parameters
-
docs «Array|Object» Documents to insert, as a spread or array
-
[options] «Object» Options passed down to
save(). To specifyoptions,docsmust be an array, not a spread. -
[callback] «Function» callback
Returns:
- «Promise»
Shortcut for saving one or more documents to the database. MyModel.create(docs) does new MyModel(doc).save() for every doc in docs.
This function triggers the following middleware.
save()
Example:
// Insert one new `Character` document
await Character.create({ name: 'Jean-Luc Picard' });
// Insert multiple new `Character` documents
await Character.create([{ name: 'Will Riker' }, { name: 'Geordi LaForge' }]);
// Create a new character within a transaction. Note that you **must**
// pass an array as the first parameter to `create()` if you want to
// specify options.
await Character.create([{ name: 'Jean-Luc Picard' }], { session });
Model.createCollection()
Parameters
-
[options] «Object» see MongoDB driver docs
-
[callback] «Function»
Create the collection for this model. By default, if no indexes are specified, mongoose will not create the collection for the model until any documents are created. Use this method to create the collection explicitly.
Note 1: You may need to call this before starting a transaction See https://docs.mongodb.com/manual/core/transactions/#transactions-and-operations
Note 2: You don‘t have to call this if your schema contains index or unique field. In that case, just use Model.init()
Example:
const userSchema = new Schema({ name: String })
const User = mongoose.model('User', userSchema);
User.createCollection().then(function(collection) {
console.log('Collection is created!');
});
Model.createIndexes()
Parameters
-
[options] «Object» internal options
-
[cb] «Function» optional callback
Returns:
- «Promise»
Similar to ensureIndexes(), except for it uses the createIndex function.
Model.deleteMany()
Parameters
- conditions «Object»
-
[options] «Object» optional see
Query.prototype.setOptions() -
[callback] «Function»
Returns:
- «Query»
Deletes all of the documents that match conditions from the collection. Behaves like remove(), but deletes all documents that match conditions regardless of the single option.
Example:
await Character.deleteMany({ name: /Stark/, age: { $gte: 18 } });
Note:
This function triggers deleteMany query hooks. Read the middleware docs to learn more.
Model.deleteOne()
Parameters
- conditions «Object»
-
[options] «Object» optional see
Query.prototype.setOptions() -
[callback] «Function»
Returns:
- «Query»
Deletes the first document that matches conditions from the collection. Behaves like remove(), but deletes at most one document regardless of the single option.
Example:
await Character.deleteOne({ name: 'Eddard Stark' });
Note:
This function triggers deleteOne query hooks. Read the middleware docs to learn more.
Model.diffIndexes()
Parameters
-
options «Object» not used at all.
-
callback «Function» optional callback
Does a dry-run of Model.syncIndexes(), meaning that the result of this function would be the result of Model.syncIndexes().
Model.discriminator()
Parameters
-
name «String» discriminator model name
-
schema «Schema» discriminator model schema
-
[value] «String» the string stored in the
discriminatorKeyproperty. If not specified, Mongoose uses thenameparameter.
Returns:
- «Model» The newly created discriminator model
Adds a discriminator type.
Example:
function BaseSchema() {
Schema.apply(this, arguments);
this.add({
name: String,
createdAt: Date
});
}
util.inherits(BaseSchema, Schema);
const PersonSchema = new BaseSchema();
const BossSchema = new BaseSchema({ department: String });
const Person = mongoose.model('Person', PersonSchema);
const Boss = Person.discriminator('Boss', BossSchema);
new Boss().__t; // "Boss". `__t` is the default `discriminatorKey`
const employeeSchema = new Schema({ boss: ObjectId });
const Employee = Person.discriminator('Employee', employeeSchema, 'staff');
new Employee().__t; // "staff" because of 3rd argument above
Model.distinct()
Parameters
- field «String»
-
[conditions] «Object» optional
-
[callback] «Function»
Returns:
- «Query»
Creates a Query for a distinct operation.
Passing a callback executes the query.
Example
Link.distinct('url', { clicks: {$gt: 100}}, function (err, result) {
if (err) return handleError(err);
assert(Array.isArray(result));
console.log('unique urls with more than 100 clicks', result);
})
const query = Link.distinct('url');
query.exec(callback);
Model.ensureIndexes()
Parameters
-
[options] «Object» internal options
-
[cb] «Function» optional callback
Returns:
- «Promise»
Sends createIndex commands to mongo for each index declared in the schema. The createIndex commands are sent in series.
Example:
Event.ensureIndexes(function (err) {
if (err) return handleError(err);
});
After completion, an index event is emitted on this Model passing an error if one occurred.
Example:
const eventSchema = new Schema({ thing: { type: 'string', unique: true }})
const Event = mongoose.model('Event', eventSchema);
Event.on('index', function (err) {
if (err) console.error(err); // error occurred during index creation
})
NOTE: It is not recommended that you run this in production. Index creation may impact database performance depending on your load. Use with caution.
Model.estimatedDocumentCount()
Parameters
- [options] «Object»
- [callback] «Function»
Returns:
- «Query»
Estimates the number of documents in the MongoDB collection. Faster than using countDocuments() for large collections because estimatedDocumentCount() uses collection metadata rather than scanning the entire collection.
Example:
const numAdventures = Adventure.estimatedDocumentCount();
Model.events
Type:
- «property»
Event emitter that reports any errors that occurred. Useful for global error handling.
Example:
MyModel.events.on('error', err => console.log(err.message));
// Prints a 'CastError' because of the above handler
await MyModel.findOne({ _id: 'notanid' }).catch(noop);
Model.exists()
Parameters
- filter «Object»
-
[options] «Object» optional see
Query.prototype.setOptions() -
[callback] «Function» callback
Returns:
- «Promise»
Returns true if at least one document exists in the database that matches the given filter, and false otherwise.
Under the hood, MyModel.exists({ answer: 42 }) is equivalent to MyModel.findOne({ answer: 42 }).select({ _id: 1 }).lean().then(doc => !!doc)
Example:
await Character.deleteMany({});
await Character.create({ name: 'Jean-Luc Picard' });
await Character.exists({ name: /picard/i }); // true
await Character.exists({ name: /riker/i }); // false
This function triggers the following middleware.
findOne()
Model.find()
Parameters
- filter «Object|ObjectId»
-
[projection] «Object|String|Array<String>» optional fields to return, see
Query.prototype.select() -
[options] «Object» optional see
Query.prototype.setOptions() -
[callback] «Function»
Returns:
- «Query»
Finds documents.
Mongoose casts the filter to match the model‘s schema before the command is sent. See our query casting tutorial for more information on how Mongoose casts filter.
Examples:
// find all documents
await MyModel.find({});
// find all documents named john and at least 18
await MyModel.find({ name: 'john', age: { $gte: 18 } }).exec();
// executes, passing results to callback
MyModel.find({ name: 'john', age: { $gte: 18 }}, function (err, docs) {});
// executes, name LIKE john and only selecting the "name" and "friends" fields
await MyModel.find({ name: /john/i }, 'name friends').exec();
// passing options
await MyModel.find({ name: /john/i }, null, { skip: 10 }).exec();
Model.findById()
Parameters
-
id «Any» value of
_idto query by -
[projection] «Object|String|Array<String>» optional fields to return, see
Query.prototype.select() -
[options] «Object» optional see
Query.prototype.setOptions() -
[callback] «Function»
Returns:
- «Query»
Finds a single document by its _id field. findById(id) is almost* equivalent to findOne({ _id: id }). If you want to query by a document‘s _id, use findById() instead of findOne().
The id is cast based on the Schema before sending the command.
This function triggers the following middleware.
-
findOne() -
Except for how it treats
undefined. If you usefindOne(), you‘ll see thatfindOne(undefined)andfindOne({ _id: undefined })are equivalent tofindOne({})and return arbitrary documents. However, mongoose translatesfindById(undefined)intofindOne({ _id: null }).
Example:
// Find the adventure with the given `id`, or `null` if not found
await Adventure.findById(id).exec();
// using callback
Adventure.findById(id, function (err, adventure) {});
// select only the adventures name and length
await Adventure.findById(id, 'name length').exec();
Model.findByIdAndDelete()
Parameters
-
id «Object|Number|String» value of
_idto query by -
[options] «Object» optional see
Query.prototype.setOptions() -
[options.strict] «Boolean|String» overwrites the schema‘s strict mode option
-
[callback] «Function»
Returns:
- «Query»
Issue a MongoDB findOneAndDelete() command by a document‘s _id field. In other words, findByIdAndDelete(id) is a shorthand for findOneAndDelete({ _id: id }).
This function triggers the following middleware.
findOneAndDelete()
Model.findByIdAndRemove()
Parameters
-
id «Object|Number|String» value of
_idto query by -
[options] «Object» optional see
Query.prototype.setOptions() -
[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.projection=null] «Object|String|Array<String>» optional fields to return, see
Query.prototype.select() -
[callback] «Function»
Returns:
- «Query»
Issue a mongodb findAndModify remove command by a document‘s _id field. findByIdAndRemove(id, ...) is equivalent to findOneAndRemove({ _id: id }, ...).
Finds a matching document, removes it, passing the found document (if any) to the callback.
Executes the query if callback is passed.
This function triggers the following middleware.
findOneAndRemove()
Options:
sort: if multiple docs are found by the conditions, sets the sort order to choose which doc to updateselect: sets the document fields to returnrawResult: if true, returns the raw result from the MongoDB driverstrict: overwrites the schema‘s strict mode option for this update
Examples:
A.findByIdAndRemove(id, options, callback) // executes
A.findByIdAndRemove(id, options) // return Query
A.findByIdAndRemove(id, callback) // executes
A.findByIdAndRemove(id) // returns Query
A.findByIdAndRemove() // returns Query
Model.findByIdAndUpdate()
Parameters
-
id «Object|Number|String» value of
_idto query by -
[update] «Object»
-
[options] «Object» optional see
Query.prototype.setOptions() -
[options.new=false] «Boolean» By default,
findByIdAndUpdate()returns the document as it was beforeupdatewas applied. If you setnew: true,findOneAndUpdate()will instead give you the object afterupdatewas applied. To change the default totrue, usemongoose.set('returnOriginal', false);. -
[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. -
[options.overwrite=false] «Boolean» By default, if you don‘t include any update operators in
update, Mongoose will wrapupdatein$setfor you. This prevents you from accidentally overwriting the document. This option tells Mongoose to skip adding$set. An alternative to this would be using Model.findOneAndReplace({ _id: id }, update, options, callback). -
[callback] «Function»
Returns:
- «Query»
Issues a mongodb findAndModify update 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) to the callback. The query executes if callback is passed.
This function triggers the following middleware.
findOneAndUpdate()
Options:
new: bool - true to return the modified document rather than the original. defaults to falseupsert: bool - creates the object if it doesn‘t exist. defaults to false.runValidators: 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.sort: if multiple docs are found by the conditions, sets the sort order to choose which doc to updateselect: sets the document fields to returnrawResult: if true, returns the raw result from the MongoDB driverstrict: overwrites the schema‘s strict mode option for this update
Examples:
A.findByIdAndUpdate(id, update, options, callback) // executes
A.findByIdAndUpdate(id, update, options) // returns Query
A.findByIdAndUpdate(id, update, callback) // executes
A.findByIdAndUpdate(id, update) // returns Query
A.findByIdAndUpdate() // returns Query
Note:
All top level update keys which are not atomic operation names are treated as set operations:
Example:
Model.findByIdAndUpdate(id, { name: 'jason bourne' }, options, callback)
// is sent as
Model.findByIdAndUpdate(id, { $set: { name: 'jason bourne' }}, options, callback)
This helps prevent accidentally overwriting your document with { name: 'jason bourne' }.
Note:
Values are cast to their appropriate types when using the findAndModify helpers. However, the below are not executed by default.
- defaults. Use the
setDefaultsOnInsertoption to override.
findAndModify helpers support limited validation. You can enable these by setting the runValidators options, respectively.
If you need full-fledged validation, use the traditional approach of first retrieving the document.
Model.findById(id, function (err, doc) {
if (err) ..
doc.name = 'jason bourne';
doc.save(callback);
});
Model.findOne()
Parameters
- [conditions] «Object»
-
[projection] «Object|String|Array<String>» optional fields to return, see
Query.prototype.select() -
[options] «Object» optional see
Query.prototype.setOptions() -
[callback] «Function»
Returns:
- «Query»
Finds one document.
The conditions are cast to their respective SchemaTypes before the command is sent.
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 findById() instead.
Example:
// Find one adventure whose `country` is 'Croatia', otherwise `null`
await Adventure.findOne({ country: 'Croatia' }).exec();
// using callback
Adventure.findOne({ country: 'Croatia' }, function (err, adventure) {});
// select only the adventures name and length
await Adventure.findOne({ country: 'Croatia' }, 'name length').exec();
Model.findOneAndDelete()
Parameters
- conditions «Object»
-
[options] «Object» optional see
Query.prototype.setOptions() -
[options.strict] «Boolean|String» overwrites the schema‘s strict mode option
-
[options.projection=null] «Object|String|Array<String>» optional fields to return, see
Query.prototype.select() -
[options.session=null] «ClientSession» The session associated with this query. See transactions docs.
-
[callback] «Function»
Returns:
- «Query»
Issue a MongoDB findOneAndDelete() command.
Finds a matching document, removes it, and passes the found document (if any) to the callback.
Executes the query 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.
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.0select: sets the document fields to return, ex.{ projection: { _id: 0 } }projection: equivalent toselectrawResult: if true, returns the raw result from the MongoDB driverstrict: overwrites the schema‘s strict mode option for this update
Examples:
A.findOneAndDelete(conditions, options, callback) // executes
A.findOneAndDelete(conditions, options) // return Query
A.findOneAndDelete(conditions, callback) // executes
A.findOneAndDelete(conditions) // returns Query
A.findOneAndDelete() // returns Query
Values are cast to their appropriate types when using the findAndModify helpers. However, the below are not executed by default.
- defaults. Use the
setDefaultsOnInsertoption to override.
findAndModify helpers support limited validation. You can enable these by setting the runValidators options, respectively.
If you need full-fledged validation, use the traditional approach of first retrieving the document.
Model.findById(id, function (err, doc) {
if (err) ..
doc.name = 'jason bourne';
doc.save(callback);
});
Model.findOneAndRemove()
Parameters
- conditions «Object»
-
[options] «Object» optional see
Query.prototype.setOptions() -
[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.projection=null] «Object|String|Array<String>» optional fields to return, see
Query.prototype.select() -
[callback] «Function»
Returns:
- «Query»
Issue a mongodb findAndModify remove command.
Finds a matching document, removes it, passing the found document (if any) to the callback.
Executes the query if callback is passed.
This function triggers the following middleware.
findOneAndRemove()
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.0select: sets the document fields to returnprojection: like select, it determines which fields to return, ex.{ projection: { _id: 0 } }rawResult: if true, returns the raw result from the MongoDB driverstrict: overwrites the schema‘s strict mode option for this update
Examples:
A.findOneAndRemove(conditions, options, callback) // executes
A.findOneAndRemove(conditions, options) // return Query
A.findOneAndRemove(conditions, callback) // executes
A.findOneAndRemove(conditions) // returns Query
A.findOneAndRemove() // returns Query
Values are cast to their appropriate types when using the findAndModify helpers. However, the below are not executed by default.
- defaults. Use the
setDefaultsOnInsertoption to override.
findAndModify helpers support limited validation. You can enable these by setting the runValidators options, respectively.
If you need full-fledged validation, use the traditional approach of first retrieving the document.
Model.findById(id, function (err, doc) {
if (err) ..
doc.name = 'jason bourne';
doc.save(callback);
});
Model.findOneAndReplace()
Parameters
-
filter «Object» Replace the first document that matches this filter
-
[replacement] «Object» Replace with this document
-
[options] «Object» optional see
Query.prototype.setOptions() -
[options.new=false] «Boolean» By default,
findOneAndReplace()returns the document as it was beforeupdatewas applied. If you setnew: true,findOneAndReplace()will instead give you the object afterupdatewas applied. To change the default totrue, usemongoose.set('returnOriginal', false);. -
[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. -
[options.projection=null] «Object|String|Array<String>» optional fields to return, see
Query.prototype.select() -
[callback] «Function»
Returns:
- «Query»
Issue a MongoDB findOneAndReplace() command.
Finds a matching document, replaces it with the provided doc, and passes the returned doc to the callback.
Executes the query if callback is passed.
This function triggers the following query middleware.
findOneAndReplace()
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.0select: sets the document fields to returnprojection: like select, it determines which fields to return, ex.{ projection: { _id: 0 } }rawResult: if true, returns the raw result from the MongoDB driverstrict: overwrites the schema‘s strict mode option for this update
Examples:
A.findOneAndReplace(conditions, options, callback) // executes
A.findOneAndReplace(conditions, options) // return Query
A.findOneAndReplace(conditions, callback) // executes
A.findOneAndReplace(conditions) // returns Query
A.findOneAndReplace() // returns Query
Values are cast to their appropriate types when using the findAndModify helpers. However, the below are not executed by default.
- defaults. Use the
setDefaultsOnInsertoption to override.
Model.findOneAndUpdate()
Parameters
- [conditions] «Object»
- [update] «Object»
-
[options] «Object» optional see
Query.prototype.setOptions() -
[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. To change the default totrue, usemongoose.set('returnOriginal', false);. -
[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 [transa
(本文超出站点单文档体积上限,已截断)
