Model()
Model.$where()
Model.aggregate()
Model.applyDefaults()
Model.applyTimestamps()
Model.applyVirtuals()
Model.bulkSave()
Model.bulkWrite()
Model.castObject()
Model.cleanIndexes()
Model.countDocuments()
Model.create()
Model.createCollection()
Model.createIndexes()
Model.createSearchIndex()
Model.db
Model.deleteMany()
Model.deleteOne()
Model.diffIndexes()
Model.discriminator()
Model.distinct()
Model.dropSearchIndex()
Model.ensureIndexes()
Model.estimatedDocumentCount()
Model.events
Model.exists()
Model.find()
Model.findById()
Model.findByIdAndDelete()
Model.findByIdAndUpdate()
Model.findOne()
Model.findOneAndDelete()
Model.findOneAndReplace()
Model.findOneAndUpdate()
Model.hydrate()
Model.init()
Model.insertMany()
Model.insertOne()
Model.inspect()
Model.listIndexes()
Model.listSearchIndexes()
Model.namespace()
Model.populate()
Model.prototype.$model()
Model.prototype.$where
Model.prototype.base
Model.prototype.baseModelName
Model.prototype.collection
Model.prototype.collection
Model.prototype.db
Model.prototype.deleteOne()
Model.prototype.discriminators
Model.prototype.increment()
Model.prototype.model()
Model.prototype.modelName
Model.prototype.save()
Model.recompileSchema()
Model.replaceOne()
Model.schema
Model.startSession()
Model.syncIndexes()
Model.translateAliases()
Model.updateMany()
Model.updateOne()
Model.updateSearchIndex()
Model.useConnection()
Model.validate()
Model.watch()
Model.where()
Model()
doc
«Object» values for initial set[fields]
«Object» optional 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 _id
field to the document.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.
// `UserModel` is a "Model", a subclass of `mongoose.Model`.constUserModel = mongoose.model('User', newSchema({ name: String })); // You can use a Model to create new documents using `new`:const userDoc = newUserModel({ name: 'Foo' }); await userDoc.save(); // You also use a model to create queries:const userFromDb = awaitUserModel.findOne({ name: 'Foo' });
Model.$where()
argument
«String|Function» is a javascript string or anonymous functionCreates a Query
and specifies a $where
condition.
Sometimes you need to query for things in mongodb using a JavaScript expression. You can do so via find({ $where: javascript })
, or you can use the mongoose shortcut method $where via a Query chain or from your mongoose Model.
Blog.$where('this.username.indexOf("val") !== -1').exec(function (err, docs) {});
Model.aggregate()
[pipeline]
«Array» aggregation pipeline as an array of objects[options]
«Object» aggregation optionsPerforms aggregations on the models collection.
The aggregate
itself is returned.
This function triggers the following middleware.
aggregate()
// Find the max balance of all accountsconst res = awaitUsers.aggregate([ { $group: { _id: null, maxBalance: { $max: '$balance' }}}, { $project: { _id: 0, maxBalance: 1 }} ]); console.log(res); // [ { maxBalance: 98000 } ]// Or use the aggregation pipeline builder.const res = awaitUsers.aggregate(). group({ _id: null, maxBalance: { $max: '$balance' } }). project('-id maxBalance'). exec(); console.log(res); // [ { maxBalance: 98 } ]
$project
and $group
operators 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.Model.applyDefaults()
obj
«Object|Document» object or document to apply defaults onApply defaults to the given document or POJO.
Model.applyTimestamps()
obj
«Object» object or document to apply virtuals on[options]
«Object»[options.isUpdate=false]
«Boolean» if true, treat this as an update: just set updatedAt, skip setting createdAt. If false, set both createdAt and updatedAt[options.currentTime]
«Function» if set, Mongoose will call this function to get the current time.Apply this model's timestamps to a given POJO, including subdocument timestamps
const userSchema = newSchema({ name: String }, { timestamps: true }); constUser = mongoose.model('User', userSchema); const obj = { name: 'John' }; User.applyTimestamps(obj); obj.createdAt; // 2024-06-01T18:00:00.000Z obj.updatedAt; // 2024-06-01T18:00:00.000Z
Model.applyVirtuals()
obj
«Object» object or document to apply virtuals on[virtualsToApply]
«Array<string>» optional whitelist of virtuals to applyApply this model's virtuals to a given POJO. Virtuals execute with the POJO as the context this
.
const userSchema = newSchema({ name: String }); userSchema.virtual('upper').get(function() { returnthis.name.toUpperCase(); }); constUser = mongoose.model('User', userSchema); const obj = { name: 'John' }; User.applyVirtuals(obj); obj.name; // 'John' obj.upper; // 'JOHN', Mongoose applied the return value of the virtual to the given object
Model.bulkSave()
documents
«Array<Document>»[options]
«Object» options passed to the underlying bulkWrite()
[options.timestamps]
«Boolean» defaults to null
, when set to false, mongoose will not add/update timestamps to the documents.[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.validateBeforeSave=true]
«Boolean» set to false
to skip Mongoose validation on all documentsbulkWrite()
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+)
bulkSave()
throws errors under the following conditions:
bulkSave()
does not send a bulkWrite()
, and throws the first validation error.bulkWrite()
fails (for example, due to being unable to connect to MongoDB or due to duplicate key error)bulkWrite()
did not insert or update any documents. In this case, bulkSave()
will throw a DocumentNotFound error.Note that bulkSave()
will not throw an error if only some of the save()
calls succeeded.
Model.bulkWrite()
ops
«Array»[ops.insertOne.document]
«Object» The document to insert[ops.insertOne.timestamps=true]
«Object» If false, do not apply timestamps to the operation[ops.updateOne.filter]
«Object» Update the first document that matches this filter[ops.updateOne.update]
«Object» An object containing update operators[ops.updateOne.upsert=false]
«Boolean» If true, insert a doc if none match[ops.updateOne.timestamps=true]
«Boolean» If false, do not apply timestamps to the operation[ops.updateOne.collation]
«Object» The MongoDB collation to use[ops.updateOne.arrayFilters]
«Array» The array filters used in update
[ops.updateMany.filter]
«Object» Update all the documents that match this filter[ops.updateMany.update]
«Object» An object containing update operators[ops.updateMany.upsert=false]
«Boolean» If true, insert a doc if no documents match filter
[ops.updateMany.timestamps=true]
«Boolean» If false, do not apply timestamps to the operation[ops.updateMany.collation]
«Object» The MongoDB collation to use[ops.updateMany.arrayFilters]
«Array» The array filters used in update
[ops.deleteOne.filter]
«Object» Delete the first document that matches this filter[ops.deleteMany.filter]
«Object» Delete all documents that match this filter[ops.replaceOne.filter]
«Object» Replace the first document that matches this filter[ops.replaceOne.replacement]
«Object» The replacement document[ops.replaceOne.upsert=false]
«Boolean» If true, insert a doc if no documents match filter
[ops.replaceOne.timestamps=true]
«Object» If false, do not apply timestamps to the operation[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.timestamps=true]
«Boolean» If false, do not apply timestamps to any operations. Can be overridden at the operation-level.[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.skipValidation=false]
«Boolean» Set to true to skip Mongoose schema validation on bulk write operations. Mongoose currently runs validation on insertOne
and replaceOne
operations by default.[options.bypassDocumentValidation=false]
«Boolean» If true, disable MongoDB server-side schema validation for all writes in this bulk.[options.throwOnValidationError=false]
«Boolean» If true and ordered: false
, throw an error if one of the operations failed validation, but all valid operations completed successfully. Note that Mongoose will still send all valid operations to the MongoDB server.[options.strict=null]
«Boolean|[object Object]» Overwrites the strict
option on schema. If false, allows filtering and writing fields not defined in the schema for all writes in this bulk.BulkWriteOpResult
if the operation succeedsSends 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. The only exception is setting the update
operator for updateOne
or updateMany
to a pipeline: Mongoose does not cast update pipelines.
This function does not trigger any middleware, neither save()
, nor update()
. If you need to trigger save()
middleware for every document use create()
instead.
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); }); // Mongoose does **not** cast update pipelines, so no casting for the `update` option below.// Mongoose does still cast `filter`awaitCharacter.bulkWrite([{ updateOne: { filter: { name: 'Annika Hansen' }, update: [{ $set: { name: 7 } }] // Array means update pipeline, so Mongoose skips casting } }]);
The supported operations are:
insertOne
updateOne
updateMany
deleteOne
deleteMany
replaceOne
Model.castObject()
obj
«Object» object or document to castoptions
«Object» options passed to castObjectoptions.ignoreCastErrors
«Boolean» If set to true
will not throw a ValidationError and only return values that were successfully cast.Cast the given POJO to the model's schema
constTest = mongoose.model('Test', Schema({ num: Number })); const obj = Test.castObject({ num: '42' }); obj.num; // 42 as a numberTest.castObject({ num: 'not a number' }); // Throws a ValidationError
Model.cleanIndexes()
[options]
«Object»[options.toDrop]
«Array<String>» if specified, contains a list of index names to drop[options.hideIndexes=false]
«Boolean» set to true
to hide indexes instead of dropping. Requires MongoDB server 4.4 or higherDeletes 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.countDocuments()
filter
«Object»Counts number of documents matching filter
in a database collection.
const count = awaitAdventure.countDocuments({ type: 'jungle' }); 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
: $geoWithin
with $center
$nearSphere
: $geoWithin
with $centerSphere
Model.create()
docs
«Array|Object» Documents to insert, as a spread or array[options]
«Object» Options passed down to save()
. To specify options
, docs
must be an array, not a spread. See Model.save for available options.[options.ordered]
«Boolean» saves the docs in series rather than parallel.[options.aggregateErrors]
«Boolean» Aggregate Errors instead of throwing the first one that occurs. Default: falseShortcut 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()
// Insert one new `Character` documentawaitCharacter.create({ name: 'Jean-Luc Picard' }); // Insert multiple new `Character` documentsawaitCharacter.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.awaitCharacter.create([{ name: 'Jean-Luc Picard' }], { session });
Model.createCollection()
[options]
«Object» see MongoDB driver docsCreate 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://www.mongodb.com/docs/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()
const userSchema = newSchema({ name: String }) constUser = mongoose.model('User', userSchema); User.createCollection().then(function(collection) { console.log('Collection is created!'); });
Model.createIndexes()
[options]
«Object» internal optionsSimilar to ensureIndexes()
, except for it uses the createIndex
function.
Model.createSearchIndex()
description
«Object» index options, including name
and definition
description.name
«String»description.definition
«Object»Create an Atlas search index. This function only works when connected to MongoDB Atlas.
const schema = newSchema({ name: { type: String, unique: true } }); constCustomer = mongoose.model('Customer', schema); awaitCustomer.createSearchIndex({ name: 'test', definition: { mappings: { dynamic: true } } });
Model.db
Connection instance the model uses.
Model.deleteMany()
conditions
«Object»[options]
«Object» optional see Query.prototype.setOptions()
[options.translateAliases=null]
«Boolean» If set to true
, translates any schema-defined aliases in filter
, projection
, update
, and distinct
. Throws an error if there are any conflicts where both alias and raw property are defined on the same object.Deletes all of the documents that match conditions
from the collection. It returns an object with the property deletedCount
containing the number of documents deleted.
awaitCharacter.deleteMany({ name: /Stark/, age: { $gte: 18 } }); // returns {deletedCount: x} where x is the number of documents deleted.
This function triggers deleteMany
query hooks. Read the middleware docs to learn more.
Model.deleteOne()
conditions
«Object»[options]
«Object» optional see Query.prototype.setOptions()
[options.translateAliases=null]
«Boolean» If set to true
, translates any schema-defined aliases in filter
, projection
, update
, and distinct
. Throws an error if there are any conflicts where both alias and raw property are defined on the same object.Deletes the first document that matches conditions
from the collection. It returns an object with the property deletedCount
indicating how many documents were deleted.
awaitCharacter.deleteOne({ name: 'Eddard Stark' }); // returns {deletedCount: 1}
This function triggers deleteOne
query hooks. Read the middleware docs to learn more.
Model.diffIndexes()
[options]
«Object»[options.indexOptionsToCreate=false]
«Boolean» If true, toCreate
will include both the index spec and the index options, not just the index spec{ toDrop: string[], toCreate: string[] }
.Does a dry-run of Model.syncIndexes()
, returning the indexes that syncIndexes()
would drop and create if you were to run syncIndexes()
.
const { toDrop, toCreate } = awaitModel.diffIndexes(); toDrop; // Array of strings containing names of indexes that `syncIndexes()` will drop toCreate; // Array of index specs containing the keys of indexes that `syncIndexes()` will create
Model.discriminator()
name
«String» discriminator model nameschema
«Schema» discriminator model schema[options]
«Object|String» If string, same as options.value
.[options.value]
«String» the string stored in the discriminatorKey
property. If not specified, Mongoose uses the name
parameter.[options.clone=true]
«Boolean» By default, discriminator()
clones the given schema
. Set to false
to skip cloning.[options.overwriteModels=false]
«Boolean» by default, Mongoose does not allow you to define a discriminator with the same name as another discriminator. Set this to allow overwriting discriminators with the same name.[options.mergeHooks=true]
«Boolean» By default, Mongoose merges the base schema's hooks with the discriminator schema's hooks. Set this option to false
to make Mongoose use the discriminator schema's hooks instead.[options.mergePlugins=true]
«Boolean» By default, Mongoose merges the base schema's plugins with the discriminator schema's plugins. Set this option to false
to make Mongoose use the discriminator schema's plugins instead.Adds a discriminator type.
functionBaseSchema() { Schema.apply(this, arguments); this.add({ name: String, createdAt: Date }); } util.inherits(BaseSchema, Schema); constPersonSchema = newBaseSchema(); constBossSchema = newBaseSchema({ department: String }); constPerson = mongoose.model('Person', PersonSchema); constBoss = Person.discriminator('Boss', BossSchema); newBoss().__t; // "Boss". `__t` is the default `discriminatorKey`const employeeSchema = newSchema({ boss: ObjectId }); constEmployee = Person.discriminator('Employee', employeeSchema, 'staff'); newEmployee().__t; // "staff" because of 3rd argument above
Model.distinct()
field
«String»[conditions]
«Object» optional[options]
«Object» optionalCreates a Query for a distinct
operation.
const query = Link.distinct('url'); query.exec();
Model.dropSearchIndex()
name
«String»Delete an existing Atlas search index by name. This function only works when connected to MongoDB Atlas.
const schema = newSchema({ name: { type: String, unique: true } }); constCustomer = mongoose.model('Customer', schema); awaitCustomer.dropSearchIndex('test');
Model.ensureIndexes()
[options]
«Object» internal optionsSends createIndex
commands to mongo for each index declared in the schema. The createIndex
commands are sent in series.
awaitEvent.ensureIndexes();
After completion, an index
event is emitted on this Model
passing an error if one occurred.
const eventSchema = newSchema({ thing: { type: 'string', unique: true } }) constEvent = 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()
[options]
«Object»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.
const numAdventures = awaitAdventure.estimatedDocumentCount();
Model.events
Event emitter that reports any errors that occurred. Useful for global error handling.
MyModel.events.on('error', err =>console.log(err.message)); // Prints a 'CastError' because of the above handlerawaitMyModel.findOne({ _id: 'Not a valid ObjectId' }).catch(noop);
Model.exists()
filter
«Object»[options]
«Object» optional see Query.prototype.setOptions()
Returns a document with _id
only if at least one document exists in the database that matches the given filter
, and null
otherwise.
Under the hood, MyModel.exists({ answer: 42 })
is equivalent to MyModel.findOne({ answer: 42 }).select({ _id: 1 }).lean()
awaitCharacter.deleteMany({}); awaitCharacter.create({ name: 'Jean-Luc Picard' }); awaitCharacter.exists({ name: /picard/i }); // { _id: ... }awaitCharacter.exists({ name: /riker/i }); // null
This function triggers the following middleware.
findOne()
Model.find()
filter
«Object|ObjectId»[projection]
«Object|String|Array[String]» optional fields to return, see Query.prototype.select()
[options]
«Object» optional see Query.prototype.setOptions()
[options.translateAliases=null]
«Boolean» If set to true
, translates any schema-defined aliases in filter
, projection
, update
, and distinct
. Throws an error if there are any conflicts where both alias and raw property are defined on the same object.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
.
// find all documentsawaitMyModel.find({}); // find all documents named john and at least 18awaitMyModel.find({ name: 'john', age: { $gte: 18 } }).exec(); // executes, name LIKE john and only selecting the "name" and "friends" fieldsawaitMyModel.find({ name: /john/i }, 'name friends').exec(); // passing optionsawaitMyModel.find({ name: /john/i }, null, { skip: 10 }).exec();
Model.findById()
id
«Any» value of _id
to query by[projection]
«Object|String|Array[String]» optional fields to return, see Query.prototype.select()
[options]
«Object» optional see Query.prototype.setOptions()
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 use findOne()
, you'll see that findOne(undefined)
and findOne({ _id: undefined })
are equivalent to findOne({})
and return arbitrary documents. However, mongoose translates findById(undefined)
into findOne({ _id: null })
.
// Find the adventure with the given `id`, or `null` if not foundawaitAdventure.findById(id).exec(); // select only the adventures name and lengthawaitAdventure.findById(id, 'name length').exec();
Model.findByIdAndDelete()
id
«Object|Number|String» value of _id
to query by[options]
«Object» optional see Query.prototype.setOptions()
[options.strict]
«Boolean|String» overwrites the schema's strict mode option[options.translateAliases=null]
«Boolean» If set to true
, translates any schema-defined aliases in filter
, projection
, update
, and distinct
. Throws an error if there are any conflicts where both alias and raw property are defined on the same object.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.findByIdAndUpdate()
id
«Object|Number|String» value of _id
to query by[update]
«Object»[options]
«Object» optional see Query.prototype.setOptions()
[options.returnDocument='before']
«String» Has two possible values, 'before'
and 'after'
. By default, it will return the document before the update was applied.[options.lean]
«Object» if truthy, mongoose will return the document as a plain JavaScript object rather than a mongoose document. See Query.lean()
and 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.timestamps=null]
«Boolean» If set to false
and schema-level timestamps are enabled, skip timestamps for this update. Note that this allows you to overwrite timestamps. Does nothing if schema-level timestamps are not set.[options.sort]
«Object|String» if multiple docs are found by the conditions, sets the sort order to choose which doc to update.[options.runValidators]
«Boolean» if true, runs update validators on this command. Update validators validate the update operation against the model's schema[options.setDefaultsOnInsert=true]
«Boolean» If setDefaultsOnInsert
and upsert
are true, mongoose will apply the defaults specified in the model's schema if a new document is created[options.includeResultMetadata]
«Boolean» if true, returns the full ModifyResult from the MongoDB driver rather than just the document[options.upsert=false]
«Boolean» if true, and no documents found, insert a new document[options.new=false]
«Boolean» if true, return the modified document rather than the original[options.select]
«Object|String» sets the document fields to return.[options.translateAliases=null]
«Boolean» If set to true
, translates any schema-defined aliases in filter
, projection
, update
, and distinct
. Throws an error if there are any conflicts where both alias and raw property are defined on the same object.[options.overwriteDiscriminatorKey=false]
«Boolean» Mongoose removes discriminator key updates from update
by default, set overwriteDiscriminatorKey
to true
to allow updating the discriminator keyIssues 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.
findOneAndUpdate()
A.findByIdAndUpdate(id, update, options) // returns Query A.findByIdAndUpdate(id, update) // returns Query A.findByIdAndUpdate() // returns Query
All top level update keys which are not atomic
operation names are treated as set operations:
Model.findByIdAndUpdate(id, { name: 'jason bourne' }, options) // is sent asModel.findByIdAndUpdate(id, { $set: { name: 'jason bourne' }}, options)
findOneAndX
and findByIdAndX
functions support limited validation. You can enable validation by setting the runValidators
option.
If you need full-fledged validation, use the traditional approach of first retrieving the document.
const doc = awaitModel.findById(id) doc.name = 'jason bourne'; await doc.save();
Model.findOne()
[conditions]
«Object»[projection]
«Object|String|Array[String]» optional fields to return, see Query.prototype.select()
[options]
«Object» optional see Query.prototype.setOptions()
[options.translateAliases=null]
«Boolean» If set to true
, translates any schema-defined aliases in filter
, projection
, update
, and distinct
. Throws an error if there are any conflicts where both alias and raw property are defined on the same object.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.
// Find one adventure whose `country` is 'Croatia', otherwise `null`awaitAdventure.findOne({ country: 'Croatia' }).exec(); // Model.findOne() no longer accepts a callback// Select only the adventures name and lengthawaitAdventure.findOne({ country: 'Croatia' }, 'name length').exec();
Model.findOneAndDelete()
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.[options.includeResultMetadata]
«Boolean» if true, returns the full ModifyResult from the MongoDB driver rather than just the document[options.sort]
«Object|String» if multiple docs are found by the conditions, sets the sort order to choose which doc to update.[options.select]
«Object|String» sets the document fields to return.[options.maxTimeMS]
«Number» puts a time limit on the query - requires mongodb >= 2.6.0[options.translateAliases=null]
«Boolean» If set to true
, translates any schema-defined aliases in filter
, projection
, update
, and distinct
. Throws an error if there are any conflicts where both alias and raw property are defined on the same object.Issue a MongoDB findOneAndDelete()
command.
Finds a matching document, removes it, and returns the found document (if any).
This function triggers the following middleware.
findOneAndDelete()
A.findOneAndDelete(conditions, options) // return Query A.findOneAndDelete(conditions) // returns Query A.findOneAndDelete() // returns Query
findOneAndX
and findByIdAndX
functions support limited validation. You can enable validation by setting the runValidators
option.
If you need full-fledged validation, use the traditional approach of first retrieving the document.
const doc = awaitModel.findById(id) doc.name = 'jason bourne'; await doc.save();
Model.findOneAndReplace()
filter
«Object» Replace the first document that matches this filter[replacement]
«Object» Replace with this document[options]
«Object» optional see Query.prototype.setOptions()
[options.returnDocument='before']
«String» Has two possible values, 'before'
and 'after'
. By default, it will return the document before the update was applied.[options.lean]
«Object» if truthy, mongoose will return the document as a plain JavaScript object rather than a mongoose document. See Query.lean()
and 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.timestamps=null]
«Boolean» If set to false
and schema-level timestamps are enabled, skip timestamps for this update. Note that this allows you to overwrite timestamps. Does nothing if schema-level timestamps are not set.[options.projection=null]
«Object|String|Array[String]» optional fields to return, see Query.prototype.select()
[options.sort]
«Object|String» if multiple docs are found by the conditions, sets the sort order to choose which doc to update.[options.includeResultMetadata]
«Boolean» if true, returns the full ModifyResult from the MongoDB driver rather than just the document[options.select]
«Object|String» sets the document fields to return.[options.maxTimeMS]
«Number» puts a time limit on the query - requires mongodb >= 2.6.0[options.translateAliases=null]
«Boolean» If set to true
, translates any schema-defined aliases in filter
, projection
, update
, and distinct
. Throws an error if there are any conflicts where both alias and raw property are defined on the same object.Issue a MongoDB findOneAndReplace()
command.
Finds a matching document, replaces it with the provided doc, and returns the document.
This function triggers the following query middleware.
findOneAndReplace()
A.findOneAndReplace(filter, replacement, options) // return Query A.findOneAndReplace(filter, replacement) // returns Query A.findOneAndReplace() // returns Query
Model.findOneAndUpdate()
[conditions]
«Object»[update]
«Object»[options]
«Object» optional see Query.prototype.setOptions()
[options.returnDocument='before']
«String» Has two possible values, 'before'
and 'after'
. By default, it will return the document before the update was applied.[options.lean]
«Object» if truthy, mongoose will return the document as a plain JavaScript object rather than a mongoose document. See Query.lean()
and 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.timestamps=null]
«Boolean» If set to false
and schema-level timestamps are enabled, skip timestamps for this update. Note that this allows you to overwrite timestamps. Does nothing if schema-level timestamps are not set.[options.upsert=false]
«Boolean» if true, and no documents found, insert a new document[options.projection=null]
«Object|String|Array[String]» optional fields to return, see Query.prototype.select()
[options.new=false]
«Boolean» if true, return the modified document rather than the original[options.fields]
«Object|String» Field selection. Equivalent to .select(fields).findOneAndUpdate()
[options.maxTimeMS]
«Number» puts a time limit on the query - requires mongodb >= 2.6.0[options.sort]
«Object|String» if multiple docs are found by the conditions, sets the sort order to choose which doc to update.[options.runValidators]
«Boolean» if true, runs update validators on this command. Update validators validate the update operation against the model's schema[options.setDefaultsOnInsert=true]
«Boolean» If setDefaultsOnInsert
and upsert
are true, mongoose will apply the defaults specified in the model's schema if a new document is created[options.includeResultMetadata]
«Boolean» if true, returns the raw result from the MongoDB driver[options.translateAliases=null]
«Boolean» If set to true
, translates any schema-defined aliases in filter
, projection
, update
, and distinct
. Throws an error if there are any conflicts where both alias and raw property are defined on the same object.[options.overwriteDiscriminatorKey=false]
«Boolean» Mongoose removes discriminator key updates from update
by default, set overwriteDiscriminatorKey
to true
to allow updating the discriminator keyIssues a mongodb findOneAndUpdate command.
Finds a matching document, updates it according to the update
arg, passing any options
. A Query object is returned.
A.findOneAndUpdate(conditions, update, options) // returns Query A.findOneAndUpdate(conditions, update) // returns Query A.findOneAndUpdate() // returns Query
All top level update keys which are not atomic
operation names are treated as set operations:
const query = { name: 'borne' }; Model.findOneAndUpdate(query, { name: 'jason bourne' }, options) // is sent asModel.findOneAndUpdate(query, { $set: { name: 'jason bourne' }}, options)
findOneAndX
and findByIdAndX
functions support limited validation that you can enable by setting the runValidators
option.
If you need full-fledged validation, use the traditional approach of first retrieving the document.
const doc = awaitModel.findById(id); doc.name = 'jason bourne'; await doc.save();
Model.hydrate()
obj
«Object»[projection]
«Object|String|Array[String]» optional projection containing which fields should be selected for this document[options]
«Object» optional options[options.setters=false]
«Boolean» if true, apply schema setters when hydrating[options.hydratedPopulatedDocs=false]
«Boolean» if true, populates the docs if passing pre-populated dataShortcut for creating a new Document from existing raw data, pre-saved in the DB. The document returned has no paths marked as modified initially.
// hydrate previous data into a Mongoose documentconst mongooseCandy = Candy.hydrate({ _id: '54108337212ffb6d459f854c', type: 'jelly bean' });
Model.init()
This function is responsible for initializing the underlying connection in MongoDB based on schema options. This function performs the following operations:
createCollection()
unless autoCreate
option is turned offensureIndexes()
unless autoIndex
option is turned offcreateSearchIndex()
on all schema search indexes if autoSearchIndex
is enabled.Mongoose calls this function automatically when a model is a created using mongoose.model()
or connection.model()
, so you don't need to call init()
to trigger index builds.
However, you may need to call init()
to get back a promise that will resolve when your indexes are finished. Calling await Model.init()
is helpful if you need to wait for indexes to build before continuing. For example, if you want to wait for unique indexes to build before continuing with a test case.
const eventSchema = newSchema({ thing: { type: 'string', unique: true } }) // This calls `Event.init()` implicitly, so you don't need to call// `Event.init()` on your own.constEvent = mongoose.model('Event', eventSchema); awaitEvent.init(); console.log('Indexes are done building!');
Model.insertMany()
doc(s)
«Array|Object|[object Object]»[options]
«Object» see the mongodb driver options[options.ordered=true]
«Boolean» if true, will fail fast on the first error encountered. If false, will insert all the documents it can and report errors later. An insertMany()
with ordered = false
is called an "unordered" insertMany()
.[options.rawResult=false]
«Boolean» if false, the returned promise resolves to the documents that passed mongoose document validation. If true
, will return the raw result from the MongoDB driver with a mongoose
property that contains validationErrors
and results
if this is an unordered insertMany
.[options.lean=false]
«Boolean» if true
, skips hydrating the documents. This means Mongoose will not cast, validate, or apply defaults to any of the documents passed to insertMany()
. This option is useful if you need the extra performance, but comes with data integrity risk. Consider using with castObject()
and applyDefaults()
.[options.limit=null]
«Number» this limits the number of documents being processed (validation/casting) by mongoose in parallel, this does NOT send the documents in batches to MongoDB. Use this option if you're processing a large number of documents and your app is running out of memory.[options.populate=null]
«String|Object|Array» populates the result documents. This option is a no-op if rawResult
is set.[options.throwOnValidationError=false]
«Boolean» If true and ordered: false
, throw an error if one of the operations failed validation, but all valid operations completed successfully.options.rawResult
was true
, or the documents that passed validation, otherwiseShortcut for validating an array of documents and inserting them into MongoDB if they're all valid. This function is faster than .create()
because it only sends one operation to the server, rather than one for each document.
Mongoose always validates each document before sending insertMany
to MongoDB. So if one document has a validation error, no documents will be saved, unless you set the ordered
option to false.
This function does not trigger save middleware.
This function triggers the following middleware.
insertMany()
const docs = awaitMovies.insertMany([ { name: 'Star Wars' }, { name: 'The Empire Strikes Back' } ]); docs[0].name; // 'Star Wars'// Return raw result from MongoDBconst result = awaitMovies.insertMany([ { name: 'Star Wars' }, { name: 'The Empire Strikes Back' } ], { rawResult: true });
Model.insertOne()
doc
«Object|Document» Document to insert, as a POJO or Mongoose document[options]
«Object» Options passed down to save()
.Shortcut for saving one document to the database. MyModel.insertOne(obj, options)
is almost equivalent to new MyModel(obj).save(options)
. The difference is that insertOne()
checks if obj
is already a document, and checks for discriminators.
This function triggers the following middleware.
save()
// Insert one new `Character` documentconst character = awaitCharacter.insertOne({ name: 'Jean-Luc Picard' }); character.name; // 'Jean-Luc Picard'// Create a new character within a transaction.awaitCharacter.insertOne({ name: 'Jean-Luc Picard' }, { session });
Model.inspect()
Helper for console.log. Given a model named 'MyModel', returns the string 'Model { MyModel }'
.
constMyModel = mongoose.model('Test', Schema({ name: String })); MyModel.inspect(); // 'Model { Test }'console.log(MyModel); // Prints 'Model { Test }'
Model.listIndexes()
Lists the indexes currently defined in MongoDB. This may or may not be the same as the indexes defined in your schema depending on whether you use the autoIndex
option and if you build indexes manually.
Model.listSearchIndexes()
[options]
«Object»List all Atlas search indexes on this model's collection. This function only works when connected to MongoDB Atlas.
const schema = newSchema({ name: { type: String, unique: true } }); constCustomer = mongoose.model('Customer', schema); awaitCustomer.createSearchIndex({ name: 'test', definition: { mappings: { dynamic: true } } }); const res = awaitCustomer.listSearchIndexes(); // Includes `[{ name: 'test' }]`
Model.namespace()
Return the MongoDB namespace for this model as a string. The namespace is the database name, followed by '.', followed by the collection name.
const conn = mongoose.createConnection('mongodb://127.0.0.1:27017/mydb'); constTestModel = conn.model('Test', mongoose.Schema({ name: String })); TestModel.namespace(); // 'mydb.tests'
Model.populate()
docs
«Document|Array» Either a single document or array of documents to populate.options
«Object|String» Either the paths to populate or an object specifying all parameters[options.path=null]
«string» The path to populate.[options.populate=null]
«string|PopulateOptions» Recursively populate paths in the populated documents. See deep populate docs.[options.retainNullValues=false]
«boolean» By default, Mongoose removes null and undefined values from populated arrays. Use this option to make populate()
retain null
and undefined
array entries.[options.getters=false]
«boolean» If true, Mongoose will call any getters defined on the localField
. By default, Mongoose gets the raw value of localField
. For example, you would need to set this option to true
if you wanted to add a lowercase
getter to your localField
.[options.clone=false]
«boolean» When you do BlogPost.find().populate('author')
, blog posts with the same author will share 1 copy of an author
doc. Enable this option to make Mongoose clone populated docs before assigning them.[options.match=null]
«Object|Function» Add an additional filter to the populate query. Can be a filter object containing MongoDB query syntax, or a function that returns a filter object.[options.skipInvalidIds=false]
«Boolean» By default, Mongoose throws a cast error if localField
and foreignField
schemas don't line up. If you enable this option, Mongoose will instead filter out any localField
properties that cannot be casted to foreignField
's schema type.[options.perDocumentLimit=null]
«Number» For legacy reasons, limit
with populate()
may give incorrect results because it only executes a single query for every document being populated. If you set perDocumentLimit
, Mongoose will ensure correct limit
per document by executing a separate query for each document to populate()
. For example, .find().populate({ path: 'test', perDocumentLimit: 2 })
will execute 2 additional queries if .find()
returns 2 documents.[options.strictPopulate=true]
«Boolean» Set to false to allow populating paths that aren't defined in the given model's schema.[options.options=null]
«Object» Additional options like limit
and lean
.[options.transform=null]
«Function» Function that Mongoose will call on every populated document that allows you to transform the populated document.[options.forceRepopulate=true]
«Boolean» Set to false
to prevent Mongoose from repopulating paths that are already populated[options.ordered=false]
«Boolean» Set to true
to execute any populate queries one at a time, as opposed to in parallel. Set this option to true
if populating multiple paths or paths with multiple models in transactions.Populates document references.
Changed in Mongoose 6: the model you call populate()
on should be the "local field" model, not the "foreign field" model.
path
to a document, or null
if no document was found. If false, Mongoose will always set path
to an array, which will be empty if no documents are found. Inferred from schema by default.false
to allow populating paths that aren't in the schema.true
. Set to false
to prevent Mongoose from repopulating paths that are already populatedconstDog = mongoose.model('Dog', newSchema({ name: String, breed: String })); constPerson = mongoose.model('Person', newSchema({ name: String, pet: { type: mongoose.ObjectId, ref: 'Dog' } })); const pets = awaitPet.create([ { name: 'Daisy', breed: 'Beagle' }, { name: 'Einstein', breed: 'Catalan Sheepdog' } ]); // populate many plain objectsconst users = [ { name: 'John Wick', dog: pets[0]._id }, { name: 'Doc Brown', dog: pets[1]._id } ]; awaitUser.populate(users, { path: 'dog', select: 'name' }); users[0].dog.name; // 'Daisy' users[0].dog.breed; // undefined because of `select`
Model.prototype.$model()
[name]
«String» model nameReturns the model instance used to create this document if no name
specified. If name
specified, returns the model with the given name
.
const doc = newTank({}); doc.$model() === Tank; // trueawait doc.$model('User').findById(id);
Model.prototype.$where
Additional properties to attach to the query when calling save()
and isNew
is false.
Model.prototype.base
Base Mongoose instance the model uses.
Model.prototype.baseModelName
If this is a discriminator model, baseModelName
is the name of the base model.
Model.prototype.collection
The collection instance this model uses. A Mongoose collection is a thin wrapper around a [MongoDB Node.js driver collection](MongoDB Node.js driver collection). Using Model.collection
means you bypass Mongoose middleware, validation, and casting.
This property is read-only. Modifying this property is a no-op.
Model.prototype.collection
Collection the model uses.
Model.prototype.db
Connection the model uses.
Model.prototype.deleteOne()
Delete this document from the db. Returns a Query instance containing a deleteOne
operation by this document's _id
.
await product.deleteOne(); awaitProduct.findById(product._id); // null
Since deleteOne()
returns a Query, the deleteOne()
will not execute unless you use either await
, .then()
, .catch()
, or .exec()
product.deleteOne(); // Doesn't do anything product.deleteOne().exec(); // Deletes the document, returns a promise
Model.prototype.discriminators
Registered discriminators for this model.
Model.prototype.increment()
Signal that we desire an increment of this documents version.
const doc = awaitModel.findById(id); doc.increment(); await doc.save();
Model.prototype.model()
[name]
«String» model nameReturns the model instance used to create this document if no name
specified. If name
specified, returns the model with the given name
.
const doc = newTank({}); doc.$model() === Tank; // trueawait doc.$model('User').findById(id);
Model.prototype.modelName
The name of the model
Model.prototype.save()
[options]
«Object» options optional options[options.session=null]
«Session» the session associated with this save operation. If not specified, defaults to the document's associated session.[options.safe]
«Object» (DEPRECATED) overrides schema's safe option. Use the w
option instead.[options.validateBeforeSave]
«Boolean» set to false to save without validating.[options.validateModifiedOnly=false]
«Boolean» if true
, Mongoose will only validate modified paths, as opposed to modified paths and required
paths.[options.w]
«Number|String» set the write concern. Overrides the schema-level writeConcern
option[options.j]
«Boolean» set to true for MongoDB to wait until this save()
has been journaled before resolving the returned promise. Overrides the schema-level writeConcern
option[options.wtimeout]
«Number» sets a timeout for the write concern. Overrides the schema-level writeConcern
option.[options.checkKeys=true]
«Boolean» the MongoDB driver prevents you from saving keys that start with '$' or contain '.' by default. Set this option to false
to skip that check. See restrictions on field names[options.timestamps=true]
«Boolean» if false
and timestamps are enabled, skip timestamps for this save()
.[options.pathsToSave]
«Array» An array of paths that tell mongoose to only validate and save the paths in pathsToSave
.Saves this document by inserting a new document into the database if document.isNew is true
, or sends an updateOne operation with just the modified paths if isNew
is false
.
product.sold = Date.now(); product = await product.save();
If save is successful, the returned promise will fulfill with the document saved.
const newProduct = await product.save(); newProduct === product; // true
Model.recompileSchema()
Apply changes made to this model's schema after this model was compiled. By default, adding virtuals and other properties to a schema after the model is compiled does nothing. Call this function to apply virtuals and properties that were added later.
const schema = new mongoose.Schema({ field: String }); constTestModel = mongoose.model('Test', schema); TestModel.schema.virtual('myVirtual').get(function() { returnthis.field + ' from myVirtual'; }); const doc = newTestModel({ field: 'Hello' }); doc.myVirtual; // undefinedTestModel.recompileSchema(); doc.myVirtual; // 'Hello from myVirtual'
Model.replaceOne()
filter
«Object»doc
«Object»[options]
«Object» optional see Query.prototype.setOptions()
[options.strict]
«Boolean|String» overwrites the schema's strict mode option[options.upsert=false]
«Boolean» if true, and no documents found, insert a new document[options.writeConcern=null]
«Object» sets the write concern for replica sets. Overrides the schema-level write concern[options.timestamps=null]
«Boolean» If set to false
and schema-level timestamps are enabled, skip timestamps for this update. Does nothing if schema-level timestamps are not set.[options.translateAliases=null]
«Boolean» If set to true
, translates any schema-defined aliases in filter
, projection
, update
, and distinct
. Throws an error if there are any conflicts where both alias and raw property are defined on the same object.Replace the existing document with the given document (no atomic operators like $set
).
const res = awaitPerson.replaceOne({ _id: 24601 }, { name: 'Jean Valjean' }); res.matchedCount; // Number of documents matched res.modifiedCount; // Number of documents modified res.acknowledged; // Boolean indicating the MongoDB server received the operation. res.upsertedId; // null or an id containing a document that had to be upserted. res.upsertedCount; // Number indicating how many documents had to be upserted. Will either be 0 or 1.
This function triggers the following middleware.
replaceOne()
Model.schema
Schema the model uses.
Model.startSession()
[options]
«Object» see the mongodb driver options[options.causalConsistency=true]
«Boolean» set to false to disable causal consistencyClientSession
Requires MongoDB >= 3.6.0. Starts a MongoDB session for benefits like causal consistency, retryable writes, and transactions.
Calling MyModel.startSession()
is equivalent to calling MyModel.db.startSession()
.
This function does not trigger any middleware.
const session = awaitPerson.startSession(); let doc = awaitPerson.findOne({ name: 'Ned Stark' }, null, { session }); await doc.deleteOne(); // `doc` will always be null, even if reading from a replica set// secondary. Without causal consistency, it is possible to// get a doc back from the below query if the query reads from a// secondary that is experiencing replication lag. doc = awaitPerson.findOne({ name: 'Ned Stark' }, null, { session, readPreference: 'secondary' });
Model.syncIndexes()
[options]
«Object» options to pass to ensureIndexes()
[options.background=null]
«Boolean» if specified, overrides each index's background
property[options.hideIndexes=false]
«Boolean» set to true
to hide indexes instead of dropping. Requires MongoDB server 4.4 or higherMakes the indexes in MongoDB match the indexes defined in this model's schema. This function will drop any indexes that are not defined in the model's schema except the _id
index, and build any indexes that are in your schema but not in MongoDB.
See the introductory blog post for more information.
const schema = newSchema({ name: { type: String, unique: true } }); constCustomer = mongoose.model('Customer', schema); awaitCustomer.collection.createIndex({ age: 1 }); // Index is not in schema// Will drop the 'age' index and create an index on `name`awaitCustomer.syncIndexes();
You should be careful about running syncIndexes()
on production applications under heavy load, because index builds are expensive operations, and unexpected index drops can lead to degraded performance. Before running syncIndexes()
, you can use the diffIndexes()
function to check what indexes syncIndexes()
will drop and create.
const { toDrop, toCreate } = awaitModel.diffIndexes(); toDrop; // Array of strings containing names of indexes that `syncIndexes()` will drop toCreate; // Array of strings containing names of indexes that `syncIndexes()` will create
Model.translateAliases()
fields
«Object» fields/conditions that may contain aliased keys[errorOnDuplicates]
«Boolean» if true, throw an error if there's both a key and an alias for that key in fields
Translate any aliases fields/conditions so the final query or document object is pure
awaitCharacter.find(Character.translateAliases({ '名': 'Eddard Stark'// Alias for 'name' });
By default, translateAliases()
overwrites raw fields with aliased fields. So if n
is an alias for name
, { n: 'alias', name: 'raw' }
will resolve to { name: 'alias' }
. However, you can set the errorOnDuplicates
option to throw an error if there are potentially conflicting paths. The translateAliases
option for queries uses errorOnDuplicates
.
Only translate arguments of object type anything else is returned raw
Model.updateMany()
filter
«Object»update.
«Object|Array» If array, this update will be treated as an update pipeline and not casted.[options]
«Object» optional see Query.prototype.setOptions()
[options.strict]
«Boolean|String» overwrites the schema's strict mode option[options.upsert=false]
«Boolean» if true, and no documents found, insert a new document[options.writeConcern=null]
«Object» sets the write concern for replica sets. Overrides the schema-level write concern[options.timestamps=null]
«Boolean» If set to false
and schema-level timestamps are enabled, skip timestamps for this update. Does nothing if schema-level timestamps are not set.[options.translateAliases=null]
«Boolean» If set to true
, translates any schema-defined aliases in filter
, projection
, update
, and distinct
. Throws an error if there are any conflicts where both alias and raw property are defined on the same object.[options.overwriteDiscriminatorKey=false]
«Boolean» Mongoose removes discriminator key updates from update
by default, set overwriteDiscriminatorKey
to true
to allow updating the discriminator keySame as updateOne()
, except MongoDB will update all documents that match filter
(as opposed to just the first one) regardless of the value of the multi
option.
Note updateMany will not fire update middleware. Use pre('updateMany')
and post('updateMany')
instead.
const res = awaitPerson.updateMany({ name: /Stark$/ }, { isDeleted: true }); res.matchedCount; // Number of documents matched res.modifiedCount; // Number of documents modified res.acknowledged; // Boolean indicating the MongoDB server received the operation. This may be false if Mongoose did not send an update to the server because the update was empty. res.upsertedId; // null or an id containing a document that had to be upserted. res.upsertedCount; // Number indicating how many documents had to be upserted. Will either be 0 or 1.// Other supported syntaxesawaitPerson.find({ name: /Stark$/ }).updateMany({ isDeleted: true }); // Using chaining syntaxawaitPerson.find().updateMany({ isDeleted: true }); // Set `isDeleted` on _all_ Person documents
This function triggers the following middleware.
updateMany()
Model.updateOne()
filter
«Object»update.
«Object|Array» If array, this update will be treated as an update pipeline and not casted.[options]
«Object» optional see Query.prototype.setOptions()
[options.strict]
«Boolean|String» overwrites the schema's strict mode option[options.upsert=false]
«Boolean» if true, and no documents found, insert a new document[options.writeConcern=null]
«Object» sets the write concern for replica sets. Overrides the schema-level write concern[options.timestamps=null]
«Boolean» If set to false
and schema-level timestamps are enabled, skip timestamps for this update. Note that this allows you to overwrite timestamps. Does nothing if schema-level timestamps are not set.[options.translateAliases=null]
«Boolean» If set to true
, translates any schema-defined aliases in filter
, projection
, update
, and distinct
. Throws an error if there are any conflicts where both alias and raw property are defined on the same object.[options.overwriteDiscriminatorKey=false]
«Boolean» Mongoose removes discriminator key updates from update
by default, set overwriteDiscriminatorKey
to true
to allow updating the discriminator keyUpdate only the first document that matches filter
.
replaceOne()
if you want to overwrite an entire document rather than using atomic operators like $set
.const res = awaitPerson.updateOne({ name: 'Jean-Luc Picard' }, { ship: 'USS Enterprise' }); res.matchedCount; // Number of documents matched res.modifiedCount; // Number of documents modified res.acknowledged; // Boolean indicating the MongoDB server received the operation. This may be false if Mongoose did not send an update to the server because the update was empty. res.upsertedId; // null or an id containing a document that had to be upserted. res.upsertedCount; // Number indicating how many documents had to be upserted. Will either be 0 or 1.// Other supported syntaxesawaitPerson.findOne({ name: 'Jean-Luc Picard' }).updateOne({ ship: 'USS Enterprise' }); // Using chaining syntaxawaitPerson.updateOne({ ship: 'USS Enterprise' }); // Updates first doc's `ship` property
This function triggers the following middleware.
updateOne()
Model.updateSearchIndex()
name
«String»definition
«Object»Update an existing Atlas search index. This function only works when connected to MongoDB Atlas.
const schema = newSchema({ name: { type: String, unique: true } }); constCustomer = mongoose.model('Customer', schema); awaitCustomer.updateSearchIndex('test', { mappings: { dynamic: true } });
Model.useConnection()
[Connection]
«» connection The new connection to useChanges the Connection instance this model uses to make requests to MongoDB. This function is most useful for changing the Connection that a Model defined using mongoose.model()
uses after initialization.
await mongoose.connect('mongodb://127.0.0.1:27017/db1'); constUserModel = mongoose.model('User', mongoose.Schema({ name: String })); UserModel.connection === mongoose.connection; // trueconst conn2 = await mongoose.createConnection('mongodb://127.0.0.1:27017/db2').asPromise(); UserModel.useConnection(conn2); // `UserModel` now stores documents in `db2`, not `db1`UserModel.connection === mongoose.connection; // falseUserModel.connection === conn2; // true conn2.model('User') === UserModel; // true mongoose.model('User'); // Throws 'MissingSchemaError'
Note: useConnection()
does not apply any connection-level plugins from the new connection. If you use useConnection()
to switch a model's connection, the model will still have the old connection's plugins.
Model.validate()
obj
«Object»pathsOrOptions
«Object|Array|String»[context]
«Object»obj
if validation succeededCasts and validates the given object against this model's schema, passing the given context
to custom validators.
constModel = mongoose.model('Test', Schema({ name: { type: String, required: true }, age: { type: Number, required: true } }); try { awaitModel.validate({ name: null }, ['name']) } catch (err) { err instanceof mongoose.Error.ValidationError; // trueObject.keys(err.errors); // ['name'] }
Model.watch()
[pipeline]
«Array»[options]
«Object» see the mongodb driver options[options.hydrate=false]
«Boolean» if true and fullDocument: 'updateLookup'
is set, Mongoose will automatically hydrate fullDocument
into a fully fledged Mongoose documentRequires a replica set running MongoDB >= 3.6.0. Watches the underlying collection for changes using MongoDB change streams.
This function does not trigger any middleware. In particular, it does not trigger aggregate middleware.
The ChangeStream object is an event emitter that emits the following events:
const doc = awaitPerson.create({ name: 'Ned Stark' }); const changeStream = Person.watch().on('change', change =>console.log(change)); // Will print from the above `console.log()`:// { _id: { _data: ... },// operationType: 'delete',// ns: { db: 'mydb', coll: 'Person' },// documentKey: { _id: 5a51b125c5500f5aa094c7bd } }await doc.deleteOne();
Model.where()
path
«String»[val]
«Object» optional valueCreates a Query, applies the passed conditions, and returns the Query.
For example, instead of writing:
User.find({ age: { $gte: 21, $lte: 65 } });
we can instead write:
User.where('age').gte(21).lte(65).exec();
Since the Query class also supports where
you can continue chaining
User .where('age').gte(21).lte(65) .where('name', /^b/i) ... etc