Model


Model()

Parameters:
  • 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.

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

Parameters:
  • argument «String|Function» is a javascript string or anonymous function

Returns:
  • «Query»
See:

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

Parameters:
  • [pipeline] «Array» aggregation pipeline as an array of objects

  • [options] «Object» aggregation options

Returns:
  • «Aggregate»
See:

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
const res = await Users.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 = await Users.aggregate().
  group({ _id: null, maxBalance: { $max: '$balance' } }).
  project('-id maxBalance').
  exec();
console.log(res); // [ { maxBalance: 98 } ]

Note:

  • Mongoose does not cast aggregation pipelines to the model's schema because $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.
  • The documents returned are plain javascript objects, not mongoose documents (since any shape of document can be returned).

More About Aggregations:


Model.applyDefaults()

Parameters:
  • obj «Object|Document» object or document to apply defaults on

Apply defaults to the given document or POJO.


Model.bulkSave()

Parameters:
  • 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.

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

    • [ops.updateOne.filter] «Object» Update the first document that matches this filter

    • [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.arrayFilters] «Array» The array filters used in update

    • [ops.updateMany.filter] «Object» Update all the documents that match this filter

    • [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.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

  • [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.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.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.strict=null] «Boolean» Overwrites the strict option on schema. If false, allows filtering and writing fields not defined in the schema for all writes in this bulk.

Returns:

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:

  • insertOne
  • updateOne
  • updateMany
  • deleteOne
  • deleteMany
  • replaceOne

Model.castObject()

Parameters:
  • obj «Object» object or document to cast

  • options «Object» options passed to castObject

  • options.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

Example:

const Test = mongoose.model('Test', Schema({ num: Number }));

const obj = Test.castObject({ num: '42' });
obj.num; // 42 as a number

Test.castObject({ num: 'not a number' }); // Throws a ValidationError

Model.cleanIndexes()

Parameters:
  • [callback] «Function» optional callback

Returns:
  • «Promise,undefined,void» Returns undefined if 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.countDocuments()

Parameters:
  • filter «Object»
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:


Model.create()

Parameters:
  • 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: false

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:

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://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()

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

Returns:
  • «Promise»

Similar to ensureIndexes(), except for it uses the createIndex function.


Model.createSearchIndex()

Parameters:
  • description «Object» index options, including name and definition

  • description.name «String»
  • description.definition «Object»
Returns:
  • «Promise»

Create an Atlas search index. This function only works when connected to MongoDB Atlas.

Example:

const schema = new Schema({ name: { type: String, unique: true } });
const Customer = mongoose.model('Customer', schema);
await Customer.createSearchIndex({ name: 'test', definition: { mappings: { dynamic: true } } });

Model.db

Type:
  • «property»

Connection instance the model uses.


Model.deleteMany()

Parameters:
  • 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.

Returns:
  • «Query»

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. Behaves like remove(), but deletes all documents that match conditions regardless of the single option.

Example:

await Character.deleteMany({ name: /Stark/, age: { $gte: 18 } }); // returns {deletedCount: x} where x is the number of documents deleted.

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

    • [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.

Returns:
  • «Query»

Deletes the first document that matches conditions from the collection. It returns an object with the property deletedCount indicating how many documents were deleted. Behaves like remove(), but deletes at most one document regardless of the single option.

Example:

await Character.deleteOne({ name: 'Eddard Stark' }); // returns {deletedCount: 1}

Note:

This function triggers deleteOne query hooks. Read the middleware docs to learn more.


Model.diffIndexes()

Parameters:
  • [options] «Object»
Returns:
  • «Promise<Object>» contains the indexes that would be dropped in MongoDB and indexes that would be created in MongoDB as { 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().

Example:

const { toDrop, toCreate } = await Model.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.discriminator()

Parameters:
  • name «String» discriminator model name

  • schema «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.

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

Returns:
  • «Query»

Creates a Query for a distinct operation.

Example:

const query = Link.distinct('url');
query.exec();

Model.dropSearchIndex()

Parameters:
  • name «String»
Returns:
  • «Promise»

Delete an existing Atlas search index by name. This function only works when connected to MongoDB Atlas.

Example:

const schema = new Schema({ name: { type: String, unique: true } });
const Customer = mongoose.model('Customer', schema);
await Customer.dropSearchIndex('test');

Model.ensureIndexes()

Parameters:
  • [options] «Object» internal options

Returns:
  • «Promise»

Sends createIndex commands to mongo for each index declared in the schema. The createIndex commands are sent in series.

Example:

await Event.ensureIndexes();

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»
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 = await 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: 'Not a valid ObjectId' }).catch(noop);

Model.exists()

Parameters:
Returns:
  • «Query»

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

Example:

await Character.deleteMany({});
await Character.create({ name: 'Jean-Luc Picard' });

await Character.exists({ name: /picard/i }); // { _id: ... }
await Character.exists({ name: /riker/i }); // null

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

    • [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.

Returns:
  • «Query»
See:

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.

Example:

// 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, 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:
Returns:
  • «Query»
See:

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

Example:

// Find the adventure with the given `id`, or `null` if not found
await Adventure.findById(id).exec();

// select only the adventures name and length
await Adventure.findById(id, 'name length').exec();

Model.findByIdAndDelete()

Parameters:
  • id «Object|Number|String» value of _id to query by

  • [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.

Returns:
  • «Query»
See:

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

Parameters:
  • 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.session=null] «ClientSession» The session associated with this query. See transactions docs.

    • [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.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.

Returns:
  • «Query»
See:

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

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

This function triggers the following middleware.

  • findOneAndUpdate()

Example:

A.findByIdAndUpdate(id, update, options)  // returns Query
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)

// is sent as
Model.findByIdAndUpdate(id, { $set: { name: 'jason bourne' }}, options)

Note:

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 = await Model.findById(id)
doc.name = 'jason bourne';
await doc.save();

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

    • [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.

Returns:
  • «Query»
See:

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

// Model.findOne() no longer accepts a callback

// 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.session=null] «ClientSession» The session associated with this query. See transactions docs.

    • [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.

Returns:
  • «Query»

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

Example:

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 = await Model.findById(id)
doc.name = 'jason bourne';
await doc.save();

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.returnDocument='before'] «String» Has two possible values, 'before' and 'after'. By default, it will return the document before the update was applied.

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

    • [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.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.

Returns:
  • «Query»

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

Example:

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

Model.findOneAndUpdate()

Parameters:
  • [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.session=null] «ClientSession» The session associated with this query. See transactions docs.

    • [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.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.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.

Returns:
  • «Query»
See:

Issues a mongodb findOneAndUpdate command.

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

Example:

A.findOneAndUpdate(conditions, update, options)  // returns Query
A.findOneAndUpdate(conditions, update)           // returns Query
A.findOneAndUpdate()                             // returns Query

Note:

All top level update keys which are not atomic operation names are treated as set operations:

Example:

const query = { name: 'borne' };
Model.findOneAndUpdate(query, { name: 'jason bourne' }, options)

// is sent as
Model.findOneAndUpdate(query, { $set: { name: 'jason bourne' }}, options)

Note:

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 = await Model.findById(id);
doc.name = 'jason bourne';
await doc.save();

Model.hydrate()

Parameters:
  • 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 data

Returns:
  • «Document» document instance

Shortcut for creating a new Document from existing raw data, pre-saved in the DB. The document returned has no paths marked as modified initially.

Example:

// hydrate previous data into a Mongoose document
const 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 off
  • ensureIndexes() unless autoIndex option is turned off
  • createSearchIndex() 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.

Example:

const eventSchema = new Schema({ thing: { type: 'string', unique: true } })
// This calls `Event.init()` implicitly, so you don't need to call
// `Event.init()` on your own.
const Event = mongoose.model('Event', eventSchema);

await Event.init();
console.log('Indexes are done building!');

Model.insertMany()

Parameters:
  • 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 and validating the documents. This option is useful if you need the extra performance, but Mongoose won't validate the documents before inserting.

    • [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.

Returns:
  • «Promise» resolving to the raw result from the MongoDB driver if options.rawResult was true, or the documents that passed validation, otherwise

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

Example:

await Movies.insertMany([
  { name: 'Star Wars' },
  { name: 'The Empire Strikes Back' }
]);

Model.inspect()

Helper for console.log. Given a model named 'MyModel', returns the string 'Model { MyModel }'.

Example:

const MyModel = mongoose.model('Test', Schema({ name: String }));
MyModel.inspect(); // 'Model { Test }'
console.log(MyModel); // Prints 'Model { Test }'

Model.listIndexes()

Returns:
  • «Promise»

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

Parameters:
  • 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.

  • [callback(err,doc)] «Function» Optional callback, executed upon completion. Receives err and the doc(s).

Returns:
  • «Promise»

Populates document references.

Changed in Mongoose 6: the model you call populate() on should be the "local field" model, not the "foreign field" model.

Available top-level options:

  • path: space delimited path(s) to populate
  • select: optional fields to select
  • match: optional query conditions to match
  • model: optional name of the model to use for population
  • options: optional query options like sort, limit, etc
  • justOne: optional boolean, if true Mongoose will always set 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.
  • strictPopulate: optional boolean, set to false to allow populating paths that aren't in the schema.

Example:

const Dog = mongoose.model('Dog', new Schema({ name: String, breed: String }));
const Person = mongoose.model('Person', new Schema({
  name: String,
  pet: { type: mongoose.ObjectId, ref: 'Dog' }
}));

const pets = await Pet.create([
  { name: 'Daisy', breed: 'Beagle' },
  { name: 'Einstein', breed: 'Catalan Sheepdog' }
]);

// populate many plain objects
const users = [
  { name: 'John Wick', dog: pets[0]._id },
  { name: 'Doc Brown', dog: pets[1]._id }
];
await User.populate(users, { path: 'dog', select: 'name' });
users[0].dog.name; // 'Daisy'
users[0].dog.breed; // undefined because of `select`

Model.prototype.$model()

Parameters:
  • [name] «String» model name

Returns:
  • «Model»

Returns the model instance used to create this document if no name specified. If name specified, returns the model with the given name.

Example:

const doc = new Tank({});
doc.$model() === Tank; // true
await doc.$model('User').findById(id);

Model.prototype.$where

Type:
  • «property»

Additional properties to attach to the query when calling save() and isNew is false.


Model.prototype.base

Type:
  • «property»

Base Mongoose instance the model uses.


Model.prototype.baseModelName

Type:
  • «property»

If this is a discriminator model, baseModelName is the name of the base model.


Model.prototype.collection

Type:
  • «property»

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

Type:
  • «property»

Collection the model uses.


Model.prototype.db

Type:
  • «property»

Connection the model uses.


Model.prototype.deleteOne()

Returns:
  • «Query» Query

Delete this document from the db.

Example:

await product.deleteOne();
await Product.findById(product._id); // null

Model.prototype.discriminators

Type:
  • «property»

Registered discriminators for this model.


Model.prototype.increment()

See:

Signal that we desire an increment of this documents version.

Example:

const doc = await Model.findById(id);
doc.increment();
await doc.save();

Model.prototype.model()

Parameters:
  • [name] «String» model name

Returns:
  • «Model»

Returns the model instance used to create this document if no name specified. If name specified, returns the model with the given name.

Example:

const doc = new Tank({});
doc.$model() === Tank; // true
await doc.$model('User').findById(id);

Model.prototype.modelName

Type:
  • «property»

The name of the model


Model.prototype.save()

Parameters:
Returns:
  • «Promise»
See:

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.

Example:

product.sold = Date.now();
product = await product.save();

If save is successful, the returned promise will fulfill with the document saved.

Example:

const newProduct = await product.save();
newProduct === product; // true

Model.recompileSchema()

Returns:
  • «undefined,void»

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.

Example:

const schema = new mongoose.Schema({ field: String });
const TestModel = mongoose.model('Test', schema);
TestModel.schema.virtual('myVirtual').get(function() {
  return this.field + ' from myVirtual';
});
const doc = new TestModel({ field: 'Hello' });
doc.myVirtual; // undefined

TestModel.recompileSchema();
doc.myVirtual; // 'Hello from myVirtual'

Model.replaceOne()

Parameters:
  • filter «Object»
  • doc «Object»
  • [options] «Object» optional see Query.prototype.setOptions()

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

    • [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.

Returns:
  • «Query»
See:

Replace the existing document with the given document (no atomic operators like $set).

Example:

const res = await Person.replaceOne({ _id: 24601 }, { name: 'Jean Valjean' });
res.matchedCount; // Number of documents matched
res.modifiedCount; // Number of documents modified
res.acknowledged; // Boolean indicating everything went smoothly.
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

Type:
  • «property»

Schema the model uses.


Model.startSession()

Parameters:
  • [options] «Object» see the mongodb driver options

    • [options.causalConsistency=true] «Boolean» set to false to disable causal consistency

Returns:
  • «Promise<ClientSession>» promise that resolves to a MongoDB driver ClientSession

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.

Example:

const session = await Person.startSession();
let doc = await Person.findOne({ name: 'Ned Stark' }, null, { session });
await doc.remove();
// `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 = await Person.findOne({ name: 'Ned Stark' }, null, { session, readPreference: 'secondary' });

Model.syncIndexes()

Parameters:
  • [options] «Object» options to pass to ensureIndexes()

    • [options.background=null] «Boolean» if specified, overrides each index's background property

Returns:
  • «Promise»

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

Example:

const schema = new Schema({ name: { type: String, unique: true } });
const Customer = mongoose.model('Customer', schema);
await Customer.collection.createIndex({ age: 1 }); // Index is not in schema
// Will drop the 'age' index and create an index on `name`
await Customer.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.

Example:

const { toDrop, toCreate } = await Model.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()

Parameters:
  • 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

Returns:
  • «Object» the translated 'pure' fields/conditions

Translate any aliases fields/conditions so the final query or document object is pure

Example:

await Character.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.

Note:

Only translate arguments of object type anything else is returned raw


Model.updateMany()

Parameters:
  • filter «Object»
  • update «Object|Array»
  • [options] «Object» optional see Query.prototype.setOptions()

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

    • [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.

Returns:
  • «Query»
See:

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

Example:

const res = await Person.updateMany({ name: /Stark$/ }, { isDeleted: true });
res.matchedCount; // Number of documents matched
res.modifiedCount; // Number of documents modified
res.acknowledged; // Boolean indicating everything went smoothly.
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.

  • updateMany()

Model.updateOne()

Parameters:
  • filter «Object»
  • update «Object|Array»
  • [options] «Object» optional see Query.prototype.setOptions()

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

    • [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.

Returns:
  • «Query»
See:

Update only the first document that matches filter.

  • Use replaceOne() if you want to overwrite an entire document rather than using atomic operators like $set.

Example:

const res = await Person.updateOne({ name: 'Jean-Luc Picard' }, { ship: 'USS Enterprise' });
res.matchedCount; // Number of documents matched
res.modifiedCount; // Number of documents modified
res.acknowledged; // Boolean indicating everything went smoothly.
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.

  • updateOne()

Model.updateSearchIndex()

Parameters:
  • name «String»
  • definition «Object»
Returns:
  • «Promise»

Update an existing Atlas search index. This function only works when connected to MongoDB Atlas.

Example:

const schema = new Schema({ name: { type: String, unique: true } });
const Customer = mongoose.model('Customer', schema);
await Customer.updateSearchIndex('test', { mappings: { dynamic: true } });

Model.validate()

Parameters:
  • obj «Object»
  • pathsOrOptions «Object|Array|String»
  • [context] «Object»
Returns:
  • «Promise<Object>» casted and validated copy of obj if validation succeeded

Casts and validates the given object against this model's schema, passing the given context to custom validators.

Example:

const Model = mongoose.model('Test', Schema({
  name: { type: String, required: true },
  age: { type: Number, required: true }
});

try {
  await Model.validate({ name: null }, ['name'])
} catch (err) {
  err instanceof mongoose.Error.ValidationError; // true
  Object.keys(err.errors); // ['name']
}

Model.watch()

Parameters:
  • [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 document

Returns:
  • «ChangeStream» mongoose-specific change stream wrapper, inherits from EventEmitter

Requires 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:

  • 'change': A change occurred, see below example
  • 'error': An unrecoverable error occurred. In particular, change streams currently error out if they lose connection to the replica set primary. Follow this GitHub issue for updates.
  • 'end': Emitted if the underlying stream is closed
  • 'close': Emitted if the underlying stream is closed

Example:

const doc = await Person.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.remove();

Model.where()

Parameters:
  • path «String»
  • [val] «Object» optional value

Returns:
  • «Query»

Creates 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