API Docs

Mongoose

Schema

Connection

Document

Model

Query

QueryCursor

Aggregate

AggregationCursor

Schematype

Virtualtype

Error

SchemaArray

DocumentArrayPath

SubdocumentPath


Mongoose


Mongoose()

Parameters

Mongoose constructor.

The exports object of the mongoose module is an instance of this class. Most apps will only use this one instance.

Example:

  1. const mongoose = require('mongoose');
  2. mongoose instanceof mongoose.Mongoose; // true
  3. // Create a new Mongoose instance with its own `connect()`, `set()`, `model()`, etc.
  4. const m = new mongoose.Mongoose();

Mongoose.prototype.Aggregate()

The Mongoose Aggregate constructor


Mongoose.prototype.CastError()

Parameters
  • type «String» The name of the type

  • value «Any» The value that failed to cast

  • path «String» The path a.b.c in the doc where this cast error occurred

  • [reason] «Error» The original error that was thrown

The Mongoose CastError constructor


Mongoose.prototype.Collection()

The Mongoose Collection constructor


Mongoose.prototype.Connection()

The Mongoose Connection constructor


Mongoose.prototype.Date

Type:
  • «property»

The Mongoose Date SchemaType.

Example:

  1. const schema = new Schema({ test: Date });
  2. schema.path('test') instanceof mongoose.Date; // true

Mongoose.prototype.Decimal128

Type:
  • «property»

The Mongoose Decimal128 SchemaType. Used for declaring paths in your schema that should be 128-bit decimal floating points. Do not use this to create a new Decimal128 instance, use mongoose.Types.Decimal128 instead.

Example:

  1. const vehicleSchema = new Schema({ fuelLevel: mongoose.Decimal128 });

Mongoose.prototype.Document()

The Mongoose Document constructor.


Mongoose.prototype.DocumentProvider()

The Mongoose DocumentProvider constructor. Mongoose users should not have to use this directly


Mongoose.prototype.Error()

The MongooseError constructor.


Mongoose.prototype.Mixed

Type:
  • «property»

The Mongoose Mixed SchemaType. Used for declaring paths in your schema that Mongoose’s change tracking, casting, and validation should ignore.

Example:

  1. const schema = new Schema({ arbitrary: mongoose.Mixed });

Mongoose.prototype.Model()

The Mongoose Model constructor.


Mongoose.prototype.Mongoose()

The Mongoose constructor

The exports of the mongoose module is an instance of this class.

Example:

  1. const mongoose = require('mongoose');
  2. const mongoose2 = new mongoose.Mongoose();

Mongoose.prototype.Number

Type:
  • «property»

The Mongoose Number SchemaType. Used for declaring paths in your schema that Mongoose should cast to numbers.

Example:

  1. const schema = new Schema({ num: mongoose.Number });
  2. // Equivalent to:
  3. const schema = new Schema({ num: 'number' });

Mongoose.prototype.ObjectId

Type:
  • «property»

The Mongoose ObjectId SchemaType. Used for declaring paths in your schema that should be MongoDB ObjectIds. Do not use this to create a new ObjectId instance, use mongoose.Types.ObjectId instead.

Example:

  1. const childSchema = new Schema({ parentId: mongoose.ObjectId });

Mongoose.prototype.Promise

Type:
  • «property»

The Mongoose Promise constructor.


Mongoose.prototype.PromiseProvider()

Storage layer for mongoose promises


Mongoose.prototype.Query()

The Mongoose Query constructor.


Mongoose.prototype.STATES

Type:
  • «property»

Expose connection states for user-land


Mongoose.prototype.Schema()

The Mongoose Schema constructor

Example:

  1. const mongoose = require('mongoose');
  2. const Schema = mongoose.Schema;
  3. const CatSchema = new Schema(..);

Mongoose.prototype.SchemaType()

The Mongoose SchemaType constructor


Mongoose.prototype.SchemaTypeOptions()

The constructor used for schematype options


Mongoose.prototype.SchemaTypes

Type:
  • «property»

The various Mongoose SchemaTypes.

Note:

Alias of mongoose.Schema.Types for backwards compatibility.


Mongoose.prototype.Types

Type:
  • «property»

The various Mongoose Types.

Example:

  1. const mongoose = require('mongoose');
  2. const array = mongoose.Types.Array;

Types:

Using this exposed access to the ObjectId type, we can construct ids on demand.

  1. const ObjectId = mongoose.Types.ObjectId;
  2. const id1 = new ObjectId;

Mongoose.prototype.VirtualType()

The Mongoose VirtualType constructor


Mongoose.prototype.connect()

Parameters
  • uri(s) «String»
  • [options] «Object» passed down to the MongoDB driver’s connect() function, except for 4 mongoose-specific options explained below.

  • [options.bufferCommands=true] «Boolean» Mongoose specific option. Set to false to disable buffering on all models associated with this connection.

  • [options.bufferTimeoutMS=10000] «Number» Mongoose specific option. If bufferCommands is true, Mongoose will throw an error after bufferTimeoutMS if the operation is still buffered.

  • [options.dbName] «String» The name of the database we want to use. If not provided, use database name from connection string.

  • [options.user] «String» username for authentication, equivalent to options.auth.user. Maintained for backwards compatibility.

  • [options.pass] «String» password for authentication, equivalent to options.auth.password. Maintained for backwards compatibility.

  • [options.maxPoolSize=100] «Number» The maximum number of sockets the MongoDB driver will keep open for this connection. Keep in mind that MongoDB only allows one operation per socket at a time, so you may want to increase this if you find you have a few slow queries that are blocking faster queries from proceeding. See Slow Trains in MongoDB and Node.js.

  • [options.minPoolSize=0] «Number» The minimum number of sockets the MongoDB driver will keep open for this connection.

  • [options.serverSelectionTimeoutMS] «Number» If useUnifiedTopology = true, the MongoDB driver will try to find a server to send any given operation to, and keep retrying for serverSelectionTimeoutMS milliseconds before erroring out. If not set, the MongoDB driver defaults to using 30000 (30 seconds).

  • [options.heartbeatFrequencyMS] «Number» If useUnifiedTopology = true, the MongoDB driver sends a heartbeat every heartbeatFrequencyMS to check on the status of the connection. A heartbeat is subject to serverSelectionTimeoutMS, so the MongoDB driver will retry failed heartbeats for up to 30 seconds by default. Mongoose only emits a 'disconnected' event after a heartbeat has failed, so you may want to decrease this setting to reduce the time between when your server goes down and when Mongoose emits 'disconnected'. We recommend you do not set this setting below 1000, too many heartbeats can lead to performance degradation.

  • [options.autoIndex=true] «Boolean» Mongoose-specific option. Set to false to disable automatic index creation for all models associated with this connection.

  • [options.reconnectTries=30] «Number» If you’re connected to a single server or mongos proxy (as opposed to a replica set), the MongoDB driver will try to reconnect every reconnectInterval milliseconds for reconnectTries times, and give up afterward. When the driver gives up, the mongoose connection emits a reconnectFailed event. This option does nothing for replica set connections.

  • [options.reconnectInterval=1000] «Number» See reconnectTries option above.

  • [options.promiseLibrary] «Class» Sets the underlying driver’s promise library.

  • [options.connectTimeoutMS=30000] «Number» How long the MongoDB driver will wait before killing a socket due to inactivity during initial connection. Defaults to 30000. This option is passed transparently to Node.js’ socket#setTimeout() function.

  • [options.socketTimeoutMS=30000] «Number» How long the MongoDB driver will wait before killing a socket due to inactivity after initial connection. A socket may be inactive because of either no activity or a long-running operation. This is set to 30000 by default, you should set this to 2-3x your longest running operation if you expect some of your database operations to run longer than 20 seconds. This option is passed to Node.js socket#setTimeout() function after the MongoDB driver successfully completes.

  • [options.family=0] «Number» Passed transparently to Node.js’ dns.lookup() function. May be either 0, 4, or 6. 4 means use IPv4 only, 6 means use IPv6 only, 0 means try both.

  • [options.autoCreate=false] «Boolean» Set to true to make Mongoose automatically call createCollection() on every model created on this connection.

  • [callback] «Function»

Returns:
  • «Promise» resolves to this if connection succeeded

Opens the default mongoose connection.

Example:

  1. mongoose.connect('mongodb://user:pass@localhost:port/database');
  2. // replica sets
  3. const uri = 'mongodb://user:pass@localhost:port,anotherhost:port,yetanother:port/mydatabase';
  4. mongoose.connect(uri);
  5. // with options
  6. mongoose.connect(uri, options);
  7. // optional callback that gets fired when initial connection completed
  8. const uri = 'mongodb://nonexistent.domain:27000';
  9. mongoose.connect(uri, function(error) {
  10. // if error is truthy, the initial connection failed.
  11. })

Mongoose.prototype.connection

Type:
  • «Connection»

The Mongoose module’s default connection. Equivalent to mongoose.connections[0], see connections.

Example:

  1. const mongoose = require('mongoose');
  2. mongoose.connect(...);
  3. mongoose.connection.on('error', cb);

This is the connection used by default for every model created using mongoose.model.

To create a new connection, use createConnection().


Mongoose.prototype.connections

Type:
  • «Array»

An array containing all connections associated with this Mongoose instance. By default, there is 1 connection. Calling createConnection() adds a connection to this array.

Example:

  1. const mongoose = require('mongoose');
  2. mongoose.connections.length; // 1, just the default connection
  3. mongoose.connections[0] === mongoose.connection; // true
  4. mongoose.createConnection('mongodb://localhost:27017/test');
  5. mongoose.connections.length; // 2

Mongoose.prototype.createConnection()

Parameters
  • [uri] «String» a mongodb:// URI

  • [options] «Object» passed down to the MongoDB driver’s connect() function, except for 4 mongoose-specific options explained below.

  • [options.bufferCommands=true] «Boolean» Mongoose specific option. Set to false to disable buffering on all models associated with this connection.

  • [options.dbName] «String» The name of the database you want to use. If not provided, Mongoose uses the database name from connection string.

  • [options.user] «String» username for authentication, equivalent to options.auth.user. Maintained for backwards compatibility.

  • [options.pass] «String» password for authentication, equivalent to options.auth.password. Maintained for backwards compatibility.

  • [options.autoIndex=true] «Boolean» Mongoose-specific option. Set to false to disable automatic index creation for all models associated with this connection.

  • [options.reconnectTries=30] «Number» If you’re connected to a single server or mongos proxy (as opposed to a replica set), the MongoDB driver will try to reconnect every reconnectInterval milliseconds for reconnectTries times, and give up afterward. When the driver gives up, the mongoose connection emits a reconnectFailed event. This option does nothing for replica set connections.

  • [options.reconnectInterval=1000] «Number» See reconnectTries option above.

  • [options.promiseLibrary] «Class» Sets the underlying driver’s promise library.

  • [options.maxPoolSize=5] «Number» The maximum number of sockets the MongoDB driver will keep open for this connection. Keep in mind that MongoDB only allows one operation per socket at a time, so you may want to increase this if you find you have a few slow queries that are blocking faster queries from proceeding. See Slow Trains in MongoDB and Node.js.

  • [options.minPoolSize=1] «Number» The minimum number of sockets the MongoDB driver will keep open for this connection. Keep in mind that MongoDB only allows one operation per socket at a time, so you may want to increase this if you find you have a few slow queries that are blocking faster queries from proceeding. See Slow Trains in MongoDB and Node.js.

  • [options.connectTimeoutMS=30000] «Number» How long the MongoDB driver will wait before killing a socket due to inactivity during initial connection. Defaults to 30000. This option is passed transparently to Node.js’ socket#setTimeout() function.

  • [options.socketTimeoutMS=30000] «Number» How long the MongoDB driver will wait before killing a socket due to inactivity after initial connection. A socket may be inactive because of either no activity or a long-running operation. This is set to 30000 by default, you should set this to 2-3x your longest running operation if you expect some of your database operations to run longer than 20 seconds. This option is passed to Node.js socket#setTimeout() function after the MongoDB driver successfully completes.

  • [options.family=0] «Number» Passed transparently to Node.js’ dns.lookup() function. May be either 0, 4, or 6. 4 means use IPv4 only, 6 means use IPv6 only, 0 means try both.

Returns:
  • «Connection» the created Connection object. Connections are thenable, so you can do await mongoose.createConnection()

Creates a Connection instance.

Each connection instance maps to a single database. This method is helpful when managing multiple db connections.

Options passed take precedence over options included in connection strings.

Example:

  1. // with mongodb:// URI
  2. db = mongoose.createConnection('mongodb://user:pass@localhost:port/database');
  3. // and options
  4. const opts = { db: { native_parser: true }}
  5. db = mongoose.createConnection('mongodb://user:pass@localhost:port/database', opts);
  6. // replica sets
  7. db = mongoose.createConnection('mongodb://user:pass@localhost:port,anotherhost:port,yetanother:port/database');
  8. // and options
  9. const opts = { replset: { strategy: 'ping', rs_name: 'testSet' }}
  10. db = mongoose.createConnection('mongodb://user:pass@localhost:port,anotherhost:port,yetanother:port/database', opts);
  11. // and options
  12. const opts = { server: { auto_reconnect: false }, user: 'username', pass: 'mypassword' }
  13. db = mongoose.createConnection('localhost', 'database', port, opts)
  14. // initialize now, connect later
  15. db = mongoose.createConnection();
  16. db.openUri('localhost', 'database', port, [opts]);

Mongoose.prototype.deleteModel()

Parameters
  • name «String|RegExp» if string, the name of the model to remove. If regexp, removes all models whose name matches the regexp.
Returns:
  • «Mongoose» this

Removes the model named name from the default connection, if it exists. You can use this function to clean up any models you created in your tests to prevent OverwriteModelErrors.

Equivalent to mongoose.connection.deleteModel(name).

Example:

  1. mongoose.model('User', new Schema({ name: String }));
  2. console.log(mongoose.model('User')); // Model object
  3. mongoose.deleteModel('User');
  4. console.log(mongoose.model('User')); // undefined
  5. // Usually useful in a Mocha `afterEach()` hook
  6. afterEach(function() {
  7. mongoose.deleteModel(/.+/); // Delete every model
  8. });

Mongoose.prototype.disconnect()

Parameters
  • [callback] «Function» called after all connection close, or when first error occurred.
Returns:
  • «Promise» resolves when all connections are closed, or rejects with the first error that occurred.

Runs .close() on all connections in parallel.


Mongoose.prototype.driver

Type:
  • «property»

Object with get() and set() containing the underlying driver this Mongoose instance uses to communicate with the database. A driver is a Mongoose-specific interface that defines functions like find().


Mongoose.prototype.get()

Parameters
  • key «String»

Gets mongoose options

Example:

  1. mongoose.get('test') // returns the 'test' value

Mongoose.prototype.isValidObjectId()

Returns true if Mongoose can cast the given value to an ObjectId, or false otherwise.

Example:

  1. mongoose.isValidObjectId(new mongoose.Types.ObjectId()); // true
  2. mongoose.isValidObjectId('0123456789ab'); // true
  3. mongoose.isValidObjectId(6); // false

Mongoose.prototype.model()

Parameters
  • name «String|Function» model name or class extending Model

  • [schema] «Schema» the schema to use.

  • [collection] «String» name (optional, inferred from model name)

Returns:
  • «Model» The model associated with name. Mongoose will create the model if it doesn’t already exist.

Defines a model or retrieves it.

Models defined on the mongoose instance are available to all connection created by the same mongoose instance.

If you call mongoose.model() with twice the same name but a different schema, you will get an OverwriteModelError. If you call mongoose.model() with the same name and same schema, you’ll get the same schema back.

Example:

  1. const mongoose = require('mongoose');
  2. // define an Actor model with this mongoose instance
  3. const schema = new Schema({ name: String });
  4. mongoose.model('Actor', schema);
  5. // create a new connection
  6. const conn = mongoose.createConnection(..);
  7. // create Actor model
  8. const Actor = conn.model('Actor', schema);
  9. conn.model('Actor') === Actor; // true
  10. conn.model('Actor', schema) === Actor; // true, same schema
  11. conn.model('Actor', schema, 'actors') === Actor; // true, same schema and collection name
  12. // This throws an `OverwriteModelError` because the schema is different.
  13. conn.model('Actor', new Schema({ name: String }));

When no collection argument is passed, Mongoose uses the model name. If you don’t like this behavior, either pass a collection name, use mongoose.pluralize(), or set your schemas collection name option.

Example:

  1. const schema = new Schema({ name: String }, { collection: 'actor' });
  2. // or
  3. schema.set('collection', 'actor');
  4. // or
  5. const collectionName = 'actor'
  6. const M = mongoose.model('Actor', schema, collectionName)

Mongoose.prototype.modelNames()

Returns:
  • «Array»

Returns an array of model names created on this instance of Mongoose.

Note:

Does not include names of models created using connection.model().


Mongoose.prototype.mongo

Type:
  • «property»

The node-mongodb-native driver Mongoose uses.


Mongoose.prototype.mquery

Type:
  • «property»

The mquery query builder Mongoose uses.


Mongoose.prototype.now()

Mongoose uses this function to get the current time when setting timestamps. You may stub out this function using a tool like Sinon for testing.


Mongoose.prototype.plugin()

Parameters
  • fn «Function» plugin callback

  • [opts] «Object» optional options

Returns:
  • «Mongoose» this

Declares a global plugin executed on all Schemas.

Equivalent to calling .plugin(fn) on each Schema you create.


Mongoose.prototype.pluralize()

Parameters
  • [fn] «Function|null» overwrites the function used to pluralize collection names
Returns:
  • «Function,null» the current function used to pluralize collection names, defaults to the legacy function from mongoose-legacy-pluralize.

Getter/setter around function for pluralizing collection names.


Mongoose.prototype.sanitizeFilter()

Parameters
  • filter «Object»

Sanitizes query filters against query selector injection attacks by wrapping any nested objects that have a property whose name starts with $ in a $eq.

  1. const obj = { username: 'val', pwd: { $ne: null } };
  2. sanitizeFilter(obj);
  3. obj; // { username: 'val', pwd: { $eq: { $ne: null } } });

Mongoose.prototype.set()

Parameters
  • key «String»
  • value «String|Function|Boolean»

Sets mongoose options

Example:

  1. mongoose.set('test', value) // sets the 'test' option to `value`
  2. mongoose.set('debug', true) // enable logging collection methods + arguments to the console/file
  3. mongoose.set('debug', function(collectionName, methodName, ...methodArgs) {}); // use custom function to log collection methods + arguments

Currently supported options are

  • ‘debug’: If true, prints the operations mongoose sends to MongoDB to the console. If a writable stream is passed, it will log to that stream, without colorization. If a callback function is passed, it will receive the collection name, the method name, then all arugments passed to the method. For example, if you wanted to replicate the default logging, you could output from the callback Mongoose: ${collectionName}.${methodName}(${methodArgs.join(', ')}).
  • ‘returnOriginal’: If false, changes the default returnOriginal option to findOneAndUpdate(), findByIdAndUpdate, and findOneAndReplace() to false. This is equivalent to setting the new option to true for findOneAndX() calls by default. Read our findOneAndUpdate() tutorial for more information.
  • ‘bufferCommands’: enable/disable mongoose’s buffering mechanism for all connections and models
  • ‘cloneSchemas’: false by default. Set to true to clone() all schemas before compiling into a model.
  • ‘applyPluginsToDiscriminators’: false by default. Set to true to apply global plugins to discriminator schemas. This typically isn’t necessary because plugins are applied to the base schema and discriminators copy all middleware, methods, statics, and properties from the base schema.
  • ‘applyPluginsToChildSchemas’: true by default. Set to false to skip applying global plugins to child schemas
  • ‘objectIdGetter’: true by default. Mongoose adds a getter to MongoDB ObjectId’s called _id that returns this for convenience with populate. Set this to false to remove the getter.
  • ‘runValidators’: false by default. Set to true to enable update validators for all validators by default.
  • ‘toObject’: { transform: true, flattenDecimals: true } by default. Overwrites default objects to toObject()
  • ‘toJSON’: { transform: true, flattenDecimals: true } by default. Overwrites default objects to toJSON(), for determining how Mongoose documents get serialized by JSON.stringify()
  • ‘strict’: true by default, may be false, true, or 'throw'. Sets the default strict mode for schemas.
  • ‘strictQuery’: false by default, may be false, true, or 'throw'. Sets the default strictQuery mode for schemas.
  • ‘selectPopulatedPaths’: true by default. Set to false to opt out of Mongoose adding all fields that you populate() to your select(). The schema-level option selectPopulatedPaths overwrites this one.
  • ‘maxTimeMS’: If set, attaches maxTimeMS to every query
  • ‘autoIndex’: true by default. Set to false to disable automatic index creation for all models associated with this Mongoose instance.
  • ‘autoCreate’: Set to true to make Mongoose call Model.createCollection() automatically when you create a model with mongoose.model() or conn.model(). This is useful for testing transactions, change streams, and other features that require the collection to exist.
  • ‘overwriteModels’: Set to true to default to overwriting models with the same name when calling mongoose.model(), as opposed to throwing an OverwriteModelError.

Mongoose.prototype.startSession()

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

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

  • [callback] «Function»

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 mongoose.startSession() is equivalent to calling mongoose.connection.startSession(). Sessions are scoped to a connection, so calling mongoose.startSession() starts a session on the default mongoose connection.


Mongoose.prototype.trusted()

Parameters
  • obj «Object»

Tells sanitizeFilter() to skip the given object when filtering out potential query selector injection attacks. Use this method when you have a known query selector that you want to use.

  1. const obj = { username: 'val', pwd: trusted({ $type: 'string', $eq: 'my secret' }) };
  2. sanitizeFilter(obj);
  3. // Note that `sanitizeFilter()` did not add `$eq` around `$type`.
  4. obj; // { username: 'val', pwd: { $type: 'string', $eq: 'my secret' } });

Mongoose.prototype.version

Type:
  • «property»

The Mongoose version

Example

  1. console.log(mongoose.version); // '5.x.x'

Schema


Schema()

Parameters
  • [definition] «Object|Schema|Array» Can be one of: object describing schema paths, or schema to copy, or array of objects and schemas

  • [options] «Object»

Schema constructor.

Example:

  1. const child = new Schema({ name: String });
  2. const schema = new Schema({ name: String, age: Number, children: [child] });
  3. const Tree = mongoose.model('Tree', schema);
  4. // setting schema options
  5. new Schema({ name: String }, { _id: false, autoIndex: false })

Options:

Options for Nested Schemas:

  • excludeIndexes: bool - defaults to false. If true, skip building indexes on this schema’s paths.

Note:

When nesting schemas, (children in the example above), always declare the child schema first before passing it into its parent.


Schema.Types

Type:
  • «property»

The various built-in Mongoose Schema Types.

Example:

  1. const mongoose = require('mongoose');
  2. const ObjectId = mongoose.Schema.Types.ObjectId;

Types:

Using this exposed access to the Mixed SchemaType, we can use them in our schema.

  1. const Mixed = mongoose.Schema.Types.Mixed;
  2. new mongoose.Schema({ _user: Mixed })

Schema.indexTypes

Type:
  • «property»

The allowed index types


Schema.prototype.add()

Parameters
  • obj «Object|Schema» plain object with paths to add, or another schema

  • [prefix] «String» path to prefix the newly added paths with

Returns:
  • «Schema» the Schema instance

Adds key path / schema type pairs to this schema.

Example:

  1. const ToySchema = new Schema();
  2. ToySchema.add({ name: 'string', color: 'string', price: 'number' });
  3. const TurboManSchema = new Schema();
  4. // You can also `add()` another schema and copy over all paths, virtuals,
  5. // getters, setters, indexes, methods, and statics.
  6. TurboManSchema.add(ToySchema).add({ year: Number });

Schema.prototype.childSchemas

Type:
  • «property»

Array of child schemas (from document arrays and single nested subdocs) and their corresponding compiled models. Each element of the array is an object with 2 properties: schema and model.

This property is typically only useful for plugin authors and advanced users. You do not need to interact with this property at all to use mongoose.


Schema.prototype.clone()

Returns:
  • «Schema» the cloned schema

Returns a deep copy of the schema

Example:

  1. const schema = new Schema({ name: String });
  2. const clone = schema.clone();
  3. clone === schema; // false
  4. clone.path('name'); // SchemaString { ... }

Schema.prototype.eachPath()

Parameters
  • fn «Function» callback function
Returns:
  • «Schema» this

Iterates the schemas paths similar to Array#forEach.

The callback is passed the pathname and the schemaType instance.

Example:

  1. const userSchema = new Schema({ name: String, registeredAt: Date });
  2. userSchema.eachPath((pathname, schematype) => {
  3. // Prints twice:
  4. // name SchemaString { ... }
  5. // registeredAt SchemaDate { ... }
  6. console.log(pathname, schematype);
  7. });

Schema.prototype.get()

Parameters
  • key «String» option name
Returns:
  • «Any» the option’s value

Gets a schema option.

Example:

  1. schema.get('strict'); // true
  2. schema.set('strict', false);
  3. schema.get('strict'); // false

Schema.prototype.index()

Parameters
  • fields «Object»
  • [options] «Object» Options to pass to MongoDB driver’s createIndex() function

  • | «String» number} [options.expires=null] Mongoose-specific syntactic sugar, uses ms to convert expires option into seconds for the expireAfterSeconds in the above link.

Defines an index (most likely compound) for this schema.

Example

  1. schema.index({ first: 1, last: -1 })

Schema.prototype.indexes()

Returns:
  • «Array» list of indexes defined in the schema

Returns a list of indexes that this schema declares, via schema.index() or by index: true in a path’s options. Indexes are expressed as an array [spec, options].

Example:

  1. const userSchema = new Schema({
  2. email: { type: String, required: true, unique: true },
  3. registeredAt: { type: Date, index: true }
  4. });
  5. // [ [ { email: 1 }, { unique: true, background: true } ],
  6. // [ { registeredAt: 1 }, { background: true } ] ]
  7. userSchema.indexes();

Plugins can use the return value of this function to modify a schema’s indexes. For example, the below plugin makes every index unique by default.

  1. function myPlugin(schema) {
  2. for (const index of schema.indexes()) {
  3. if (index[1].unique === undefined) {
  4. index[1].unique = true;
  5. }
  6. }
  7. }

Schema.prototype.loadClass()

Parameters
  • model «Function»
  • [virtualsOnly] «Boolean» if truthy, only pulls virtuals from the class, not methods or statics

Loads an ES6 class into a schema. Maps setters + getters, static methods, and instance methods to schema virtuals, statics, and methods.

Example:

  1. const md5 = require('md5');
  2. const userSchema = new Schema({ email: String });
  3. class UserClass {
  4. // `gravatarImage` becomes a virtual
  5. get gravatarImage() {
  6. const hash = md5(this.email.toLowerCase());
  7. return `https://www.gravatar.com/avatar/${hash}`;
  8. }
  9. // `getProfileUrl()` becomes a document method
  10. getProfileUrl() {
  11. return `https://mysite.com/${this.email}`;
  12. }
  13. // `findByEmail()` becomes a static
  14. static findByEmail(email) {
  15. return this.findOne({ email });
  16. }
  17. }
  18. // `schema` will now have a `gravatarImage` virtual, a `getProfileUrl()` method,
  19. // and a `findByEmail()` static
  20. userSchema.loadClass(UserClass);

Schema.prototype.method()

Parameters
  • method «String|Object» name

  • [fn] «Function»

Adds an instance method to documents constructed from Models compiled from this schema.

Example

  1. const schema = kittySchema = new Schema(..);
  2. schema.method('meow', function () {
  3. console.log('meeeeeoooooooooooow');
  4. })
  5. const Kitty = mongoose.model('Kitty', schema);
  6. const fizz = new Kitty;
  7. fizz.meow(); // meeeeeooooooooooooow

If a hash of name/fn pairs is passed as the only argument, each name/fn pair will be added as methods.

  1. schema.method({
  2. purr: function () {}
  3. , scratch: function () {}
  4. });
  5. // later
  6. fizz.purr();
  7. fizz.scratch();

NOTE: Schema.method() adds instance methods to the Schema.methods object. You can also add instance methods directly to the Schema.methods object as seen in the guide


Schema.prototype.obj

Type:
  • «property»

The original object passed to the schema constructor

Example:

  1. const schema = new Schema({ a: String }).add({ b: String });
  2. schema.obj; // { a: String }

Schema.prototype.path()

Parameters
  • path «String»
  • constructor «Object»

Gets/sets schema paths.

Sets a path (if arity 2) Gets a path (if arity 1)

Example

  1. schema.path('name') // returns a SchemaType
  2. schema.path('name', Number) // changes the schemaType of `name` to Number

Schema.prototype.pathType()

Parameters
  • path «String»
Returns:
  • «String»

Returns the pathType of path for this schema.

Given a path, returns whether it is a real, virtual, nested, or ad-hoc/undefined path.

Example:

  1. const s = new Schema({ name: String, nested: { foo: String } });
  2. s.virtual('foo').get(() => 42);
  3. s.pathType('name'); // "real"
  4. s.pathType('nested'); // "nested"
  5. s.pathType('foo'); // "virtual"
  6. s.pathType('fail'); // "adhocOrUndefined"

Schema.prototype.paths

Type:
  • «property»

The paths defined on this schema. The keys are the top-level paths in this schema, and the values are instances of the SchemaType class.

Example:

  1. const schema = new Schema({ name: String }, { _id: false });
  2. schema.paths; // { name: SchemaString { ... } }
  3. schema.add({ age: Number });
  4. schema.paths; // { name: SchemaString { ... }, age: SchemaNumber { ... } }

Schema.prototype.pick()

Parameters
  • paths «Array» list of paths to pick

  • [options] «Object» options to pass to the schema constructor. Defaults to this.options if not set.

Returns:
  • «Schema»

Returns a new schema that has the picked paths from this schema.

This method is analagous to Lodash’s pick() function for Mongoose schemas.

Example:

  1. const schema = Schema({ name: String, age: Number });
  2. // Creates a new schema with the same `name` path as `schema`,
  3. // but no `age` path.
  4. const newSchema = schema.pick(['name']);
  5. newSchema.path('name'); // SchemaString { ... }
  6. newSchema.path('age'); // undefined

Schema.prototype.plugin()

Parameters
  • plugin «Function» callback

  • [opts] «Object»

Registers a plugin for this schema.

Example:

  1. const s = new Schema({ name: String });
  2. s.plugin(schema => console.log(schema.path('name').path));
  3. mongoose.model('Test', s); // Prints 'name'

Schema.prototype.post()

Parameters
  • The «String|RegExp» method name or regular expression to match method name

  • [options] «Object»

  • [options.document] «Boolean» If name is a hook for both document and query middleware, set to true to run on document middleware.

  • [options.query] «Boolean» If name is a hook for both document and query middleware, set to true to run on query middleware.

  • fn «Function» callback

Defines a post hook for the document

  1. const schema = new Schema(..);
  2. schema.post('save', function (doc) {
  3. console.log('this fired after a document was saved');
  4. });
  5. schema.post('find', function(docs) {
  6. console.log('this fired after you ran a find query');
  7. });
  8. schema.post(/Many$/, function(res) {
  9. console.log('this fired after you ran `updateMany()` or `deleteMany()`);
  10. });
  11. const Model = mongoose.model('Model', schema);
  12. const m = new Model(..);
  13. m.save(function(err) {
  14. console.log('this fires after the `post` hook');
  15. });
  16. m.find(function(err, docs) {
  17. console.log('this fires after the post find hook');
  18. });

Schema.prototype.pre()

Parameters
  • The «String|RegExp» method name or regular expression to match method name

  • [options] «Object»

  • [options.document] «Boolean» If name is a hook for both document and query middleware, set to true to run on document middleware. For example, set options.document to true to apply this hook to Document#deleteOne() rather than Query#deleteOne().

  • [options.query] «Boolean» If name is a hook for both document and query middleware, set to true to run on query middleware.

  • callback «Function»

Defines a pre hook for the model.

Example

  1. const toySchema = new Schema({ name: String, created: Date });
  2. toySchema.pre('save', function(next) {
  3. if (!this.created) this.created = new Date;
  4. next();
  5. });
  6. toySchema.pre('validate', function(next) {
  7. if (this.name !== 'Woody') this.name = 'Woody';
  8. next();
  9. });
  10. // Equivalent to calling `pre()` on `find`, `findOne`, `findOneAndUpdate`.
  11. toySchema.pre(/^find/, function(next) {
  12. console.log(this.getFilter());
  13. });
  14. // Equivalent to calling `pre()` on `updateOne`, `findOneAndUpdate`.
  15. toySchema.pre(['updateOne', 'findOneAndUpdate'], function(next) {
  16. console.log(this.getFilter());
  17. });
  18. toySchema.pre('deleteOne', function() {
  19. // Runs when you call `Toy.deleteOne()`
  20. });
  21. toySchema.pre('deleteOne', { document: true }, function() {
  22. // Runs when you call `doc.deleteOne()`
  23. });

Schema.prototype.queue()

Parameters
  • name «String» name of the document method to call later

  • args «Array» arguments to pass to the method

Adds a method call to the queue.

Example:

  1. schema.methods.print = function() { console.log(this); };
  2. schema.queue('print', []); // Print the doc every one is instantiated
  3. const Model = mongoose.model('Test', schema);
  4. new Model({ name: 'test' }); // Prints '{"_id": ..., "name": "test" }'

Schema.prototype.remove()

Parameters
  • path «String|Array»
Returns:
  • «Schema» the Schema instance

Removes the given path (or [paths]).

Example:

  1. const schema = new Schema({ name: String, age: Number });
  2. schema.remove('name');
  3. schema.path('name'); // Undefined
  4. schema.path('age'); // SchemaNumber { ... }

Schema.prototype.requiredPaths()

Parameters
  • invalidate «Boolean» refresh the cache
Returns:
  • «Array»

Returns an Array of path strings that are required by this schema.

Example:

  1. const s = new Schema({
  2. name: { type: String, required: true },
  3. age: { type: String, required: true },
  4. notes: String
  5. });
  6. s.requiredPaths(); // [ 'age', 'name' ]

Schema.prototype.set()

Parameters
  • key «String» option name

  • [value] «Object» if not passed, the current option value is returned

Sets a schema option.

Example

  1. schema.set('strict'); // 'true' by default
  2. schema.set('strict', false); // Sets 'strict' to false
  3. schema.set('strict'); // 'false'

Schema.prototype.static()

Parameters
  • name «String|Object»
  • [fn] «Function»

Adds static “class” methods to Models compiled from this schema.

Example

  1. const schema = new Schema(..);
  2. // Equivalent to `schema.statics.findByName = function(name) {}`;
  3. schema.static('findByName', function(name) {
  4. return this.find({ name: name });
  5. });
  6. const Drink = mongoose.model('Drink', schema);
  7. await Drink.findByName('LaCroix');

If a hash of name/fn pairs is passed as the only argument, each name/fn pair will be added as statics.


Schema.prototype.virtual()

Parameters
  • name «String»
  • [options] «Object»

  • [options.ref] «String|Model» model name or model instance. Marks this as a populate virtual.

  • [options.localField] «String|Function» Required for populate virtuals. See populate virtual docs for more information.

  • [options.foreignField] «String|Function» Required for populate virtuals. See populate virtual docs for more information.

  • [options.justOne=false] «Boolean|Function» Only works with populate virtuals. If truthy, will be a single doc or null. Otherwise, the populate virtual will be an array.

  • [options.count=false] «Boolean» Only works with populate virtuals. If truthy, this populate virtual will contain the number of documents rather than the documents themselves when you populate().

  • [options.get=null] «Function|null» Adds a getter to this virtual to transform the populated doc.

Returns:
  • «VirtualType»

Creates a virtual type with the given name.


Schema.prototype.virtualpath()

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

Returns the virtual type with the given name.


Schema.prototype.virtuals

Type:
  • «property»

Object containing all virtuals defined on this schema. The objects’ keys are the virtual paths and values are instances of VirtualType.

This property is typically only useful for plugin authors and advanced users. You do not need to interact with this property at all to use mongoose.

Example:

  1. const schema = new Schema({});
  2. schema.virtual('answer').get(() => 42);
  3. console.log(schema.virtuals); // { answer: VirtualType { path: 'answer', ... } }
  4. console.log(schema.virtuals['answer'].getters[0].call()); // 42

Schema.reserved

Type:
  • «property»

Reserved document keys.

Keys in this object are names that are warned in schema declarations because they have the potential to break Mongoose/ Mongoose plugins functionality. If you create a schema using new Schema() with one of these property names, Mongoose will log a warning.

  • _posts
  • _pres
  • collection
  • emit
  • errors
  • get
  • init
  • isModified
  • isNew
  • listeners
  • modelName
  • on
  • once
  • populated
  • prototype
  • remove
  • removeListener
  • save
  • schema
  • toObject
  • validate

NOTE: Use of these terms as method names is permitted, but play at your own risk, as they may be existing mongoose document methods you are stomping on.

  1. const schema = new Schema(..);
  2. schema.methods.init = function () {} // potentially breaking

Connection


Connection()

Parameters
  • base «Mongoose» a mongoose instance

Connection constructor

For practical reasons, a Connection equals a Db.


Connection.prototype.asPromise()

Returns:
  • «Promise»

Returns a promise that resolves when this connection successfully connects to MongoDB, or rejects if this connection failed to connect.

Example:

  1. const conn = await mongoose.createConnection('mongodb://localhost:27017/test').
  2. asPromise();
  3. conn.readyState; // 1, means Mongoose is connected

Connection.prototype.client

Type:
  • «property»

The MongoClient instance this connection uses to talk to MongoDB. Mongoose automatically sets this property when the connection is opened.


Connection.prototype.close()

Parameters
  • [force] «Boolean» optional

  • [callback] «Function» optional

Returns:
  • «Promise»

Closes the connection


Connection.prototype.collection()

Parameters
  • name «String» of the collection

  • [options] «Object» optional collection options

Returns:
  • «Collection» collection instance

Retrieves a collection, creating it if not cached.

Not typically needed by applications. Just talk to your collection through your model.


Connection.prototype.collections

Type:
  • «property»

A hash of the collections associated with this connection


Connection.prototype.config

Type:
  • «property»

A hash of the global options that are associated with this connection


Connection.prototype.createCollection()

Parameters
  • collection «string» The collection to create

  • [options] «Object» see MongoDB driver docs

  • [callback] «Function»

Returns:
  • «Promise»

Helper for createCollection(). Will explicitly create the given collection with specified options. Used to create capped collections and views from mongoose.

Options are passed down without modification to the MongoDB driver’s createCollection() function


Connection.prototype.db

Type:
  • «property»

The mongodb.Db instance, set when the connection is opened


Connection.prototype.deleteModel()

Parameters
  • name «String|RegExp» if string, the name of the model to remove. If regexp, removes all models whose name matches the regexp.
Returns:
  • «Connection» this

Removes the model named name from this connection, if it exists. You can use this function to clean up any models you created in your tests to prevent OverwriteModelErrors.

Example:

  1. conn.model('User', new Schema({ name: String }));
  2. console.log(conn.model('User')); // Model object
  3. conn.deleteModel('User');
  4. console.log(conn.model('User')); // undefined
  5. // Usually useful in a Mocha `afterEach()` hook
  6. afterEach(function() {
  7. conn.deleteModel(/.+/); // Delete every model
  8. });

Connection.prototype.dropCollection()

Parameters
  • collection «string» The collection to delete

  • [callback] «Function»

Returns:
  • «Promise»

Helper for dropCollection(). Will delete the given collection, including all documents and indexes.


Connection.prototype.dropDatabase()

Parameters
  • [callback] «Function»
Returns:
  • «Promise»

Helper for dropDatabase(). Deletes the given database, including all collections, documents, and indexes.

Example:

  1. const conn = mongoose.createConnection('mongodb://localhost:27017/mydb');
  2. // Deletes the entire 'mydb' database
  3. await conn.dropDatabase();

Connection.prototype.get()

Parameters
  • key «String»

Gets the value of the option key. Equivalent to conn.options[key]

Example:

  1. conn.get('test'); // returns the 'test' value

Connection.prototype.getClient()

Returns:
  • «MongoClient»

Returns the MongoDB driver MongoClient instance that this connection uses to talk to MongoDB.

Example:

  1. const conn = await mongoose.createConnection('mongodb://localhost:27017/test');
  2. conn.getClient(); // MongoClient { ... }

Connection.prototype.host

Type:
  • «property»

The host name portion of the URI. If multiple hosts, such as a replica set, this will contain the first host name in the URI

Example

  1. mongoose.createConnection('mongodb://localhost:27017/mydb').host; // "localhost"

Connection.prototype.id

Type:
  • «property»

A number identifier for this connection. Used for debugging when you have multiple connections.

Example

  1. // The default connection has `id = 0`
  2. mongoose.connection.id; // 0
  3. // If you create a new connection, Mongoose increments id
  4. const conn = mongoose.createConnection();
  5. conn.id; // 1

Connection.prototype.model()

Parameters
  • name «String|Function» the model name or class extending Model

  • [schema] «Schema» a schema. necessary when defining a model

  • [collection] «String» name of mongodb collection (optional) if not given it will be induced from model name

  • [options] «Object»

  • [options.overwriteModels=false] «Boolean» If true, overwrite existing models with the same name to avoid OverwriteModelError

Returns:
  • «Model» The compiled model

Defines or retrieves a model.

  1. const mongoose = require('mongoose');
  2. const db = mongoose.createConnection(..);
  3. db.model('Venue', new Schema(..));
  4. const Ticket = db.model('Ticket', new Schema(..));
  5. const Venue = db.model('Venue');

When no collection argument is passed, Mongoose produces a collection name by passing the model name to the utils.toCollectionName method. This method pluralizes the name. If you don’t like this behavior, either pass a collection name or set your schemas collection name option.

Example:

  1. const schema = new Schema({ name: String }, { collection: 'actor' });
  2. // or
  3. schema.set('collection', 'actor');
  4. // or
  5. const collectionName = 'actor'
  6. const M = conn.model('Actor', schema, collectionName)

Connection.prototype.modelNames()

Returns:
  • «Array»

Returns an array of model names created on this connection.


Connection.prototype.models

Type:
  • «property»

A POJO containing a map from model names to models. Contains all models that have been added to this connection using Connection#model().

Example

  1. const conn = mongoose.createConnection();
  2. const Test = conn.model('Test', mongoose.Schema({ name: String }));
  3. Object.keys(conn.models).length; // 1
  4. conn.models.Test === Test; // true

Connection.prototype.name

Type:
  • «property»

The name of the database this connection points to.

Example

  1. mongoose.createConnection('mongodb://localhost:27017/mydb').name; // "mydb"

Connection.prototype.openUri()

Parameters
  • uri «String» The URI to connect with.

  • [options] «Object» Passed on to http://mongodb.github.io/node-mongodb-native/2.2/api/MongoClient.html#connect

  • [options.bufferCommands=true] «Boolean» Mongoose specific option. Set to false to disable buffering on all models associated with this connection.

  • [options.bufferTimeoutMS=10000] «Number» Mongoose specific option. If bufferCommands is true, Mongoose will throw an error after bufferTimeoutMS if the operation is still buffered.

  • [options.dbName] «String» The name of the database we want to use. If not provided, use database name from connection string.

  • [options.user] «String» username for authentication, equivalent to options.auth.user. Maintained for backwards compatibility.

  • [options.pass] «String» password for authentication, equivalent to options.auth.password. Maintained for backwards compatibility.

  • [options.maxPoolSize=100] «Number» The maximum number of sockets the MongoDB driver will keep open for this connection. Keep in mind that MongoDB only allows one operation per socket at a time, so you may want to increase this if you find you have a few slow queries that are blocking faster queries from proceeding. See Slow Trains in MongoDB and Node.js.

  • [options.minPoolSize=0] «Number» The minimum number of sockets the MongoDB driver will keep open for this connection. Keep in mind that MongoDB only allows one operation per socket at a time, so you may want to increase this if you find you have a few slow queries that are blocking faster queries from proceeding. See Slow Trains in MongoDB and Node.js.

  • [options.serverSelectionTimeoutMS] «Number» If useUnifiedTopology = true, the MongoDB driver will try to find a server to send any given operation to, and keep retrying for serverSelectionTimeoutMS milliseconds before erroring out. If not set, the MongoDB driver defaults to using 30000 (30 seconds).

  • [options.heartbeatFrequencyMS] «Number» If useUnifiedTopology = true, the MongoDB driver sends a heartbeat every heartbeatFrequencyMS to check on the status of the connection. A heartbeat is subject to serverSelectionTimeoutMS, so the MongoDB driver will retry failed heartbeats for up to 30 seconds by default. Mongoose only emits a 'disconnected' event after a heartbeat has failed, so you may want to decrease this setting to reduce the time between when your server goes down and when Mongoose emits 'disconnected'. We recommend you do not set this setting below 1000, too many heartbeats can lead to performance degradation.

  • [options.autoIndex=true] «Boolean» Mongoose-specific option. Set to false to disable automatic index creation for all models associated with this connection.

  • [options.promiseLibrary] «Class» Sets the underlying driver’s promise library.

  • [options.connectTimeoutMS=30000] «Number» How long the MongoDB driver will wait before killing a socket due to inactivity during initial connection. Defaults to 30000. This option is passed transparently to Node.js’ socket#setTimeout() function.

  • [options.socketTimeoutMS=30000] «Number» How long the MongoDB driver will wait before killing a socket due to inactivity after initial connection. A socket may be inactive because of either no activity or a long-running operation. This is set to 30000 by default, you should set this to 2-3x your longest running operation if you expect some of your database operations to run longer than 20 seconds. This option is passed to Node.js socket#setTimeout() function after the MongoDB driver successfully completes.

  • [options.family=0] «Number» Passed transparently to Node.js’ dns.lookup() function. May be either 0, 4, or 6. 4means use IPv4 only,6means use IPv6 only,0` means try both.

  • [options.autoCreate=false] «Boolean» Set to true to make Mongoose automatically call createCollection() on every model created on this connection.

  • [callback] «Function»

Opens the connection with a URI using MongoClient.connect().


Connection.prototype.pass

Type:
  • «property»

The password specified in the URI

Example

  1. mongoose.createConnection('mongodb://val:psw@localhost:27017/mydb').pass; // "psw"

Connection.prototype.plugin()

Parameters
  • fn «Function» plugin callback

  • [opts] «Object» optional options

Returns:
  • «Connection» this

Declares a plugin executed on all schemas you pass to conn.model()

Equivalent to calling .plugin(fn) on each schema you create.

Example:

  1. const db = mongoose.createConnection('mongodb://localhost:27017/mydb');
  2. db.plugin(() => console.log('Applied'));
  3. db.plugins.length; // 1
  4. db.model('Test', new Schema({})); // Prints "Applied"

Connection.prototype.plugins

Type:
  • «property»

The plugins that will be applied to all models created on this connection.

Example:

  1. const db = mongoose.createConnection('mongodb://localhost:27017/mydb');
  2. db.plugin(() => console.log('Applied'));
  3. db.plugins.length; // 1
  4. db.model('Test', new Schema({})); // Prints "Applied"

Connection.prototype.port

Type:
  • «property»

The port portion of the URI. If multiple hosts, such as a replica set, this will contain the port from the first host name in the URI.

Example

  1. mongoose.createConnection('mongodb://localhost:27017/mydb').port; // 27017

Connection.prototype.readyState

Type:
  • «property»

Connection ready state

  • 0 = disconnected
  • 1 = connected
  • 2 = connecting
  • 3 = disconnecting

Each state change emits its associated event name.

Example

  1. conn.on('connected', callback);
  2. conn.on('disconnected', callback);

Connection.prototype.set()

Parameters
  • key «String»
  • val «Any»

Sets the value of the option key. Equivalent to conn.options[key] = val

Supported options include

  • maxTimeMS: Set maxTimeMS for all queries on this connection.

Example:

  1. conn.set('test', 'foo');
  2. conn.get('test'); // 'foo'
  3. conn.options.test; // 'foo'

Connection.prototype.setClient()

Returns:
  • «Connection» this

Set the MongoDB driver MongoClient instance that this connection uses to talk to MongoDB. This is useful if you already have a MongoClient instance, and want to reuse it.

Example:

  1. const client = await mongodb.MongoClient.connect('mongodb://localhost:27017/test');
  2. const conn = mongoose.createConnection().setClient(client);
  3. conn.getClient(); // MongoClient { ... }
  4. conn.readyState; // 1, means 'CONNECTED'

Connection.prototype.startSession()

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

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

  • [callback] «Function»

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.

Example:

  1. const session = await conn.startSession();
  2. let doc = await Person.findOne({ name: 'Ned Stark' }, null, { session });
  3. await doc.remove();
  4. // `doc` will always be null, even if reading from a replica set
  5. // secondary. Without causal consistency, it is possible to
  6. // get a doc back from the below query if the query reads from a
  7. // secondary that is experiencing replication lag.
  8. doc = await Person.findOne({ name: 'Ned Stark' }, null, { session, readPreference: 'secondary' });

Connection.prototype.transaction()

Parameters
  • fn «Function» Function to execute in a transaction

  • [options] «mongodb.TransactionOptions» Optional settings for the transaction

Returns:
  • «Promise<Any>» promise that is fulfilled if Mongoose successfully committed the transaction, or rejects if the transaction was aborted or if Mongoose failed to commit the transaction. If fulfilled, the promise resolves to a MongoDB command result.

Requires MongoDB >= 3.6.0. Executes the wrapped async function in a transaction. Mongoose will commit the transaction if the async function executes successfully and attempt to retry if there was a retriable error.

Calls the MongoDB driver’s session.withTransaction(), but also handles resetting Mongoose document state as shown below.

Example:

  1. const doc = new Person({ name: 'Will Riker' });
  2. await db.transaction(async function setRank(session) {
  3. doc.rank = 'Captain';
  4. await doc.save({ session });
  5. doc.isNew; // false
  6. // Throw an error to abort the transaction
  7. throw new Error('Oops!');
  8. },{ readPreference: 'primary' }).catch(() => {});
  9. // true, `transaction()` reset the document's state because the
  10. // transaction was aborted.
  11. doc.isNew;

Connection.prototype.useDb()

Parameters
  • name «String» The database name

  • [options] «Object»

  • [options.useCache=false] «Boolean» If true, cache results so calling useDb() multiple times with the same name only creates 1 connection object.

  • [options.noListener=false] «Boolean» If true, the connection object will not make the db listen to events on the original connection. See issue #9961.

Returns:
  • «Connection» New Connection Object

Switches to a different database using the same connection pool.

Returns a new connection object, with the new db.


Connection.prototype.user

Type:
  • «property»

The username specified in the URI

Example

  1. mongoose.createConnection('mongodb://val:psw@localhost:27017/mydb').user; // "val"

Connection.prototype.watch()

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

Watches the entire underlying database for changes. Similar to Model.watch().

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:

  1. const User = conn.model('User', new Schema({ name: String }));
  2. const changeStream = conn.watch().on('change', data => console.log(data));
  3. // Triggers a 'change' event on the change stream.
  4. await User.create({ name: 'test' });

Document


Document.prototype.$errors

Type:
  • «property»

Hash containing current validation $errors.


Document.prototype.$getAllSubdocs()

Get all subdocs (by bfs)


Document.prototype.$ignore()

Parameters
  • path «String» the path to ignore

Don’t run validation on this path or persist changes to this path.

Example:

  1. doc.foo = null;
  2. doc.$ignore('foo');
  3. doc.save(); // changes to foo will not be persisted and validators won't be run

Document.prototype.$isDefault()

Parameters
  • [path] «String»
Returns:
  • «Boolean»

Checks if a path is set to its default.

Example

  1. MyModel = mongoose.model('test', { name: { type: String, default: 'Val '} });
  2. const m = new MyModel();
  3. m.$isDefault('name'); // true

Document.prototype.$isDeleted()

Parameters
  • [val] «Boolean» optional, overrides whether mongoose thinks the doc is deleted
Returns:
  • «Boolean» whether mongoose thinks this doc is deleted.

Getter/setter, determines whether the document was removed or not.

Example:

  1. const product = await product.remove();
  2. product.$isDeleted(); // true
  3. product.remove(); // no-op, doesn't send anything to the db
  4. product.$isDeleted(false);
  5. product.$isDeleted(); // false
  6. product.remove(); // will execute a remove against the db

Document.prototype.$isEmpty()

Returns:
  • «Boolean»

Returns true if the given path is nullish or only contains empty objects. Useful for determining whether this subdoc will get stripped out by the minimize option.

Example:

  1. const schema = new Schema({ nested: { foo: String } });
  2. const Model = mongoose.model('Test', schema);
  3. const doc = new Model({});
  4. doc.$isEmpty('nested'); // true
  5. doc.nested.$isEmpty(); // true
  6. doc.nested.foo = 'bar';
  7. doc.$isEmpty('nested'); // false
  8. doc.nested.$isEmpty(); // false

Document.prototype.$isNew

Type:
  • «property»

Boolean flag specifying if the document is new.


Document.prototype.$locals

Type:
  • «property»

Empty object that you can use for storing properties on the document. This is handy for passing data to middleware without conflicting with Mongoose internals.

Example:

  1. schema.pre('save', function() {
  2. // Mongoose will set `isNew` to `false` if `save()` succeeds
  3. this.$locals.wasNew = this.isNew;
  4. });
  5. schema.post('save', function() {
  6. // Prints true if `isNew` was set before `save()`
  7. console.log(this.$locals.wasNew);
  8. });

Document.prototype.$markValid()

Parameters
  • path «String» the field to mark as valid

Marks a path as valid, removing existing validation errors.


Document.prototype.$op

Type:
  • «property»

A string containing the current operation that Mongoose is executing on this document. May be null, 'save', 'validate', or 'remove'.

Example:

  1. const doc = new Model({ name: 'test' });
  2. doc.$op; // null
  3. const promise = doc.save();
  4. doc.$op; // 'save'
  5. await promise;
  6. doc.$op; // null

Document.prototype.$parent()

Alias for parent(). If this document is a subdocument or populated document, returns the document’s parent. Returns undefined otherwise.


Document.prototype.$session()

Parameters
  • [session] «ClientSession» overwrite the current session
Returns:
  • «ClientSession»

Getter/setter around the session associated with this document. Used to automatically set session if you save() a doc that you got from a query with an associated session.

Example:

  1. const session = MyModel.startSession();
  2. const doc = await MyModel.findOne().session(session);
  3. doc.$session() === session; // true
  4. doc.$session(null);
  5. doc.$session() === null; // true

If this is a top-level document, setting the session propagates to all child docs.


Document.prototype.$set()

Parameters
  • path «String|Object» path or object of key/vals to set

  • val «Any» the value to set

  • [type] «Schema|String|Number|Buffer|*» optionally specify a type for “on-the-fly” attributes

  • [options] «Object» optionally specify options that modify the behavior of the set

Alias for set(), used internally to avoid conflicts


Document.prototype.$where

Type:
  • «property»

Set this property to add additional query filters when Mongoose saves this document and isNew is false.

Example:

  1. // Make sure `save()` never updates a soft deleted document.
  2. schema.pre('save', function() {
  3. this.$where = { isDeleted: false };
  4. });

Document.prototype.depopulate()

Parameters
  • path «String»
Returns:
  • «Document» this

Takes a populated field and returns it to its unpopulated state.

Example:

  1. Model.findOne().populate('author').exec(function (err, doc) {
  2. console.log(doc.author.name); // Dr.Seuss
  3. console.log(doc.depopulate('author'));
  4. console.log(doc.author); // '5144cf8050f071d979c118a7'
  5. })

If the path was not provided, then all populated fields are returned to their unpopulated state.


Document.prototype.directModifiedPaths()

Returns:
  • «Array»

Returns the list of paths that have been directly modified. A direct modified path is a path that you explicitly set, whether via doc.foo = 'bar', Object.assign(doc, { foo: 'bar' }), or doc.set('foo', 'bar').

A path a may be in modifiedPaths() but not in directModifiedPaths() because a child of a was directly modified.

Example

  1. const schema = new Schema({ foo: String, nested: { bar: String } });
  2. const Model = mongoose.model('Test', schema);
  3. await Model.create({ foo: 'original', nested: { bar: 'original' } });
  4. const doc = await Model.findOne();
  5. doc.nested.bar = 'modified';
  6. doc.directModifiedPaths(); // ['nested.bar']
  7. doc.modifiedPaths(); // ['nested', 'nested.bar']

Document.prototype.equals()

Parameters
  • doc «Document» a document to compare
Returns:
  • «Boolean»

Returns true if this document is equal to another document.

Documents are considered equal when they have matching _ids, unless neither document has an _id, in which case this function falls back to using deepEqual().


Document.prototype.errors

Type:
  • «property»

Hash containing current validation errors.


Document.prototype.get()

Parameters
  • path «String»
  • [type] «Schema|String|Number|Buffer|*» optionally specify a type for on-the-fly attributes

  • [options] «Object»

  • [options.virtuals=false] «Boolean» Apply virtuals before getting this path

  • [options.getters=true] «Boolean» If false, skip applying getters and just get the raw value

Returns the value of a path.

Example

  1. // path
  2. doc.get('age') // 47
  3. // dynamic casting to a string
  4. doc.get('age', String) // "47"

Document.prototype.getChanges()

Returns:
  • «Object»

Returns the changes that happened to the document in the format that will be sent to MongoDB.

Example:

  1. const userSchema = new Schema({
  2. name: String,
  3. age: Number,
  4. country: String
  5. });
  6. const User = mongoose.model('User', userSchema);
  7. const user = await User.create({
  8. name: 'Hafez',
  9. age: 25,
  10. country: 'Egypt'
  11. });
  12. // returns an empty object, no changes happened yet
  13. user.getChanges(); // { }
  14. user.country = undefined;
  15. user.age = 26;
  16. user.getChanges(); // { $set: { age: 26 }, { $unset: { country: 1 } } }
  17. await user.save();
  18. user.getChanges(); // { }

Modifying the object that getChanges() returns does not affect the document’s change tracking state. Even if you delete user.getChanges().$set, Mongoose will still send a $set to the server.


Document.prototype.id

Type:
  • «property»

The string version of this documents _id.

Note:

This getter exists on all documents by default. The getter can be disabled by setting the id option of its Schema to false at construction time.

  1. new Schema({ name: String }, { id: false });

Document.prototype.init()

Parameters
  • doc «Object» document returned by mongo

Initializes the document without setters or marking anything modified.

Called internally after a document is returned from mongodb. Normally, you do not need to call this function on your own.

This function triggers init middleware. Note that init hooks are synchronous.


Document.prototype.inspect()

Helper for console.log


Document.prototype.invalidate()

Parameters
  • path «String» the field to invalidate. For array elements, use the array.i.field syntax, where i is the 0-based index in the array.

  • errorMsg «String|Error» the error which states the reason path was invalid

  • value «Object|String|Number|any» optional invalid value

  • [kind] «String» optional kind property for the error

Returns:
  • «ValidationError» the current ValidationError, with all currently invalidated paths

Marks a path as invalid, causing validation to fail.

The errorMsg argument will become the message of the ValidationError.

The value argument (if passed) will be available through the ValidationError.value property.

  1. doc.invalidate('size', 'must be less than 20', 14);
  2. doc.validate(function (err) {
  3. console.log(err)
  4. // prints
  5. { message: 'Validation failed',
  6. name: 'ValidationError',
  7. errors:
  8. { size:
  9. { message: 'must be less than 20',
  10. name: 'ValidatorError',
  11. path: 'size',
  12. type: 'user defined',
  13. value: 14 } } }
  14. })

Document.prototype.isDirectModified()

Parameters
  • path «String|Array<String>»
Returns:
  • «Boolean»

Returns true if path was directly set and modified, else false.

Example

  1. doc.set('documents.0.title', 'changed');
  2. doc.isDirectModified('documents.0.title') // true
  3. doc.isDirectModified('documents') // false

Document.prototype.isDirectSelected()

Parameters
  • path «String»
Returns:
  • «Boolean»

Checks if path was explicitly selected. If no projection, always returns true.

Example

  1. Thing.findOne().select('nested.name').exec(function (err, doc) {
  2. doc.isDirectSelected('nested.name') // true
  3. doc.isDirectSelected('nested.otherName') // false
  4. doc.isDirectSelected('nested') // false
  5. })

Document.prototype.isInit()

Parameters
  • path «String»
Returns:
  • «Boolean»

Checks if path is in the init state, that is, it was set by Document#init() and not modified since.


Document.prototype.isModified()

Parameters
  • [path] «String» optional
Returns:
  • «Boolean»

Returns true if any of the given paths is modified, else false. If no arguments, returns true if any path in this document is modified.

If path is given, checks if a path or any full path containing path as part of its path chain has been modified.

Example

  1. doc.set('documents.0.title', 'changed');
  2. doc.isModified() // true
  3. doc.isModified('documents') // true
  4. doc.isModified('documents.0.title') // true
  5. doc.isModified('documents otherProp') // true
  6. doc.isDirectModified('documents') // false

Document.prototype.isNew

Type:
  • «property»

Boolean flag specifying if the document is new.


Document.prototype.isSelected()

Parameters
  • path «String|Array<String>»
Returns:
  • «Boolean»

Checks if path was selected in the source query which initialized this document.

Example

  1. const doc = await Thing.findOne().select('name');
  2. doc.isSelected('name') // true
  3. doc.isSelected('age') // false

Document.prototype.markModified()

Parameters
  • path «String» the path to mark modified

  • [scope] «Document» the scope to run validators with

Marks the path as having pending changes to write to the db.

Very helpful when using Mixed types.

Example:

  1. doc.mixed.type = 'changed';
  2. doc.markModified('mixed.type');
  3. doc.save() // changes to mixed.type are now persisted

Document.prototype.modifiedPaths()

Parameters
  • [options] «Object»

  • [options.includeChildren=false] «Boolean» if true, returns children of modified paths as well. For example, if false, the list of modified paths for doc.colors = { primary: 'blue' }; will not contain colors.primary. If true, modifiedPaths() will return an array that contains colors.primary.

Returns:
  • «Array»

Returns the list of paths that have been modified.


Document.prototype.overwrite()

Parameters
  • obj «Object» the object to overwrite this document with

Overwrite all values in this document with the values of obj, except for immutable properties. Behaves similarly to set(), except for it unsets all properties that aren’t in obj.


Document.prototype.parent()

If this document is a subdocument or populated document, returns the document’s parent. Returns undefined otherwise.


Document.prototype.populate()

Parameters
  • path «String|Object|Array» either the path to populate or an object specifying all parameters, or either an array of those

  • [select] «Object|String» Field selection for the population query

  • [model] «Model» The model you wish to use for population. If not specified, populate will look up the model by the name in the Schema’s ref field.

  • [match] «Object» Conditions for the population query

  • [options] «Object» Options for the population query (sort, etc)

  • [options.path=null] «String» The path to populate.

  • [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.transform=null] «Function» Function that Mongoose will call on every populated document that allows you to transform the populated document.

  • [options.options=null] «Object» Additional options like limit and lean.

  • [callback] «Function» Callback

Returns:
  • «Promise,null»

Populates paths on an existing document.

Example:

  1. await doc.populate([
  2. 'stories',
  3. { path: 'fans', sort: { name: -1 } }
  4. ]);
  5. doc.populated('stories'); // Array of ObjectIds
  6. doc.stories[0].title; // 'Casino Royale'
  7. doc.populated('fans'); // Array of ObjectIds
  8. await doc.populate('fans', '-email');
  9. doc.fans[0].email // not populated
  10. await doc.populate('author fans', '-email');
  11. doc.author.email // not populated
  12. doc.fans[0].email // not populated

Document.prototype.populated()

Parameters
  • path «String»
Returns:
  • «Array,ObjectId,Number,Buffer,String,undefined»

Gets _id(s) used during population of the given path.

Example:

  1. Model.findOne().populate('author').exec(function (err, doc) {
  2. console.log(doc.author.name) // Dr.Seuss
  3. console.log(doc.populated('author')) // '5144cf8050f071d979c118a7'
  4. })

If the path was not populated, returns undefined.


Document.prototype.replaceOne()

Parameters
  • doc «Object»
  • options «Object»
  • callback «Function»
Returns:
  • «Query»

Sends a replaceOne command with this document _id as the query selector.

Valid options:


Document.prototype.save()

Parameters
Returns:
  • «Promise,undefined» Returns undefined if used with callback or a Promise otherwise.

Saves this document by inserting a new document into the database if document.isNew is true, or sends an updateOne operation only with the modifications to the database, it does not replace the whole document in the latter case.

Example:

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

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

Example:

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

Document.prototype.schema

Type:
  • «property»

The document’s schema.


Document.prototype.set()

Parameters
  • path «String|Object» path or object of key/vals to set

  • val «Any» the value to set

  • [type] «Schema|String|Number|Buffer|*» optionally specify a type for “on-the-fly” attributes

  • [options] «Object» optionally specify options that modify the behavior of the set

Sets the value of a path, or many paths.

Example:

  1. // path, value
  2. doc.set(path, value)
  3. // object
  4. doc.set({
  5. path : value
  6. , path2 : {
  7. path : value
  8. }
  9. })
  10. // on-the-fly cast to number
  11. doc.set(path, value, Number)
  12. // on-the-fly cast to string
  13. doc.set(path, value, String)
  14. // changing strict mode behavior
  15. doc.set(path, value, { strict: false });

Document.prototype.toJSON()

Parameters
  • options «Object»
Returns:
  • «Object»

The return value of this method is used in calls to JSON.stringify(doc).

This method accepts the same options as Document#toObject. To apply the options to every document of your schema by default, set your schemas toJSON option to the same argument.

  1. schema.set('toJSON', { virtuals: true })

See schema options for details.


Document.prototype.toObject()

Parameters
  • [options] «Object»

  • [options.getters=false] «Boolean» if true, apply all getters, including virtuals

  • [options.virtuals=false] «Boolean» if true, apply virtuals, including aliases. Use { getters: true, virtuals: false } to just apply getters, not virtuals

  • [options.aliases=true] «Boolean» if options.virtuals = true, you can set options.aliases = false to skip applying aliases. This option is a no-op if options.virtuals = false.

  • [options.minimize=true] «Boolean» if true, omit any empty objects from the output

  • [options.transform=null] «Function|null» if set, mongoose will call this function to allow you to transform the returned object

  • [options.depopulate=false] «Boolean» if true, replace any conventionally populated paths with the original id in the output. Has no affect on virtual populated paths.

  • [options.versionKey=true] «Boolean» if false, exclude the version key (__v by default) from the output

  • [options.flattenMaps=false] «Boolean» if true, convert Maps to POJOs. Useful if you want to JSON.stringify() the result of toObject().

  • [options.useProjection=false] «Boolean»

    • If true, omits fields that are excluded in this document’s projection. Unless you specified a projection, this will omit any field that has select: false in the schema.
Returns:
  • «Object» js object

Converts this document into a plain-old JavaScript object (POJO).

Buffers are converted to instances of mongodb.Binary for proper storage.

Options:

  • getters apply all getters (path and virtual getters), defaults to false
  • aliases apply all aliases if virtuals=true, defaults to true
  • virtuals apply virtual getters (can override getters option), defaults to false
  • minimize remove empty objects, defaults to true
  • transform a transform function to apply to the resulting document before returning
  • depopulate depopulate any populated paths, replacing them with their original refs, defaults to false
  • versionKey whether to include the version key, defaults to true
  • flattenMaps convert Maps to POJOs. Useful if you want to JSON.stringify() the result of toObject(), defaults to false
  • useProjection set to true to omit fields that are excluded in this document’s projection. Unless you specified a projection, this will omit any field that has select: false in the schema.

Getters/Virtuals

Example of only applying path getters

  1. doc.toObject({ getters: true, virtuals: false })

Example of only applying virtual getters

  1. doc.toObject({ virtuals: true })

Example of applying both path and virtual getters

  1. doc.toObject({ getters: true })

To apply these options to every document of your schema by default, set your schemas toObject option to the same argument.

  1. schema.set('toObject', { virtuals: true })

Transform

We may need to perform a transformation of the resulting object based on some criteria, say to remove some sensitive information or return a custom object. In this case we set the optional transform function.

Transform functions receive three arguments

  1. function (doc, ret, options) {}
  • doc The mongoose document which is being converted
  • ret The plain object representation which has been converted
  • options The options in use (either schema options or the options passed inline)

Example

  1. // specify the transform schema option
  2. if (!schema.options.toObject) schema.options.toObject = {};
  3. schema.options.toObject.transform = function (doc, ret, options) {
  4. // remove the _id of every document before returning the result
  5. delete ret._id;
  6. return ret;
  7. }
  8. // without the transformation in the schema
  9. doc.toObject(); // { _id: 'anId', name: 'Wreck-it Ralph' }
  10. // with the transformation
  11. doc.toObject(); // { name: 'Wreck-it Ralph' }

With transformations we can do a lot more than remove properties. We can even return completely new customized objects:

  1. if (!schema.options.toObject) schema.options.toObject = {};
  2. schema.options.toObject.transform = function (doc, ret, options) {
  3. return { movie: ret.name }
  4. }
  5. // without the transformation in the schema
  6. doc.toObject(); // { _id: 'anId', name: 'Wreck-it Ralph' }
  7. // with the transformation
  8. doc.toObject(); // { movie: 'Wreck-it Ralph' }

Note: if a transform function returns undefined, the return value will be ignored.

Transformations may also be applied inline, overridding any transform set in the options:

  1. function xform (doc, ret, options) {
  2. return { inline: ret.name, custom: true }
  3. }
  4. // pass the transform as an inline option
  5. doc.toObject({ transform: xform }); // { inline: 'Wreck-it Ralph', custom: true }

If you want to skip transformations, use transform: false:

  1. schema.options.toObject.hide = '_id';
  2. schema.options.toObject.transform = function (doc, ret, options) {
  3. if (options.hide) {
  4. options.hide.split(' ').forEach(function (prop) {
  5. delete ret[prop];
  6. });
  7. }
  8. return ret;
  9. }
  10. const doc = new Doc({ _id: 'anId', secret: 47, name: 'Wreck-it Ralph' });
  11. doc.toObject(); // { secret: 47, name: 'Wreck-it Ralph' }
  12. doc.toObject({ hide: 'secret _id', transform: false });// { _id: 'anId', secret: 47, name: 'Wreck-it Ralph' }
  13. doc.toObject({ hide: 'secret _id', transform: true }); // { name: 'Wreck-it Ralph' }

If you pass a transform in toObject() options, Mongoose will apply the transform to subdocuments in addition to the top-level document. Similarly, transform: false skips transforms for all subdocuments.

Note that this is behavior is different for transforms defined in the schema

if you define a transform in schema.options.toObject.transform, that transform will not apply to subdocuments.

  1. const memberSchema = new Schema({ name: String, email: String });
  2. const groupSchema = new Schema({ members: [memberSchema], name: String, email });
  3. const Group = mongoose.model('Group', groupSchema);
  4. const doc = new Group({
  5. name: 'Engineering',
  6. email: 'dev@mongoosejs.io',
  7. members: [{ name: 'Val', email: 'val@mongoosejs.io' }]
  8. });
  9. // Removes `email` from both top-level document **and** array elements
  10. // { name: 'Engineering', members: [{ name: 'Val' }] }
  11. doc.toObject({ transform: (doc, ret) => { delete ret.email; return ret; } });

Transforms, like all of these options, are also available for toJSON. See this guide to JSON.stringify() to learn why toJSON() and toObject() are separate functions.

See schema options for some more details.

During save, no custom options are applied to the document before being sent to the database.


Document.prototype.toString()

Helper for console.log


Document.prototype.undefined

Returns:
  • «Array<Document>» array of populated documents. Empty array if there are no populated documents associated with this document.

Gets all populated documents associated with this document.


Document.prototype.unmarkModified()

Parameters
  • path «String» the path to unmark modified

Clears the modified state on the specified path.

Example:

  1. doc.foo = 'bar';
  2. doc.unmarkModified('foo');
  3. doc.save(); // changes to foo will not be persisted

Document.prototype.update()

Parameters
  • doc «Object»
  • options «Object»
  • callback «Function»
Returns:
  • «Query»

Sends an update command with this document _id as the query selector.

Example:

  1. weirdCar.update({$inc: {wheels:1}}, { w: 1 }, callback);

Valid options:


Document.prototype.updateOne()

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

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

  • callback «Function»

Returns:
  • «Query»

Sends an updateOne command with this document _id as the query selector.

Example:

  1. weirdCar.updateOne({$inc: {wheels:1}}, { w: 1 }, callback);

Valid options:


Document.prototype.validate()

Parameters
  • [pathsToValidate] «Array|String» list of paths to validate. If set, Mongoose will validate only the modified paths that are in the given list.

  • [options] «Object» internal options

  • [options.validateModifiedOnly=false] «Boolean» if true mongoose validates only modified paths.

  • [options.pathsToSkip] «Array|string» list of paths to skip. If set, Mongoose will validate every modified path that is not in this list.

  • [callback] «Function» optional callback called after validation completes, passing an error if one occurred

Returns:
  • «Promise» Promise

Executes registered validation rules for this document.

Note:

This method is called pre save and if a validation rule is violated, save is aborted and the error is returned to your callback.

Example:

  1. doc.validate(function (err) {
  2. if (err) handleError(err);
  3. else // validation passed
  4. });

Document.prototype.validateSync()

Parameters
  • pathsToValidate «Array|string» only validate the given paths

  • [options] «Object» options for validation

  • [options.validateModifiedOnly=false] «Boolean» If true, Mongoose will only validate modified paths, as opposed to modified paths and required paths.

  • [options.pathsToSkip] «Array|string» list of paths to skip. If set, Mongoose will validate every modified path that is not in this list.

Returns:
  • «ValidationError,undefined» ValidationError if there are errors during validation, or undefined if there is no error.

Executes registered validation rules (skipping asynchronous validators) for this document.

Note:

This method is useful if you need synchronous validation.

Example:

  1. const err = doc.validateSync();
  2. if (err) {
  3. handleError(err);
  4. } else {
  5. // validation passed
  6. }

Model


Model()

Parameters
  • doc «Object» values for initial set

  • optional «[fields]» object containing the fields that were selected in the query which returned this document. You do not need to set this parameter to ensure Mongoose handles your query projection.

  • [skipId=false] «Boolean» optional boolean. If true, mongoose doesn’t add an _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.

Example:

  1. // `UserModel` is a "Model", a subclass of `mongoose.Model`.
  2. const UserModel = mongoose.model('User', new Schema({ name: String }));
  3. // You can use a Model to create new documents using `new`:
  4. const userDoc = new UserModel({ name: 'Foo' });
  5. await userDoc.save();
  6. // You also use a model to create queries:
  7. const userFromDb = await UserModel.findOne({ name: 'Foo' });

Model.aggregate()

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

  • [options] «Object» aggregation options

  • [callback] «Function»

Returns:
  • «Aggregate»

Performs aggregations on the models collection.

If a callback is passed, the aggregate is executed and a Promise is returned. If a callback is not passed, the aggregate itself is returned.

This function triggers the following middleware.

  • aggregate()

Example:

  1. // Find the max balance of all accounts
  2. const res = await Users.aggregate([
  3. { $group: { _id: null, maxBalance: { $max: '$balance' }}},
  4. { $project: { _id: 0, maxBalance: 1 }}
  5. ]);
  6. console.log(res); // [ { maxBalance: 98000 } ]
  7. // Or use the aggregation pipeline builder.
  8. const res = await Users.aggregate().
  9. group({ _id: null, maxBalance: { $max: '$balance' } }).
  10. project('-id maxBalance').
  11. exec();
  12. 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.buildBulkWriteOperations()

Parameters
  • options «Object»
  • options.skipValidation «Boolean» defaults to false, when set to true, building the write operations will bypass validating the documents.

@param {[Document]} documents The array of documents to build write operations of


Model.bulkSave()

Parameters
  • documents «[Document]»

takes an array of documents, gets the changes and inserts/updates documents in the database according to whether or not the document is new, or whether it has changes or not.

bulkSave uses bulkWrite under the hood, so it’s mostly useful when dealing with many documents (10K+)


Model.bulkWrite()

Parameters
  • ops «Array»

  • [ops.insertOne.document] «Object» The document to insert

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

  • [opts.updateOne.update] «Object» An object containing update operators

  • [opts.updateOne.upsert=false] «Boolean» If true, insert a doc if none match

  • [opts.updateOne.timestamps=true] «Boolean» If false, do not apply timestamps to the operation

  • [opts.updateOne.collation] «Object» The MongoDB collation to use

  • [opts.updateOne.arrayFilters] «Array» The array filters used in update

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

  • [opts.updateMany.update] «Object» An object containing update operators

  • [opts.updateMany.upsert=false] «Boolean» If true, insert a doc if no documents match filter

  • [opts.updateMany.timestamps=true] «Boolean» If false, do not apply timestamps to the operation

  • [opts.updateMany.collation] «Object» The MongoDB collation to use

  • [opts.updateMany.arrayFilters] «Array» The array filters used in update

  • [opts.deleteOne.filter] «Object» Delete the first document that matches this filter

  • [opts.deleteMany.filter] «Object» Delete all documents that match this filter

  • [opts.replaceOne.filter] «Object» Replace the first document that matches this filter

  • [opts.replaceOne.replacement] «Object» The replacement document

  • [opts.replaceOne.upsert=false] «Boolean» If true, insert a doc if no documents match filter

  • [options] «Object»

  • [options.ordered=true] «Boolean» If true, execute writes in order and stop at the first error. If false, execute writes in parallel and continue until all writes have either succeeded or errored.

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

  • [options.w=1] «String|number» The write concern. See Query#w() for more information.

  • [options.wtimeout=null] «number» The write concern timeout.

  • [options.j=true] «Boolean» If false, disable journal acknowledgement

  • [options.bypassDocumentValidation=false] «Boolean» If true, disable MongoDB server-side schema validation for all writes in this bulk.

  • [options.strict=null] «Boolean» Overwrites the strict option on schema. If false, allows filtering and writing fields not defined in the schema for all writes in this bulk.

  • [callback] «Function» callback function(error, bulkWriteOpResult) {}

Returns:

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:

  1. Character.bulkWrite([
  2. {
  3. insertOne: {
  4. document: {
  5. name: 'Eddard Stark',
  6. title: 'Warden of the North'
  7. }
  8. }
  9. },
  10. {
  11. updateOne: {
  12. filter: { name: 'Eddard Stark' },
  13. // If you were using the MongoDB driver directly, you'd need to do
  14. // `update: { $set: { title: ... } }` but mongoose adds $set for
  15. // you.
  16. update: { title: 'Hand of the King' }
  17. }
  18. },
  19. {
  20. deleteOne: {
  21. {
  22. filter: { name: 'Eddard Stark' }
  23. }
  24. }
  25. }
  26. ]).then(res => {
  27. // Prints "1 1 1"
  28. console.log(res.insertedCount, res.modifiedCount, res.deletedCount);
  29. });

The supported operations are:

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

Model.cleanIndexes()

Parameters
  • [callback] «Function» optional callback
Returns:
  • «Promise,undefined» 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.count()

Parameters
  • filter «Object»
  • [callback] «Function»
Returns:
  • «Query»

Counts number of documents that match filter in a database collection.

This method is deprecated. If you want to count the number of documents in a collection, e.g. count({}), use the estimatedDocumentCount() function instead. Otherwise, use the countDocuments() function instead.

Example:

  1. const count = await Adventure.count({ type: 'jungle' });
  2. console.log('there are %d jungle adventures', count);

Model.countDocuments()

Parameters
  • filter «Object»
  • [callback] «Function»
Returns:
  • «Query»

Counts number of documents matching filter in a database collection.

Example:

  1. Adventure.countDocuments({ type: 'jungle' }, function (err, count) {
  2. console.log('there are %d jungle adventures', count);
  3. });

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.

  • [callback] «Function» callback

Returns:
  • «Promise»

Shortcut for saving one or more documents to the database. MyModel.create(docs) does new MyModel(doc).save() for every doc in docs.

This function triggers the following middleware.

  • save()

Example:

  1. // Insert one new `Character` document
  2. await Character.create({ name: 'Jean-Luc Picard' });
  3. // Insert multiple new `Character` documents
  4. await Character.create([{ name: 'Will Riker' }, { name: 'Geordi LaForge' }]);
  5. // Create a new character within a transaction. Note that you **must**
  6. // pass an array as the first parameter to `create()` if you want to
  7. // specify options.
  8. 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://docs.mongodb.com/manual/core/transactions/#transactions-and-operations

Note 2: You don’t have to call this if your schema contains index or unique field. In that case, just use Model.init()

Example:

  1. const userSchema = new Schema({ name: String })
  2. const User = mongoose.model('User', userSchema);
  3. User.createCollection().then(function(collection) {
  4. console.log('Collection is created!');
  5. });

Model.createIndexes()

Parameters
  • [options] «Object» internal options

  • [cb] «Function» optional callback

Returns:
  • «Promise»

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


Model.deleteMany()

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

  1. 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
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:

  1. 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» not used at all.

  • callback «Function» optional callback

Does a dry-run of Model.syncIndexes(), meaning that the result of this function would be the result of Model.syncIndexes().


Model.discriminator()

Parameters
  • name «String» discriminator model name

  • schema «Schema» discriminator model schema

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

Returns:
  • «Model» The newly created discriminator model

Adds a discriminator type.

Example:

  1. function BaseSchema() {
  2. Schema.apply(this, arguments);
  3. this.add({
  4. name: String,
  5. createdAt: Date
  6. });
  7. }
  8. util.inherits(BaseSchema, Schema);
  9. const PersonSchema = new BaseSchema();
  10. const BossSchema = new BaseSchema({ department: String });
  11. const Person = mongoose.model('Person', PersonSchema);
  12. const Boss = Person.discriminator('Boss', BossSchema);
  13. new Boss().__t; // "Boss". `__t` is the default `discriminatorKey`
  14. const employeeSchema = new Schema({ boss: ObjectId });
  15. const Employee = Person.discriminator('Employee', employeeSchema, 'staff');
  16. new Employee().__t; // "staff" because of 3rd argument above

Model.distinct()

Parameters
  • field «String»
  • [conditions] «Object» optional

  • [callback] «Function»

Returns:
  • «Query»

Creates a Query for a distinct operation.

Passing a callback executes the query.

Example

  1. Link.distinct('url', { clicks: {$gt: 100}}, function (err, result) {
  2. if (err) return handleError(err);
  3. assert(Array.isArray(result));
  4. console.log('unique urls with more than 100 clicks', result);
  5. })
  6. const query = Link.distinct('url');
  7. query.exec(callback);

Model.ensureIndexes()

Parameters
  • [options] «Object» internal options

  • [cb] «Function» optional callback

Returns:
  • «Promise»

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

Example:

  1. Event.ensureIndexes(function (err) {
  2. if (err) return handleError(err);
  3. });

After completion, an index event is emitted on this Model passing an error if one occurred.

Example:

  1. const eventSchema = new Schema({ thing: { type: 'string', unique: true }})
  2. const Event = mongoose.model('Event', eventSchema);
  3. Event.on('index', function (err) {
  4. if (err) console.error(err); // error occurred during index creation
  5. })

NOTE: It is not recommended that you run this in production. Index creation may impact database performance depending on your load. Use with caution.


Model.estimatedDocumentCount()

Parameters
  • [options] «Object»
  • [callback] «Function»
Returns:
  • «Query»

Estimates the number of documents in the MongoDB collection. Faster than using countDocuments() for large collections because estimatedDocumentCount() uses collection metadata rather than scanning the entire collection.

Example:

  1. const numAdventures = Adventure.estimatedDocumentCount();

Model.events

Type:
  • «property»

Event emitter that reports any errors that occurred. Useful for global error handling.

Example:

  1. MyModel.events.on('error', err => console.log(err.message));
  2. // Prints a 'CastError' because of the above handler
  3. await MyModel.findOne({ _id: 'notanid' }).catch(noop);

Model.exists()

Parameters
Returns:
  • «Query»

Returns true if at least one document exists in the database that matches the given filter, and false otherwise.

Under the hood, MyModel.exists({ answer: 42 }) is equivalent to MyModel.findOne({ answer: 42 }).select({ _id: 1 }).lean()

Example:

  1. await Character.deleteMany({});
  2. await Character.create({ name: 'Jean-Luc Picard' });
  3. await Character.exists({ name: /picard/i }); // { _id: ... }
  4. await Character.exists({ name: /riker/i }); // null

This function triggers the following middleware.

  • findOne()

Model.find()

Parameters
Returns:
  • «Query»

Finds documents.

Mongoose casts the filter to match the model’s schema before the command is sent. See our query casting tutorial for more information on how Mongoose casts filter.

Examples:

  1. // find all documents
  2. await MyModel.find({});
  3. // find all documents named john and at least 18
  4. await MyModel.find({ name: 'john', age: { $gte: 18 } }).exec();
  5. // executes, passing results to callback
  6. MyModel.find({ name: 'john', age: { $gte: 18 }}, function (err, docs) {});
  7. // executes, name LIKE john and only selecting the "name" and "friends" fields
  8. await MyModel.find({ name: /john/i }, 'name friends').exec();
  9. // passing options
  10. await MyModel.find({ name: /john/i }, null, { skip: 10 }).exec();

Model.findById()

Parameters
Returns:
  • «Query»

Finds a single document by its _id field. findById(id) is almost* equivalent to findOne({ _id: id }). If you want to query by a document’s _id, use findById() instead of findOne().

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

This function triggers the following middleware.

  • findOne()

* Except for how it treats undefined. If you 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:

  1. // Find the adventure with the given `id`, or `null` if not found
  2. await Adventure.findById(id).exec();
  3. // using callback
  4. Adventure.findById(id, function (err, adventure) {});
  5. // select only the adventures name and length
  6. await Adventure.findById(id, 'name length').exec();

Model.findByIdAndDelete()

Parameters
Returns:
  • «Query»

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

This function triggers the following middleware.

  • findOneAndDelete()

Model.findByIdAndRemove()

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

  • [options] «Object» optional see Query.prototype.setOptions()

  • [options.strict] «Boolean|String» overwrites the schema’s strict mode option

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

  • [options.projection=null] «Object|String|Array<String>» optional fields to return, see Query.prototype.select()

  • [callback] «Function»

Returns:
  • «Query»

Issue a mongodb findAndModify remove command by a document’s _id field. findByIdAndRemove(id, ...) is equivalent to findOneAndRemove({ _id: id }, ...).

Finds a matching document, removes it, passing the found document (if any) to the callback.

Executes the query if callback is passed.

This function triggers the following middleware.

  • findOneAndRemove()

Options:

  • sort: if multiple docs are found by the conditions, sets the sort order to choose which doc to update
  • select: sets the document fields to return
  • rawResult: if true, returns the raw result from the MongoDB driver
  • strict: overwrites the schema’s strict mode option for this update

Examples:

  1. A.findByIdAndRemove(id, options, callback) // executes
  2. A.findByIdAndRemove(id, options) // return Query
  3. A.findByIdAndRemove(id, callback) // executes
  4. A.findByIdAndRemove(id) // returns Query
  5. A.findByIdAndRemove() // returns Query

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.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.overwrite=false] «Boolean» By default, if you don’t include any update operators in update, Mongoose will wrap update in $set for you. This prevents you from accidentally overwriting the document. This option tells Mongoose to skip adding $set. An alternative to this would be using Model.findOneAndReplace({ _id: id }, update, options, callback).

  • [callback] «Function»

Returns:
  • «Query»

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

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

This function triggers the following middleware.

  • findOneAndUpdate()

Options:

  • new: bool - true to return the modified document rather than the original. defaults to false
  • upsert: bool - creates the object if it doesn’t exist. defaults to false.
  • runValidators: if true, runs update validators on this command. Update validators validate the update operation against the model’s schema.
  • setDefaultsOnInsert: true by default. If setDefaultsOnInsert and upsert are true, mongoose will apply the defaults specified in the model’s schema if a new document is created.
  • sort: if multiple docs are found by the conditions, sets the sort order to choose which doc to update
  • select: sets the document fields to return
  • rawResult: if true, returns the raw result from the MongoDB driver
  • strict: overwrites the schema’s strict mode option for this update

Examples:

  1. A.findByIdAndUpdate(id, update, options, callback) // executes
  2. A.findByIdAndUpdate(id, update, options) // returns Query
  3. A.findByIdAndUpdate(id, update, callback) // executes
  4. A.findByIdAndUpdate(id, update) // returns Query
  5. A.findByIdAndUpdate() // returns Query

Note:

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

Example:

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

This helps prevent accidentally overwriting your document with { name: 'jason bourne' }.

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.

  1. Model.findById(id, function (err, doc) {
  2. if (err) ..
  3. doc.name = 'jason bourne';
  4. doc.save(callback);
  5. });

Model.findOne()

Parameters
Returns:
  • «Query»

Finds one document.

The conditions are cast to their respective SchemaTypes before the command is sent.

Note: conditions is optional, and if conditions is null or undefined, mongoose will send an empty findOne command to MongoDB, which will return an arbitrary document. If you’re querying by _id, use findById() instead.

Example:

  1. // Find one adventure whose `country` is 'Croatia', otherwise `null`
  2. await Adventure.findOne({ country: 'Croatia' }).exec();
  3. // using callback
  4. Adventure.findOne({ country: 'Croatia' }, function (err, adventure) {});
  5. // select only the adventures name and length
  6. await Adventure.findOne({ country: 'Croatia' }, 'name length').exec();

Model.findOneAndDelete()

Parameters
Returns:
  • «Query»

Issue a MongoDB findOneAndDelete() command.

Finds a matching document, removes it, and passes the found document (if any) to the callback.

Executes the query if callback is passed.

This function triggers the following middleware.

  • findOneAndDelete()

This function differs slightly from Model.findOneAndRemove() in that findOneAndRemove() becomes a MongoDB findAndModify() command, as opposed to a findOneAndDelete() command. For most mongoose use cases, this distinction is purely pedantic. You should use findOneAndDelete() unless you have a good reason not to.

Options:

  • sort: if multiple docs are found by the conditions, sets the sort order to choose which doc to update
  • maxTimeMS: puts a time limit on the query - requires mongodb >= 2.6.0
  • select: sets the document fields to return, ex. { projection: { _id: 0 } }
  • projection: equivalent to select
  • rawResult: if true, returns the raw result from the MongoDB driver
  • strict: overwrites the schema’s strict mode option for this update

Examples:

  1. A.findOneAndDelete(conditions, options, callback) // executes
  2. A.findOneAndDelete(conditions, options) // return Query
  3. A.findOneAndDelete(conditions, callback) // executes
  4. A.findOneAndDelete(conditions) // returns Query
  5. 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.

  1. Model.findById(id, function (err, doc) {
  2. if (err) ..
  3. doc.name = 'jason bourne';
  4. doc.save(callback);
  5. });

Model.findOneAndRemove()

Parameters
Returns:
  • «Query»

Issue a mongodb findAndModify remove command.

Finds a matching document, removes it, passing the found document (if any) to the callback.

Executes the query if callback is passed.

This function triggers the following middleware.

  • findOneAndRemove()

Options:

  • sort: if multiple docs are found by the conditions, sets the sort order to choose which doc to update
  • maxTimeMS: puts a time limit on the query - requires mongodb >= 2.6.0
  • select: sets the document fields to return
  • projection: like select, it determines which fields to return, ex. { projection: { _id: 0 } }
  • rawResult: if true, returns the raw result from the MongoDB driver
  • strict: overwrites the schema’s strict mode option for this update

Examples:

  1. A.findOneAndRemove(conditions, options, callback) // executes
  2. A.findOneAndRemove(conditions, options) // return Query
  3. A.findOneAndRemove(conditions, callback) // executes
  4. A.findOneAndRemove(conditions) // returns Query
  5. A.findOneAndRemove() // 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.

  1. Model.findById(id, function (err, doc) {
  2. if (err) ..
  3. doc.name = 'jason bourne';
  4. doc.save(callback);
  5. });

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

  • [callback] «Function»

Returns:
  • «Query»

Issue a MongoDB findOneAndReplace() command.

Finds a matching document, replaces it with the provided doc, and passes the returned doc to the callback.

Executes the query if callback is passed.

This function triggers the following query middleware.

  • findOneAndReplace()

Options:

  • sort: if multiple docs are found by the conditions, sets the sort order to choose which doc to update
  • maxTimeMS: puts a time limit on the query - requires mongodb >= 2.6.0
  • select: sets the document fields to return
  • projection: like select, it determines which fields to return, ex. { projection: { _id: 0 } }
  • rawResult: if true, returns the raw result from the MongoDB driver
  • strict: overwrites the schema’s strict mode option for this update

Examples:

  1. A.findOneAndReplace(conditions, options, callback) // executes
  2. A.findOneAndReplace(conditions, options) // return Query
  3. A.findOneAndReplace(conditions, callback) // executes
  4. A.findOneAndReplace(conditions) // returns Query
  5. 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.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.overwrite=false] «Boolean» By default, if you don’t include any update operators in update, Mongoose will wrap update in $set for you. This prevents you from accidentally overwriting the document. This option tells Mongoose to skip adding $set. An alternative to this would be using Model.findOneAndReplace(conditions, update, options, callback).

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

  • [callback] «Function»

Returns:
  • «Query»

Issues a mongodb findAndModify update command.

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

Options:

  • new: bool - if true, return the modified document rather than the original. defaults to false (changed in 4.0)
  • upsert: bool - creates the object if it doesn’t exist. defaults to false.
  • overwrite: bool - if true, replace the entire document.
  • fields: {Object|String} - Field selection. Equivalent to .select(fields).findOneAndUpdate()
  • maxTimeMS: puts a time limit on the query - requires mongodb >= 2.6.0
  • sort: if multiple docs are found by the conditions, sets the sort order to choose which doc to update
  • runValidators: if true, runs update validators on this command. Update validators validate the update operation against the model’s schema.
  • setDefaultsOnInsert: true by default. If setDefaultsOnInsert and upsert are true, mongoose will apply the defaults specified in the model’s schema if a new document is created.
  • rawResult: if true, returns the raw result from the MongoDB driver
  • strict: overwrites the schema’s strict mode option for this update

Examples:

  1. A.findOneAndUpdate(conditions, update, options, callback) // executes
  2. A.findOneAndUpdate(conditions, update, options) // returns Query
  3. A.findOneAndUpdate(conditions, update, callback) // executes
  4. A.findOneAndUpdate(conditions, update) // returns Query
  5. A.findOneAndUpdate() // returns Query

Note:

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

Example:

  1. const query = { name: 'borne' };
  2. Model.findOneAndUpdate(query, { name: 'jason bourne' }, options, callback)
  3. // is sent as
  4. Model.findOneAndUpdate(query, { $set: { name: 'jason bourne' }}, options, callback)

This helps prevent accidentally overwriting your document with { name: 'jason bourne' }.

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.

  1. const doc = await Model.findById(id);
  2. doc.name = 'jason bourne';
  3. await doc.save();

Model.hydrate()

Parameters
  • obj «Object»
  • [projection] «Object|String|Array<String>» optional projection containing which fields should be selected for this document
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:

  1. // hydrate previous data into a Mongoose document
  2. const mongooseCandy = Candy.hydrate({ _id: '54108337212ffb6d459f854c', type: 'jelly bean' });

Model.init()

Parameters
  • [callback] «Function»

This function is responsible for building indexes, unless autoIndex is turned off.

Mongoose calls this function automatically when a model is created using mongoose.model() or connection.model(), so you don’t need to call it. This function is also idempotent, so you may call it to get back a promise that will resolve when your indexes are finished building as an alternative to MyModel.on('index')

Example:

  1. const eventSchema = new Schema({ thing: { type: 'string', unique: true }})
  2. // This calls `Event.init()` implicitly, so you don't need to call
  3. // `Event.init()` on your own.
  4. const Event = mongoose.model('Event', eventSchema);
  5. Event.init().then(function(Event) {
  6. // You can also use `Event.on('index')` if you prefer event emitters
  7. // over promises.
  8. console.log('Indexes are done building!');
  9. });

Model.insertMany()

Parameters
  • doc(s) «Array|Object|*»
  • [options] «Object» see the mongodb driver options

  • [options.ordered «Boolean» = true] 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 «Boolean» = false] 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 if this is an unordered insertMany.

  • [options.lean «Boolean» = false] 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 «Number» = null] 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 «String|Object|Array» = null] populates the result documents. This option is a no-op if rawResult is set.

  • [callback] «Function» callback

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:

  1. const arr = [{ name: 'Star Wars' }, { name: 'The Empire Strikes Back' }];
  2. Movies.insertMany(arr, function(error, docs) {});

Model.inspect()

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

Example:

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

Model.listIndexes()

Parameters
  • [cb] «Function» optional callback
Returns:
  • «Promise,undefined» Returns undefined if callback is specified, returns a promise if no callback.

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

Parameters
  • o «Object» an object specifying map-reduce options

  • [callback] «Function» optional callback

Returns:
  • «Promise»

Executes a mapReduce command.

o is an object specifying all mapReduce options as well as the map and reduce functions. All options are delegated to the driver implementation. See node-mongodb-native mapReduce() documentation for more detail about options.

This function does not trigger any middleware.

Example:

  1. const o = {};
  2. // `map()` and `reduce()` are run on the MongoDB server, not Node.js,
  3. // these functions are converted to strings
  4. o.map = function () { emit(this.name, 1) };
  5. o.reduce = function (k, vals) { return vals.length };
  6. User.mapReduce(o, function (err, results) {
  7. console.log(results)
  8. })

Other options:

  • query {Object} query filter object.
  • sort {Object} sort input objects using this key
  • limit {Number} max number of documents
  • keeptemp {Boolean, default:false} keep temporary data
  • finalize {Function} finalize function
  • scope {Object} scope variables exposed to map/reduce/finalize during execution
  • jsMode {Boolean, default:false} it is possible to make the execution stay in JS. Provided in MongoDB > 2.0.X
  • verbose {Boolean, default:false} provide statistics on job execution time.
  • readPreference {String}
  • out* {Object, default: {inline:1}} sets the output target for the map reduce job.

* out options:

  • {inline:1} the results are returned in an array
  • {replace: 'collectionName'} add the results to collectionName: the results replace the collection
  • {reduce: 'collectionName'} add the results to collectionName: if dups are detected, uses the reducer / finalize functions
  • {merge: 'collectionName'} add the results to collectionName: if dups exist the new docs overwrite the old

If options.out is set to replace, merge, or reduce, a Model instance is returned that can be used for further querying. Queries run against this model are all executed with the lean option; meaning only the js object is returned and no Mongoose magic is applied (getters, setters, etc).

Example:

  1. const o = {};
  2. // You can also define `map()` and `reduce()` as strings if your
  3. // linter complains about `emit()` not being defined
  4. o.map = 'function () { emit(this.name, 1) }';
  5. o.reduce = 'function (k, vals) { return vals.length }';
  6. o.out = { replace: 'createdCollectionNameForResults' }
  7. o.verbose = true;
  8. User.mapReduce(o, function (err, model, stats) {
  9. console.log('map reduce took %d ms', stats.processtime)
  10. model.find().where('value').gt(10).exec(function (err, docs) {
  11. console.log(docs);
  12. });
  13. })
  14. // `mapReduce()` returns a promise. However, ES6 promises can only
  15. // resolve to exactly one value,
  16. o.resolveToObject = true;
  17. const promise = User.mapReduce(o);
  18. promise.then(function (res) {
  19. const model = res.model;
  20. const stats = res.stats;
  21. console.log('map reduce took %d ms', stats.processtime)
  22. return model.find().where('value').gt(10).exec();
  23. }).then(function (docs) {
  24. console.log(docs);
  25. }).then(null, handleError).end()

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.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 an array. Inferred from schema by default.
  • strictPopulate: optional boolean, set to false to allow populating paths that aren’t in the schema.

Examples:

  1. const Dog = mongoose.model('Dog', new Schema({ name: String, breed: String }));
  2. const Person = mongoose.model('Person', new Schema({
  3. name: String,
  4. pet: { type: mongoose.ObjectId, ref: 'Dog' }
  5. }));
  6. const pets = await Pet.create([
  7. { name: 'Daisy', breed: 'Beagle' },
  8. { name: 'Einstein', breed: 'Catalan Sheepdog' }
  9. ]);
  10. // populate many plain objects
  11. const users = [
  12. { name: 'John Wick', dog: pets[0]._id },
  13. { name: 'Doc Brown', dog: pets[1]._id }
  14. ];
  15. await User.populate(users, { path: 'dog', select: 'name' });
  16. users[0].dog.name; // 'Daisy'
  17. users[0].dog.breed; // undefined because of `select`

Model.prototype.$where

Type:
  • «property»

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


Model.prototype.$where()

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

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.

  1. Blog.$where('this.username.indexOf("val") !== -1').exec(function (err, docs) {});

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»

Collection the model uses.

This property is read-only. Modifying this property is a no-op.


Model.prototype.db

Type:
  • «property»

Connection the model uses.


Model.prototype.deleteOne()

Parameters
  • [fn] «function(err|product)» optional callback
Returns:
  • «Promise» Promise

Removes this document from the db. Equivalent to .remove().

Example:

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

Model.prototype.discriminators

Type:
  • «property»

Registered discriminators for this model.


Model.prototype.model()

Parameters
  • name «String» model name

Returns another Model instance.

Example:

  1. const doc = new Tank;
  2. doc.model('User').findById(id, callback);

Model.prototype.modelName

Type:
  • «property»

The name of the model


Model.prototype.remove()

Parameters
  • [options] «Object»

  • [options.session=null] «Session» the session associated with this operation. If not specified, defaults to the document’s associated session.

  • [fn] «function(err|product)» optional callback

Returns:
  • «Promise» Promise

Removes this document from the db.

Example:

  1. product.remove(function (err, product) {
  2. if (err) return handleError(err);
  3. Product.findById(product._id, function (err, product) {
  4. console.log(product) // null
  5. })
  6. })

As an extra measure of flow control, remove will return a Promise (bound to fn if passed) so it could be chained, or hooked to recieve errors

Example:

  1. product.remove().then(function (product) {
  2. ...
  3. }).catch(function (err) {
  4. assert.ok(err)
  5. })

Model.prototype.save()

Parameters
Returns:
  • «Promise,undefined» Returns undefined if used with callback or a Promise otherwise.

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:

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

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

Example:

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

Model.prototype.schema

Type:
  • «property»

Schema the model uses.


Model.remove()

Parameters
  • conditions «Object»
  • [options] «Object»

  • [options.session=null] «Session» the session associated with this operation.

  • [callback] «Function»

Returns:
  • «Query»

Removes all documents that match conditions from the collection. To remove just the first document that matches conditions, set the single option to true.

This method is deprecated. See Deprecation Warnings for details.

Example:

  1. const res = await Character.remove({ name: 'Eddard Stark' });
  2. res.deletedCount; // Number of documents removed

Note:

This method sends a remove command directly to MongoDB, no Mongoose documents are involved. Because no Mongoose documents are involved, Mongoose does not execute document middleware.


Model.replaceOne()

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

  • [callback] «Function» function(error, res) {} where res has 3 properties: n, nModified, ok.

Returns:
  • «Query»

Same as update(), except MongoDB replace the existing document with the given document (no atomic operators like $set).

Example:

  1. const res = await Person.replaceOne({ _id: 24601 }, { name: 'Jean Valjean' });
  2. res.matchedCount; // Number of documents matched
  3. res.modifiedCount; // Number of documents modified
  4. res.acknowledged; // Boolean indicating everything went smoothly.
  5. res.upsertedId; // null or an id containing a document that had to be upserted.
  6. 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.startSession()

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

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

  • [callback] «Function»

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:

  1. const session = await Person.startSession();
  2. let doc = await Person.findOne({ name: 'Ned Stark' }, null, { session });
  3. await doc.remove();
  4. // `doc` will always be null, even if reading from a replica set
  5. // secondary. Without causal consistency, it is possible to
  6. // get a doc back from the below query if the query reads from a
  7. // secondary that is experiencing replication lag.
  8. 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

  • [callback] «Function» optional callback

Returns:
  • «Promise,undefined» Returns undefined if callback is specified, returns a promise if no callback.

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:

  1. const schema = new Schema({ name: { type: String, unique: true } });
  2. const Customer = mongoose.model('Customer', schema);
  3. await Customer.collection.createIndex({ age: 1 }); // Index is not in schema
  4. // Will drop the 'age' index and create an index on `name`
  5. await Customer.syncIndexes();

Model.translateAliases()

Parameters
  • raw «Object» fields/conditions that may contain aliased keys
Returns:
  • «Object» the translated ‘pure’ fields/conditions

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

Example:

  1. Character
  2. .find(Character.translateAliases({
  3. '名': 'Eddard Stark' // Alias for 'name'
  4. })
  5. .exec(function(err, characters) {})

Note:

Only translate arguments of object type anything else is returned raw


Model.update()

Parameters
  • 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.multi=false] «Boolean» whether multiple documents should be updated or just the first one that matches filter.

  • [options.runValidators=false] «Boolean» if true, runs update validators on this command. Update validators validate the update operation against the model’s schema.

  • [options.setDefaultsOnInsert=false] «Boolean» true by default. If setDefaultsOnInsert and upsert are true, mongoose will apply the defaults specified in the model’s schema if a new document is created.

  • [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.overwrite=false] «Boolean» By default, if you don’t include any update operators in doc, Mongoose will wrap doc in $set for you. This prevents you from accidentally overwriting the document. This option tells Mongoose to skip adding $set.

  • [callback] «Function» params are (error, updateWriteOpResult)

  • [callback] «Function»

Returns:
  • «Query»

Updates one document in the database without returning it.

This function triggers the following middleware.

  • update()

This method is deprecated. See Deprecation Warnings for details.

Examples:

  1. MyModel.update({ age: { $gt: 18 } }, { oldEnough: true }, fn);
  2. const res = await MyModel.update({ name: 'Tobi' }, { ferret: true });
  3. res.n; // Number of documents that matched `{ name: 'Tobi' }`
  4. // Number of documents that were changed. If every doc matched already
  5. // had `ferret` set to `true`, `nModified` will be 0.
  6. res.nModified;

Valid options:

  • strict (boolean): overrides the schema-level strict option for this update
  • upsert (boolean): whether to create the doc if it doesn’t match (false)
  • writeConcern (object): sets the write concern for replica sets. Overrides the schema-level write concern
  • multi (boolean): whether multiple documents should be updated (false)
  • runValidators: if true, runs update validators on this command. Update validators validate the update operation against the model’s schema.
  • setDefaultsOnInsert (boolean): if this and upsert are true, mongoose will apply the defaults specified in the model’s schema if a new document is created. This option only works on MongoDB >= 2.4 because it relies on MongoDB’s $setOnInsert operator.
  • timestamps (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.
  • overwrite (boolean): disables update-only mode, allowing you to overwrite the doc (false)

All update values are cast to their appropriate SchemaTypes before being sent.

The callback function receives (err, rawResponse).

  • err is the error if any occurred
  • rawResponse is the full response from Mongo

Note:

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

Example:

  1. const query = { name: 'borne' };
  2. Model.update(query, { name: 'jason bourne' }, options, callback);
  3. // is sent as
  4. Model.update(query, { $set: { name: 'jason bourne' }}, options, function(err, res));
  5. // if overwrite option is false. If overwrite is true, sent without the $set wrapper.

This helps prevent accidentally overwriting all documents in your collection with { name: 'jason bourne' }.

Note:

Be careful to not use an existing model instance for the update clause (this won’t work and can cause weird behavior like infinite loops). Also, ensure that the update clause does not have an _id property, which causes Mongo to return a “Mod on _id not allowed” error.


Model.updateMany()

Parameters
  • filter «Object»
  • update «Object|Array»
  • [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.

  • [callback] «Function» function(error, res) {} where res has 5 properties: modifiedCount, matchedCount, acknowledged, upsertedId, and upsertedCount.

Returns:
  • «Query»

Same as update(), 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:

  1. const res = await Person.updateMany({ name: /Stark$/ }, { isDeleted: true });
  2. res.matchedCount; // Number of documents matched
  3. res.modifiedCount; // Number of documents modified
  4. res.acknowledged; // Boolean indicating everything went smoothly.
  5. res.upsertedId; // null or an id containing a document that had to be upserted.
  6. 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.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.

  • [callback] «Function» params are (error, writeOpResult)

Returns:
  • «Query»

Same as update(), except it does not support the multi or overwrite options.

  • MongoDB will update only the first document that matches filter regardless of the value of the multi option.
  • Use replaceOne() if you want to overwrite an entire document rather than using atomic operators like $set.

Example:

  1. const res = await Person.updateOne({ name: 'Jean-Luc Picard' }, { ship: 'USS Enterprise' });
  2. res.matchedCount; // Number of documents matched
  3. res.modifiedCount; // Number of documents modified
  4. res.acknowledged; // Boolean indicating everything went smoothly.
  5. res.upsertedId; // null or an id containing a document that had to be upserted.
  6. 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.validate()

Parameters
  • obj «Object»
  • pathsToValidate «Array»
  • [context] «Object»
  • [callback] «Function»
Returns:
  • «Promise,undefined»

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

Example:

  1. const Model = mongoose.model('Test', Schema({
  2. name: { type: String, required: true },
  3. age: { type: Number, required: true }
  4. });
  5. try {
  6. await Model.validate({ name: null }, ['name'])
  7. } catch (err) {
  8. err instanceof mongoose.Error.ValidationError; // true
  9. Object.keys(err.errors); // ['name']
  10. }

Model.watch()

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

  1. const doc = await Person.create({ name: 'Ned Stark' });
  2. const changeStream = Person.watch().on('change', change => console.log(change));
  3. // Will print from the above `console.log()`:
  4. // { _id: { _data: ... },
  5. // operationType: 'delete',
  6. // ns: { db: 'mydb', coll: 'Person' },
  7. // documentKey: { _id: 5a51b125c5500f5aa094c7bd } }
  8. 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:

  1. User.find({age: {$gte: 21, $lte: 65}}, callback);

we can instead write:

  1. User.where('age').gte(21).lte(65).exec(callback);

Since the Query class also supports where you can continue chaining

  1. User
  2. .where('age').gte(21).lte(65)
  3. .where('name', /^b/i)
  4. ... etc

increment()

Signal that we desire an increment of this documents version.

Example:

  1. Model.findById(id, function (err, doc) {
  2. doc.increment();
  3. doc.save(function (err) { .. })
  4. })

Query


Query()

Parameters
  • [options] «Object»
  • [model] «Object»
  • [conditions] «Object»
  • [collection] «Object» Mongoose collection

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

Example:

  1. const query = MyModel.find(); // `query` is an instance of `Query`
  2. query.setOptions({ lean : true });
  3. query.collection(MyModel.collection);
  4. query.where('age').gte(21).exec(callback);
  5. // You can instantiate a query directly. There is no need to do
  6. // this unless you're an advanced user with a very good reason to.
  7. const query = new mongoose.Query();

Query.prototype.$where()

Parameters
  • js «String|Function» javascript string or function
Returns:
  • «Query» this

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

Example

  1. query.$where('this.comments.length === 10 || this.name.length === 5')
  2. // or
  3. query.$where(function () {
  4. return this.comments.length === 10 || this.name.length === 5;
  5. })

NOTE:

Only use $where when you have a condition that cannot be met using other MongoDB operators like $lt. Be sure to read about all of its caveats before using.


Query.prototype.Symbol.asyncIterator()

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

Example

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

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

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


Query.prototype.all()

Parameters
  • [path] «String»
  • val «Array»

Specifies an $all query condition.

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

Example:

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

Query.prototype.allowDiskUse()

Parameters
  • [v] «Boolean» Enable/disable allowDiskUse. If called with 0 arguments, sets allowDiskUse: true
Returns:
  • «Query» this

Sets the allowDiskUse option, which allows the MongoDB server to use more than 100 MB for this query’s sort(). This option can let you work around QueryExceededMemoryLimitNoDiskUseAllowed errors from the MongoDB server.

Note that this option requires MongoDB server >= 4.4. Setting this option is a no-op for MongoDB 4.2 and earlier.

Calling query.allowDiskUse(v) is equivalent to query.setOptions({ allowDiskUse: v })

Example:

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

Query.prototype.and()

Parameters
  • array «Array» array of conditions
Returns:
  • «Query» this

Specifies arguments for a $and condition.

Example

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

Query.prototype.batchSize()

Parameters
  • val «Number»

Specifies the batchSize option.

Example

  1. query.batchSize(100)

Note

Cannot be used with distinct()


Query.prototype.box()

Parameters
  • val «Object»
  • Upper «[Array]» Right Coords
Returns:
  • «Query» this

Specifies a $box condition

Example

  1. const lowerLeft = [40.73083, -73.99756]
  2. const upperRight= [40.741404, -73.988135]
  3. query.where('loc').within().box(lowerLeft, upperRight)
  4. query.box({ ll : lowerLeft, ur : upperRight })

Query.prototype.cast()

Parameters
  • [model] «Model» the model to cast to. If not set, defaults to this.model

  • [obj] «Object»

Returns:
  • «Object»

Casts this query to the schema of model

Note

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


Query.prototype.catch()

Parameters
  • [reject] «Function»
Returns:
  • «Promise»

Executes the query returning a Promise which will be resolved with either the doc(s) or rejected with the error. Like .then(), but only takes a rejection handler.

More about Promise catch() in JavaScript.


Query.prototype.center()

DEPRECATED Alias for circle

Deprecated. Use circle instead.


Query.prototype.centerSphere()

Parameters
  • [path] «String»
  • val «Object»
Returns:
  • «Query» this

DEPRECATED Specifies a $centerSphere condition

Deprecated. Use circle instead.

Example

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

Query.prototype.circle()

Parameters
  • [path] «String»
  • area «Object»
Returns:
  • «Query» this

Specifies a $center or $centerSphere condition.

Example

  1. const area = { center: [50, 50], radius: 10, unique: true }
  2. query.where('loc').within().circle(area)
  3. // alternatively
  4. query.circle('loc', area);
  5. // spherical calculations
  6. const area = { center: [50, 50], radius: 10, unique: true, spherical: true }
  7. query.where('loc').within().circle(area)
  8. // alternatively
  9. query.circle('loc', area);

Query.prototype.clone()

Returns:
  • «Query» copy

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

Example:

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

Query.prototype.collation()

Parameters
  • value «Object»
Returns:
  • «Query» this

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


Query.prototype.comment()

Parameters
  • val «String»

Specifies the comment option.

Example

  1. query.comment('login query')

Note

Cannot be used with distinct()


Query.prototype.count()

Parameters
  • [filter] «Object» count documents that match this object

  • [callback] «Function» optional params are (error, count)

Returns:
  • «Query» this

Specifies this query as a count query.

This method is deprecated. If you want to count the number of documents in a collection, e.g. count({}), use the estimatedDocumentCount() function instead. Otherwise, use the countDocuments() function instead.

Passing a callback executes the query.

This function triggers the following middleware.

  • count()

Example:

  1. const countQuery = model.where({ 'color': 'black' }).count();
  2. query.count({ color: 'black' }).count(callback)
  3. query.count({ color: 'black' }, callback)
  4. query.where('color', 'black').count(function (err, count) {
  5. if (err) return handleError(err);
  6. console.log('there are %d kittens', count);
  7. })

Query.prototype.countDocuments()

Parameters
  • [filter] «Object» mongodb selector

  • [callback] «Function» optional params are (error, count)

Returns:
  • «Query» this

Specifies this query as a countDocuments() query. Behaves like count(), except it always does a full collection scan when passed an empty filter {}.

There are also minor differences in how countDocuments() handles $where and a couple geospatial operators. versus count().

Passing a callback executes the query.

This function triggers the following middleware.

  • countDocuments()

Example:

  1. const countQuery = model.where({ 'color': 'black' }).countDocuments();
  2. query.countDocuments({ color: 'black' }).count(callback);
  3. query.countDocuments({ color: 'black' }, callback);
  4. query.where('color', 'black').countDocuments(function(err, count) {
  5. if (err) return handleError(err);
  6. console.log('there are %d kittens', count);
  7. });

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:


Query.prototype.cursor()

Parameters
  • [options] «Object»
Returns:
  • «QueryCursor»

Returns a wrapper around a mongodb driver cursor. A QueryCursor exposes a Streams3 interface, as well as a .next() function.

The .cursor() function triggers pre find hooks, but not post find hooks.

Example

  1. // There are 2 ways to use a cursor. First, as a stream:
  2. Thing.
  3. find({ name: /^hello/ }).
  4. cursor().
  5. on('data', function(doc) { console.log(doc); }).
  6. on('end', function() { console.log('Done!'); });
  7. // Or you can use `.next()` to manually get the next doc in the stream.
  8. // `.next()` returns a promise, so you can use promises or callbacks.
  9. const cursor = Thing.find({ name: /^hello/ }).cursor();
  10. cursor.next(function(error, doc) {
  11. console.log(doc);
  12. });
  13. // Because `.next()` returns a promise, you can use co
  14. // to easily iterate through all documents without loading them
  15. // all into memory.
  16. const cursor = Thing.find({ name: /^hello/ }).cursor();
  17. for (let doc = await cursor.next(); doc != null; doc = await cursor.next()) {
  18. console.log(doc);
  19. }

Valid options

  • transform: optional function which accepts a mongoose document. The return value of the function will be emitted on data and returned by .next().

Query.prototype.deleteMany()

Parameters
  • [filter] «Object|Query» mongodb selector

  • [options] «Object» optional see Query.prototype.setOptions()

  • [callback] «Function» optional params are (error, mongooseDeleteResult)

Returns:
  • «Query» this

Declare and/or execute this query as a deleteMany() operation. Works like remove, except it deletes every document that matches filter in the collection, regardless of the value of single.

This function triggers deleteMany middleware.

Example

  1. await Character.deleteMany({ name: /Stark/, age: { $gte: 18 } });
  2. // Using callbacks:
  3. Character.deleteMany({ name: /Stark/, age: { $gte: 18 } }, callback);

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

  • ok: 1 if no errors occurred
  • deletedCount: the number of documents deleted
  • n: the number of documents deleted. Equal to deletedCount.

Example

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

Query.prototype.deleteOne()

Parameters
  • [filter] «Object|Query» mongodb selector

  • [options] «Object» optional see Query.prototype.setOptions()

  • [callback] «Function» optional params are (error, mongooseDeleteResult)

Returns:
  • «Query» this

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

This function triggers deleteOne middleware.

Example

  1. await Character.deleteOne({ name: 'Eddard Stark' });
  2. // Using callbacks:
  3. Character.deleteOne({ name: 'Eddard Stark' }, callback);

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

  • ok: 1 if no errors occurred
  • deletedCount: the number of documents deleted
  • n: the number of documents deleted. Equal to deletedCount.

Example

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

Query.prototype.distinct()

Parameters
  • [field] «String»
  • [filter] «Object|Query»
  • [callback] «Function» optional params are (error, arr)
Returns:
  • «Query» this

Declares or executes a distinct() operation.

Passing a callback executes the query.

This function does not trigger any middleware.

Example

  1. distinct(field, conditions, callback)
  2. distinct(field, conditions)
  3. distinct(field, callback)
  4. distinct(field)
  5. distinct(callback)
  6. distinct()

Query.prototype.elemMatch()

Parameters
  • path «String|Object|Function»
  • filter «Object|Function»
Returns:
  • «Query» this

Specifies an $elemMatch condition

Example

  1. query.elemMatch('comment', { author: 'autobot', votes: {$gte: 5}})
  2. query.where('comment').elemMatch({ author: 'autobot', votes: {$gte: 5}})
  3. query.elemMatch('comment', function (elem) {
  4. elem.where('author').equals('autobot');
  5. elem.where('votes').gte(5);
  6. })
  7. query.where('comment').elemMatch(function (elem) {
  8. elem.where({ author: 'autobot' });
  9. elem.where('votes').gte(5);
  10. })

Query.prototype.equals()

Parameters
  • val «Object»
Returns:
  • «Query» this

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

Example

  1. User.where('age').equals(49);
  2. // is the same as
  3. User.where('age', 49);

Query.prototype.error()

Parameters
  • err «Error|null» if set, exec() will fail fast before sending the query to MongoDB
Returns:
  • «Query» this

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

Example:

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

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

Example:

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

Query.prototype.estimatedDocumentCount()

Parameters
  • [options] «Object» passed transparently to the MongoDB driver

  • [callback] «Function» optional params are (error, count)

Returns:
  • «Query» this

Specifies this query as a estimatedDocumentCount() query. Faster than using countDocuments() for large collections because estimatedDocumentCount() uses collection metadata rather than scanning the entire collection.

estimatedDocumentCount() does not accept a filter. Model.find({ foo: bar }).estimatedDocumentCount() is equivalent to Model.find().estimatedDocumentCount()

This function triggers the following middleware.

  • estimatedDocumentCount()

Example:

  1. await Model.find().estimatedDocumentCount();

Query.prototype.exec()

Parameters
  • [operation] «String|Function»
  • [callback] «Function» optional params depend on the function being called
Returns:
  • «Promise»

Executes the query

Examples:

  1. const promise = query.exec();
  2. const promise = query.exec('update');
  3. query.exec(callback);
  4. query.exec('find', callback);

Query.prototype.exists()

Parameters
  • [path] «String»
  • val «Boolean»
Returns:
  • «Query» this

Specifies an $exists condition

Example

  1. // { name: { $exists: true }}
  2. Thing.where('name').exists()
  3. Thing.where('name').exists(true)
  4. Thing.find().exists('name')
  5. // { name: { $exists: false }}
  6. Thing.where('name').exists(false);
  7. Thing.find().exists('name', false);

Query.prototype.explain()

Parameters
  • [verbose] «String» The verbosity mode. Either ‘queryPlanner’, ‘executionStats’, or ‘allPlansExecution’. The default is ‘queryPlanner’
Returns:
  • «Query» this

Sets the explain option, which makes this query return detailed execution stats instead of the actual query result. This method is useful for determining what index your queries use.

Calling query.explain(v) is equivalent to query.setOptions({ explain: v })

Example:

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

Query.prototype.find()

Parameters
  • [filter] «Object|ObjectId» mongodb selector. If not specified, returns all documents.

  • [callback] «Function»

Returns:
  • «Query» this

Find all documents that match selector. The result will be an array of documents.

If there are too many documents in the result to fit in memory, use Query.prototype.cursor()

Example

  1. // Using async/await
  2. const arr = await Movie.find({ year: { $gte: 1980, $lte: 1989 } });
  3. // Using callbacks
  4. Movie.find({ year: { $gte: 1980, $lte: 1989 } }, function(err, arr) {});

Query.prototype.findOne()

Parameters
  • [filter] «Object» mongodb selector

  • [projection] «Object» optional fields to return

  • [options] «Object» see setOptions()

  • [callback] «Function» optional params are (error, document)

Returns:
  • «Query» this

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

Passing a callback executes the query. The result of the query is a single document.

  • Note: 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 Model.findById() instead.

This function triggers the following middleware.

  • findOne()

Example

  1. const query = Kitten.where({ color: 'white' });
  2. query.findOne(function (err, kitten) {
  3. if (err) return handleError(err);
  4. if (kitten) {
  5. // doc may be null if no document matched
  6. }
  7. });

Query.prototype.findOneAndDelete()

Parameters
  • [conditions] «Object»
  • [options] «Object»

  • [options.rawResult] «Boolean» if true, returns the raw result from the MongoDB driver

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

  • [options.strict] «Boolean|String» overwrites the schema’s strict mode option

  • [callback] «Function» optional params are (error, document)

Returns:
  • «Query» this

Issues a MongoDB findOneAndDelete command.

Finds a matching document, removes it, and passes the found document (if any) to the callback. Executes if callback is passed.

This function triggers the following middleware.

  • findOneAndDelete()

This function differs slightly from Model.findOneAndRemove() in that findOneAndRemove() becomes a MongoDB findAndModify() command, as opposed to a findOneAndDelete() command. For most mongoose use cases, this distinction is purely pedantic. You should use findOneAndDelete() unless you have a good reason not to.

Available options

  • sort: if multiple docs are found by the conditions, sets the sort order to choose which doc to update
  • maxTimeMS: puts a time limit on the query - requires mongodb >= 2.6.0
  • rawResult: if true, resolves to the raw result from the MongoDB driver

Callback Signature

  1. function(error, doc) {
  2. // error: any errors that occurred
  3. // doc: the document before updates are applied if `new: false`, or after updates if `new = true`
  4. }

Examples

  1. A.where().findOneAndDelete(conditions, options, callback) // executes
  2. A.where().findOneAndDelete(conditions, options) // return Query
  3. A.where().findOneAndDelete(conditions, callback) // executes
  4. A.where().findOneAndDelete(conditions) // returns Query
  5. A.where().findOneAndDelete(callback) // executes
  6. A.where().findOneAndDelete() // returns Query

Query.prototype.findOneAndRemove()

Parameters
  • [conditions] «Object»
  • [options] «Object»

  • [options.rawResult] «Boolean» if true, returns the raw result from the MongoDB driver

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

  • [options.strict] «Boolean|String» overwrites the schema’s strict mode option

  • [callback] «Function» optional params are (error, document)

Returns:
  • «Query» this

Issues a mongodb findAndModify remove command.

Finds a matching document, removes it, passing the found document (if any) to the callback. Executes if callback is passed.

This function triggers the following middleware.

  • findOneAndRemove()

Available options

  • sort: if multiple docs are found by the conditions, sets the sort order to choose which doc to update
  • maxTimeMS: puts a time limit on the query - requires mongodb >= 2.6.0
  • rawResult: if true, resolves to the raw result from the MongoDB driver

Callback Signature

  1. function(error, doc) {
  2. // error: any errors that occurred
  3. // doc: the document before updates are applied if `new: false`, or after updates if `new = true`
  4. }

Examples

  1. A.where().findOneAndRemove(conditions, options, callback) // executes
  2. A.where().findOneAndRemove(conditions, options) // return Query
  3. A.where().findOneAndRemove(conditions, callback) // executes
  4. A.where().findOneAndRemove(conditions) // returns Query
  5. A.where().findOneAndRemove(callback) // executes
  6. A.where().findOneAndRemove() // returns Query

Query.prototype.findOneAndReplace()

Parameters
  • [filter] «Object»
  • [replacement] «Object»
  • [options] «Object»

  • [options.rawResult] «Boolean» if true, returns the raw result from the MongoDB driver

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

  • [options.strict] «Boolean|String» overwrites the schema’s strict mode option

  • [options.new=false] «Boolean» By default, findOneAndUpdate() returns the document as it was before update was applied. If you set new: true, findOneAndUpdate() will instead give you the object after 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.returnOriginal=null] «Boolean» An alias for the new option. returnOriginal: false is equivalent to new: true.

  • [callback] «Function» optional params are (error, document)

Returns:
  • «Query» this

Issues a MongoDB findOneAndReplace command.

Finds a matching document, removes it, and passes the found document (if any) to the callback. Executes if callback is passed.

This function triggers the following middleware.

  • findOneAndReplace()

Available options

  • sort: if multiple docs are found by the conditions, sets the sort order to choose which doc to update
  • maxTimeMS: puts a time limit on the query - requires mongodb >= 2.6.0
  • rawResult: if true, resolves to the raw result from the MongoDB driver

Callback Signature

  1. function(error, doc) {
  2. // error: any errors that occurred
  3. // doc: the document before updates are applied if `new: false`, or after updates if `new = true`
  4. }

Examples

  1. A.where().findOneAndReplace(filter, replacement, options, callback); // executes
  2. A.where().findOneAndReplace(filter, replacement, options); // return Query
  3. A.where().findOneAndReplace(filter, replacement, callback); // executes
  4. A.where().findOneAndReplace(filter); // returns Query
  5. A.where().findOneAndReplace(callback); // executes
  6. A.where().findOneAndReplace(); // returns Query

Query.prototype.findOneAndUpdate()

Parameters
  • [filter] «Object|Query»
  • [doc] «Object»
  • [options] «Object»

  • [options.rawResult] «Boolean» if true, returns the raw result from the MongoDB driver

  • [options.strict] «Boolean|String» overwrites the schema’s strict mode option

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

  • [options.multipleCastError] «Boolean» by default, mongoose only returns the first error that occurred in casting the query. Turn on this option to aggregate all the cast errors.

  • [options.new=false] «Boolean» By default, findOneAndUpdate() returns the document as it was before update was applied. If you set new: true, findOneAndUpdate() will instead give you the object after 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.returnOriginal=null] «Boolean» An alias for the new option. returnOriginal: false is equivalent to new: true.

  • [callback] «Function» optional params are (error, doc), unless rawResult is used, in which case params are (error, writeOpResult)

Returns:
  • «Query» this

Issues a mongodb findAndModify update command.

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

This function triggers the following middleware.

  • findOneAndUpdate()

Available options

  • new: bool - if true, return the modified document rather than the original. defaults to false (changed in 4.0)
  • upsert: bool - creates the object if it doesn’t exist. defaults to false.
  • fields: {Object|String} - Field selection. Equivalent to .select(fields).findOneAndUpdate()
  • sort: if multiple docs are found by the conditions, sets the sort order to choose which doc to update
  • maxTimeMS: puts a time limit on the query - requires mongodb >= 2.6.0
  • runValidators: if true, runs update validators on this command. Update validators validate the update operation against the model’s schema.
  • setDefaultsOnInsert: true by default. If setDefaultsOnInsert and upsert are true, mongoose will apply the defaults specified in the model’s schema if a new document is created.
  • rawResult: if true, returns the raw result from the MongoDB driver

Callback Signature

  1. function(error, doc) {
  2. // error: any errors that occurred
  3. // doc: the document before updates are applied if `new: false`, or after updates if `new = true`
  4. }

Examples

  1. query.findOneAndUpdate(conditions, update, options, callback) // executes
  2. query.findOneAndUpdate(conditions, update, options) // returns Query
  3. query.findOneAndUpdate(conditions, update, callback) // executes
  4. query.findOneAndUpdate(conditions, update) // returns Query
  5. query.findOneAndUpdate(update, callback) // returns Query
  6. query.findOneAndUpdate(update) // returns Query
  7. query.findOneAndUpdate(callback) // executes
  8. query.findOneAndUpdate() // returns Query

Query.prototype.geometry()

Parameters
  • object «Object» Must contain a type property which is a String and a coordinates property which is an Array. See the examples.
Returns:
  • «Query» this

Specifies a $geometry condition

Example

  1. const polyA = [[[ 10, 20 ], [ 10, 40 ], [ 30, 40 ], [ 30, 20 ]]]
  2. query.where('loc').within().geometry({ type: 'Polygon', coordinates: polyA })
  3. // or
  4. const polyB = [[ 0, 0 ], [ 1, 1 ]]
  5. query.where('loc').within().geometry({ type: 'LineString', coordinates: polyB })
  6. // or
  7. const polyC = [ 0, 0 ]
  8. query.where('loc').within().geometry({ type: 'Point', coordinates: polyC })
  9. // or
  10. query.where('loc').intersects().geometry({ type: 'Point', coordinates: polyC })

The argument is assigned to the most recent path passed to where().

NOTE:

geometry() must come after either intersects() or within().

The object argument must contain type and coordinates properties. - type {String} - coordinates {Array}


Query.prototype.get()

Parameters
  • path «String|Object» path or object of key/value pairs to get
Returns:
  • «Query» this

For update operations, returns the value of a path in the update’s $set. Useful for writing getters/setters that can work with both update operations and save().

Example:

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

Query.prototype.getFilter()

Returns:
  • «Object» current query filter

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

Example:

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

Query.prototype.getOptions()

Returns:
  • «Object» the options

Gets query options.

Example:

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

Query.prototype.getPopulatedPaths()

Returns:
  • «Array» an array of strings representing populated paths

Gets a list of paths to be populated by this query

Example:

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

Example:

  1. // Deep populate
  2. const q = L1.find().populate({
  3. path: 'level2',
  4. populate: { path: 'level3' }
  5. });
  6. q.getPopulatedPaths(); // ['level2', 'level2.level3']

Query.prototype.getQuery()

Returns:
  • «Object» current query filter

Returns the current query filter. Equivalent to getFilter().

You should use getFilter() instead of getQuery() where possible. getQuery() will likely be deprecated in a future release.

Example:

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

Query.prototype.getUpdate()

Returns:
  • «Object» current update operations

Returns the current update operations as a JSON object.

Example:

  1. const query = new Query();
  2. query.update({}, { $set: { a: 5 } });
  3. query.getUpdate(); // { $set: { a: 5 } }

Query.prototype.gt()

Parameters
  • [path] «String»
  • val «Number»

Specifies a $gt query condition.

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

Example

  1. Thing.find().where('age').gt(21)
  2. // or
  3. Thing.find().gt('age', 21)

Query.prototype.gte()

Parameters
  • [path] «String»
  • val «Number»

Specifies a $gte query condition.

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


Query.prototype.hint()

Parameters
  • val «Object» a hint object
Returns:
  • «Query» this

Sets query hints.

Example

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

Note

Cannot be used with distinct()


Query.prototype.in()

Parameters
  • [path] «String»
  • val «Array»

Specifies an $in query condition.

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


Query.prototype.intersects()

Parameters
  • [arg] «Object»
Returns:
  • «Query» this

Declares an intersects query for geometry().

Example

  1. query.where('path').intersects().geometry({
  2. type: 'LineString'
  3. , coordinates: [[180.0, 11.0], [180, 9.0]]
  4. })
  5. query.where('path').intersects({
  6. type: 'LineString'
  7. , coordinates: [[180.0, 11.0], [180, 9.0]]
  8. })

NOTE:

MUST be used after where().

NOTE:

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


Query.prototype.j()

Parameters
  • val «boolean»
Returns:
  • «Query» this

Requests acknowledgement that this operation has been persisted to MongoDB’s on-disk journal.

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

  • deleteOne()
  • deleteMany()
  • findOneAndDelete()
  • findOneAndReplace()
  • findOneAndUpdate()
  • remove()
  • update()
  • updateOne()
  • updateMany()

Defaults to the schema’s writeConcern.j option

Example:

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

Query.prototype.lean()

Parameters
  • bool «Boolean|Object» defaults to true
Returns:
  • «Query» this

Sets the lean option.

Documents returned from queries with the lean option enabled are plain javascript objects, not Mongoose Documents. They have no save method, getters/setters, virtuals, or other Mongoose features.

Example:

  1. new Query().lean() // true
  2. new Query().lean(true)
  3. new Query().lean(false)
  4. const docs = await Model.find().lean();
  5. docs[0] instanceof mongoose.Document; // false

Lean is great for high-performance, read-only cases, especially when combined with cursors.

If you need virtuals, getters/setters, or defaults with lean(), you need to use a plugin. See:


Query.prototype.limit()

Parameters
  • val «Number»

Specifies the maximum number of documents the query will return.

Example

  1. query.limit(20)

Note

Cannot be used with distinct()


Query.prototype.lt()

Parameters
  • [path] «String»
  • val «Number»

Specifies a $lt query condition.

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


Query.prototype.lte()

Parameters
  • [path] «String»
  • val «Number»

Specifies a $lte query condition.

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


Query.prototype.map()

Parameters
  • fn «Function» function to run to transform the query result
Returns:
  • «Query» this

Runs a function fn and treats the return value of fn as the new value for the query to resolve to.

Any functions you pass to map() will run after any post hooks.

Example:

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

Query.prototype.maxDistance()

Parameters
  • [path] «String»
  • val «Number»

Specifies a maxDistance query condition.

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


Query.prototype.maxScan()

Parameters
  • val «Number»

Specifies the maxScan option.

Example

  1. query.maxScan(100)

Note

Cannot be used with distinct()


Query.prototype.maxTimeMS()

Parameters
  • [ms] «Number» The number of milliseconds
Returns:
  • «Query» this

Sets the maxTimeMS option. This will tell the MongoDB server to abort if the query or write op has been running for more than ms milliseconds.

Calling query.maxTimeMS(v) is equivalent to query.setOptions({ maxTimeMS: v })

Example:

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

Query.prototype.maxscan()

DEPRECATED Alias of maxScan


Query.prototype.merge()

Parameters
  • source «Query|Object»
Returns:
  • «Query» this

Merges another Query or conditions object into this one.

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


Query.prototype.mod()

Parameters
  • [path] «String»
  • val «Array» must be of length 2, first element is divisor, 2nd element is remainder.
Returns:
  • «Query» this

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

Example

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

Query.prototype.model

Type:
  • «property»

The model this query is associated with.

Example:

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

Query.prototype.mongooseOptions()

Parameters
  • options «Object» if specified, overwrites the current options
Returns:
  • «Object» the options

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

  • populate: an array representing what paths will be populated. Should have one entry for each call to Query.prototype.populate()
  • lean: if truthy, Mongoose will not hydrate any documents that are returned from this query. See Query.prototype.lean() for more information.
  • strict: controls how Mongoose handles keys that aren’t in the schema for updates. This option is true by default, which means Mongoose will silently strip any paths in the update that aren’t in the schema. See the strict mode docs for more information.
  • strictQuery: controls how Mongoose handles keys that aren’t in the schema for the query filter. This option is false by default for backwards compatibility, which means Mongoose will allow Model.find({ foo: 'bar' }) even if foo is not in the schema. See the strictQuery docs for more information.
  • nearSphere: use $nearSphere instead of near(). See the Query.prototype.nearSphere() docs

Mongoose maintains a separate object for internal options because Mongoose sends Query.prototype.options to the MongoDB server, and the above options are not relevant for the MongoDB server.


Query.prototype.ne()

Parameters
  • [path] «String»
  • val «any»

Specifies a $ne query condition.

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


Query.prototype.near()

Parameters
  • [path] «String»
  • val «Object»
Returns:
  • «Query» this

Specifies a $near or $nearSphere condition

These operators return documents sorted by distance.

Example

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

Query.prototype.nearSphere()

DEPRECATED Specifies a $nearSphere condition

Example

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

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

Example

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

Query.prototype.nin()

Parameters
  • [path] «String»
  • val «Array»

Specifies an $nin query condition.

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


Query.prototype.nor()

Parameters
  • array «Array» array of conditions
Returns:
  • «Query» this

Specifies arguments for a $nor condition.

Example

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

Query.prototype.or()

Parameters
  • array «Array» array of conditions
Returns:
  • «Query» this

Specifies arguments for an $or condition.

Example

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

Query.prototype.orFail()

Parameters
  • [err] «Function|Error» optional error to throw if no docs match filter. If not specified, orFail() will throw a DocumentNotFoundError
Returns:
  • «Query» this

Make this query throw an error if no documents match the given filter. This is handy for integrating with async/await, because orFail() saves you an extra if statement to check if no document was found.

Example:

  1. // Throws if no doc returned
  2. await Model.findOne({ foo: 'bar' }).orFail();
  3. // Throws if no document was updated
  4. await Model.updateOne({ foo: 'bar' }, { name: 'test' }).orFail();
  5. // Throws "No docs found!" error if no docs match `{ foo: 'bar' }`
  6. await Model.find({ foo: 'bar' }).orFail(new Error('No docs found!'));
  7. // Throws "Not found" error if no document was found
  8. await Model.findOneAndUpdate({ foo: 'bar' }, { name: 'test' }).
  9. orFail(() => Error('Not found'));

Query.prototype.polygon()

Parameters
  • [path] «String|Array»

  • [coordinatePairs…] «Array|Object»

Returns:
  • «Query» this

Specifies a $polygon condition

Example

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

Query.prototype.populate()

Parameters
  • path «Object|String» either the path to populate or an object specifying all parameters

  • [select] «Object|String» Field selection for the population query

  • [model] «Model» The model you wish to use for population. If not specified, populate will look up the model by the name in the Schema’s ref field.

  • [match] «Object» Conditions for the population query

  • [options] «Object» Options for the population query (sort, etc)

  • [options.path=null] «String» The path to populate.

  • [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.transform=null] «Function» Function that Mongoose will call on every populated document that allows you to transform the populated document.

  • [options.options=null] «Object» Additional options like limit and lean.

Returns:
  • «Query» this

Specifies paths which should be populated with other documents.

Example:

  1. let book = await Book.findOne().populate('authors');
  2. book.title; // 'Node.js in Action'
  3. book.authors[0].name; // 'TJ Holowaychuk'
  4. book.authors[1].name; // 'Nathan Rajlich'
  5. let books = await Book.find().populate({
  6. path: 'authors',
  7. // `match` and `sort` apply to the Author model,
  8. // not the Book model. These options do not affect
  9. // which documents are in `books`, just the order and
  10. // contents of each book document's `authors`.
  11. match: { name: new RegExp('.*h.*', 'i') },
  12. sort: { name: -1 }
  13. });
  14. books[0].title; // 'Node.js in Action'
  15. // Each book's `authors` are sorted by name, descending.
  16. books[0].authors[0].name; // 'TJ Holowaychuk'
  17. books[0].authors[1].name; // 'Marc Harter'
  18. books[1].title; // 'Professional AngularJS'
  19. // Empty array, no authors' name has the letter 'h'
  20. books[1].authors; // []

Paths are populated after the query executes and a response is received. A separate query is then executed for each path specified for population. After a response for each query has also been returned, the results are passed to the callback.


Query.prototype.post()

Parameters
  • fn «Function»
Returns:
  • «Promise»

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

Example:

  1. const q1 = Question.find({ answer: 42 });
  2. q1.post(function middleware() {
  3. console.log(this.getFilter());
  4. });
  5. await q1.exec(); // Prints "{ answer: 42 }"
  6. // Doesn't print anything, because `middleware()` is only
  7. // registered on `q1`.
  8. await Question.find({ answer: 42 });

Query.prototype.pre()

Parameters
  • fn «Function»
Returns:
  • «Promise»

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

Example:

  1. const q1 = Question.find({ answer: 42 });
  2. q1.pre(function middleware() {
  3. console.log(this.getFilter());
  4. });
  5. await q1.exec(); // Prints "{ answer: 42 }"
  6. // Doesn't print anything, because `middleware()` is only
  7. // registered on `q1`.
  8. await Question.find({ answer: 42 });

Query.prototype.projection()

Parameters
  • arg «Object|null»
Returns:
  • «Object» the current projection

Get/set the current projection (AKA fields). Pass null to remove the current projection.

Unlike projection(), the select() function modifies the current projection in place. This function overwrites the existing projection.

Example:

  1. const q = Model.find();
  2. q.projection(); // null
  3. q.select('a b');
  4. q.projection(); // { a: 1, b: 1 }
  5. q.projection({ c: 1 });
  6. q.projection(); // { c: 1 }
  7. q.projection(null);
  8. q.projection(); // null

Query.prototype.read()

Parameters
  • pref «String» one of the listed preference options or aliases

  • [tags] «Array» optional tags for this query

Returns:
  • «Query» this

Determines the MongoDB nodes from which to read.

Preferences:

  1. primary - (default) Read from primary only. Operations will produce an error if primary is unavailable. Cannot be combined with tags.
  2. secondary Read from secondary if available, otherwise error.
  3. primaryPreferred Read from primary if available, otherwise a secondary.
  4. secondaryPreferred Read from a secondary if available, otherwise read from the primary.
  5. nearest All operations read from among the nearest candidates, but unlike other modes, this option will include both the primary and all secondaries in the random selection.

Aliases

  1. p primary
  2. pp primaryPreferred
  3. s secondary
  4. sp secondaryPreferred
  5. n nearest

Example:

  1. new Query().read('primary')
  2. new Query().read('p') // same as primary
  3. new Query().read('primaryPreferred')
  4. new Query().read('pp') // same as primaryPreferred
  5. new Query().read('secondary')
  6. new Query().read('s') // same as secondary
  7. new Query().read('secondaryPreferred')
  8. new Query().read('sp') // same as secondaryPreferred
  9. new Query().read('nearest')
  10. new Query().read('n') // same as nearest
  11. // read from secondaries with matching tags
  12. new Query().read('s', [{ dc:'sf', s: 1 },{ dc:'ma', s: 2 }])

Read more about how to use read preferences here and here.


Query.prototype.readConcern()

Parameters
  • level «String» one of the listed read concern level or their aliases
Returns:
  • «Query» this

Sets the readConcern option for the query.

Example:

  1. new Query().readConcern('local')
  2. new Query().readConcern('l') // same as local
  3. new Query().readConcern('available')
  4. new Query().readConcern('a') // same as available
  5. new Query().readConcern('majority')
  6. new Query().readConcern('m') // same as majority
  7. new Query().readConcern('linearizable')
  8. new Query().readConcern('lz') // same as linearizable
  9. new Query().readConcern('snapshot')
  10. new Query().readConcern('s') // same as snapshot

Read Concern Level:

  1. local MongoDB 3.2+ The query returns from the instance with no guarantee guarantee that the data has been written to a majority of the replica set members (i.e. may be rolled back).
  2. available MongoDB 3.6+ The query returns from the instance with no guarantee guarantee that the data has been written to a majority of the replica set members (i.e. may be rolled back).
  3. majority MongoDB 3.2+ The query returns the data that has been acknowledged by a majority of the replica set members. The documents returned by the read operation are durable, even in the event of failure.
  4. linearizable MongoDB 3.4+ The query returns data that reflects all successful majority-acknowledged writes that completed prior to the start of the read operation. The query may wait for concurrently executing writes to propagate to a majority of replica set members before returning results.
  5. snapshot MongoDB 4.0+ Only available for operations within multi-document transactions. Upon transaction commit with write concern "majority", the transaction operations are guaranteed to have read from a snapshot of majority-committed data.

Aliases

  1. l local
  2. a available
  3. m majority
  4. lz linearizable
  5. s snapshot

Read more about how to use read concern here.


Query.prototype.regex()

Parameters
  • [path] «String»
  • val «String|RegExp»

Specifies a $regex query condition.

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


Query.prototype.remove()

Parameters
  • [filter] «Object|Query» mongodb selector

  • [callback] «Function» optional params are (error, mongooseDeleteResult)

Returns:
  • «Query» this

Declare and/or execute this query as a remove() operation. remove() is deprecated, you should use deleteOne() or deleteMany() instead.

This function does not trigger any middleware

Example

  1. Character.remove({ name: /Stark/ }, callback);

This function calls the MongoDB driver’s Collection#remove() function. The returned promise resolves to an object that contains 3 properties:

  • ok: 1 if no errors occurred
  • deletedCount: the number of documents deleted
  • n: the number of documents deleted. Equal to deletedCount.

Example

  1. const res = await Character.remove({ name: /Stark/ });
  2. // Number of docs deleted
  3. res.deletedCount;

Note

Calling remove() creates a Mongoose query, and a query does not execute until you either pass a callback, call Query#then(), or call Query#exec().

  1. // not executed
  2. const query = Character.remove({ name: /Stark/ });
  3. // executed
  4. Character.remove({ name: /Stark/ }, callback);
  5. Character.remove({ name: /Stark/ }).remove(callback);
  6. // executed without a callback
  7. Character.exec();

Query.prototype.replaceOne()

Parameters
  • [filter] «Object»
  • [doc] «Object» the update command

  • [options] «Object»

  • [options.multipleCastError] «Boolean» by default, mongoose only returns the first error that occurred in casting the query. Turn on this option to aggregate all the cast errors.

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

  • [callback] «Function» params are (error, writeOpResult)

Returns:
  • «Query» this

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

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

Example:

  1. const res = await Person.replaceOne({ _id: 24601 }, { name: 'Jean Valjean' });
  2. res.n; // Number of documents matched
  3. res.nModified; // Number of documents modified

This function triggers the following middleware.

  • replaceOne()

Query.prototype.select()

Parameters
  • arg «Object|String|Array<String>»
Returns:
  • «Query» this

Specifies which document fields to include or exclude (also known as the query “projection”)

When using string syntax, prefixing a path with - will flag that path as excluded. When a path does not have the - prefix, it is included. Lastly, if a path is prefixed with +, it forces inclusion of the path, which is useful for paths excluded at the schema level.

A projection must be either inclusive or exclusive. In other words, you must either list the fields to include (which excludes all others), or list the fields to exclude (which implies all other fields are included). The _id field is the only exception because MongoDB includes it by default.

Example

  1. // include a and b, exclude other fields
  2. query.select('a b');
  3. // Equivalent syntaxes:
  4. query.select(['a', 'b']);
  5. query.select({ a: 1, b: 1 });
  6. // exclude c and d, include other fields
  7. query.select('-c -d');
  8. // Use `+` to override schema-level `select: false` without making the
  9. // projection inclusive.
  10. const schema = new Schema({
  11. foo: { type: String, select: false },
  12. bar: String
  13. });
  14. // ...
  15. query.select('+foo'); // Override foo's `select: false` without excluding `bar`
  16. // or you may use object notation, useful when
  17. // you have keys already prefixed with a "-"
  18. query.select({ a: 1, b: 1 });
  19. query.select({ c: 0, d: 0 });

Query.prototype.selected()

Returns:
  • «Boolean»

Determines if field selection has been made.


Query.prototype.selectedExclusively()

Returns:
  • «Boolean»

Determines if exclusive field selection has been made.

  1. query.selectedExclusively() // false
  2. query.select('-name')
  3. query.selectedExclusively() // true
  4. query.selectedInclusively() // false

Query.prototype.selectedInclusively()

Returns:
  • «Boolean»

Determines if inclusive field selection has been made.

  1. query.selectedInclusively() // false
  2. query.select('name')
  3. query.selectedInclusively() // true

Query.prototype.session()

Parameters
  • [session] «ClientSession» from await conn.startSession()
Returns:
  • «Query» this

Sets the MongoDB session associated with this query. Sessions are how you mark a query as part of a transaction.

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

Example:

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

Query.prototype.set()

Parameters
  • path «String|Object» path or object of key/value pairs to set

  • [val] «Any» the value to set

Returns:
  • «Query» this

Adds a $set to this query’s update without changing the operation. This is useful for query middleware so you can add an update regardless of whether you use updateOne(), updateMany(), findOneAndUpdate(), etc.

Example:

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

Query.prototype.setOptions()

Parameters
  • options «Object»
Returns:
  • «Query» this

Sets query options. Some options only make sense for certain operations.

Options:

The following options are only for find():

The following options are only for write operations: update(), updateOne(), updateMany(), replaceOne(), findOneAndUpdate(), and findByIdAndUpdate():

  • upsert
  • writeConcern
  • timestamps: If timestamps is set in the schema, set this option to false to skip timestamps for that particular update. Has no effect if timestamps is not enabled in the schema options.
  • omitUndefined: delete any properties whose value is undefined when casting an update. In other words, if this is set, Mongoose will delete baz from the update in Model.updateOne({}, { foo: 'bar', baz: undefined }) before sending the update to the server.
  • overwriteDiscriminatorKey: allow setting the discriminator key in the update. Will use the correct discriminator schema if the update changes the discriminator key.

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

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

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

  • rawResult

The following options are for all operations


Query.prototype.setQuery()

Parameters
  • new «Object» query conditions
Returns:
  • «undefined»

Sets the query conditions to the provided JSON object.

Example:

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

Query.prototype.setUpdate()

Parameters
  • new «Object» update operation
Returns:
  • «undefined»

Sets the current update operation to new value.

Example:

  1. const query = new Query();
  2. query.update({}, { $set: { a: 5 } });
  3. query.setUpdate({ $set: { b: 6 } });
  4. query.getUpdate(); // { $set: { b: 6 } }

Query.prototype.size()

Parameters
  • [path] «String»
  • val «Number»

Specifies a $size query condition.

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

Example

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

Query.prototype.skip()

Parameters
  • val «Number»

Specifies the number of documents to skip.

Example

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

Note

Cannot be used with distinct()


Query.prototype.slaveOk()

Parameters
  • v «Boolean» defaults to true
Returns:
  • «Query» this

DEPRECATED Sets the slaveOk option.

Deprecated in MongoDB 2.2 in favor of read preferences.

Example:

  1. query.slaveOk() // true
  2. query.slaveOk(true)
  3. query.slaveOk(false)

Query.prototype.slice()

Parameters
  • [path] «String»
  • val «Number» number/range of elements to slice
Returns:
  • «Query» this

Specifies a $slice projection for an array.

Example

  1. query.slice('comments', 5)
  2. query.slice('comments', -5)
  3. query.slice('comments', [10, 5])
  4. query.where('comments').slice(5)
  5. query.where('comments').slice([-10, 5])

Query.prototype.snapshot()

Returns:
  • «Query» this

Specifies this query as a snapshot query.

Example

  1. query.snapshot() // true
  2. query.snapshot(true)
  3. query.snapshot(false)

Note

Cannot be used with distinct()


Query.prototype.sort()

Parameters
  • arg «Object|String»
Returns:
  • «Query» this

Sets the sort order

If an object is passed, values allowed are asc, desc, ascending, descending, 1, and -1.

If a string is passed, it must be a space delimited list of path names. The sort order of each path is ascending unless the path name is prefixed with - which will be treated as descending.

Example

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

Note

Cannot be used with distinct()


Query.prototype.tailable()

Parameters
  • bool «Boolean» defaults to true

  • [opts] «Object» options to set

  • [opts.numberOfRetries] «Number» if cursor is exhausted, retry this many times before giving up

  • [opts.tailableRetryInterval] «Number» if cursor is exhausted, wait this many milliseconds before retrying

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

Example

  1. query.tailable() // true
  2. query.tailable(true)
  3. query.tailable(false)

Note

Cannot be used with distinct()


Query.prototype.then()

Parameters
  • [resolve] «Function»
  • [reject] «Function»
Returns:
  • «Promise»

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

More about then() in JavaScript.


Query.prototype.toConstructor()

Returns:
  • «Query» subclass-of-Query

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

Example

  1. // Create a query for adventure movies and read from the primary
  2. // node in the replica-set unless it is down, in which case we'll
  3. // read from a secondary node.
  4. const query = Movie.find({ tags: 'adventure' }).read('primaryPreferred');
  5. // create a custom Query constructor based off these settings
  6. const Adventure = query.toConstructor();
  7. // Adventure is now a subclass of mongoose.Query and works the same way but with the
  8. // default query parameters and options set.
  9. Adventure().exec(callback)
  10. // further narrow down our query results while still using the previous settings
  11. Adventure().where({ name: /^Life/ }).exec(callback);
  12. // since Adventure is a stand-alone constructor we can also add our own
  13. // helper methods and getters without impacting global queries
  14. Adventure.prototype.startsWith = function (prefix) {
  15. this.where({ name: new RegExp('^' + prefix) })
  16. return this;
  17. }
  18. Object.defineProperty(Adventure.prototype, 'highlyRated', {
  19. get: function () {
  20. this.where({ rating: { $gt: 4.5 }});
  21. return this;
  22. }
  23. })
  24. Adventure().highlyRated.startsWith('Life').exec(callback)

Query.prototype.update()

Parameters
  • [filter] «Object»
  • [doc] «Object» the update command

  • [options] «Object»

  • [options.multipleCastError] «Boolean» by default, mongoose only returns the first error that occurred in casting the query. Turn on this option to aggregate all the cast errors.

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

  • [callback] «Function» params are (error, writeOpResult)

Returns:
  • «Query» this

Declare and/or execute this query as an update() operation.

All paths passed that are not atomic operations will become $set ops.

This function triggers the following middleware.

  • update()

Example

  1. Model.where({ _id: id }).update({ title: 'words' })
  2. // becomes
  3. Model.where({ _id: id }).update({ $set: { title: 'words' }})

Valid options:

  • upsert (boolean) whether to create the doc if it doesn’t match (false)
  • multi (boolean) whether multiple documents should be updated (false)
  • runValidators (boolean) if true, runs update validators on this command. Update validators validate the update operation against the model’s schema.
  • setDefaultsOnInsert (boolean) true by default. If setDefaultsOnInsert and upsert are true, mongoose will apply the defaults specified in the model’s schema if a new document is created.
  • strict (boolean) overrides the strict option for this update
  • read
  • writeConcern

Note

Passing an empty object {} as the doc will result in a no-op. The update operation will be ignored and the callback executed without sending the command to MongoDB.

Note

The operation is only executed when a callback is passed. To force execution without a callback, we must first call update() and then execute it by using the exec() method.

  1. const q = Model.where({ _id: id });
  2. q.update({ $set: { name: 'bob' }}).update(); // not executed
  3. q.update({ $set: { name: 'bob' }}).exec(); // executed
  4. // keys that are not [atomic](https://docs.mongodb.com/manual/tutorial/model-data-for-atomic-operations/#pattern) ops become `$set`.
  5. // this executes the same command as the previous example.
  6. q.update({ name: 'bob' }).exec();
  7. // multi updates
  8. Model.where()
  9. .update({ name: /^match/ }, { $set: { arr: [] }}, { multi: true }, callback)
  10. // more multi updates
  11. Model.where()
  12. .setOptions({ multi: true })
  13. .update({ $set: { arr: [] }}, callback)
  14. // single update by default
  15. Model.where({ email: 'address@example.com' })
  16. .update({ $inc: { counter: 1 }}, callback)

API summary

  1. update(filter, doc, options, cb) // executes
  2. update(filter, doc, options)
  3. update(filter, doc, cb) // executes
  4. update(filter, doc)
  5. update(doc, cb) // executes
  6. update(doc)
  7. update(cb) // executes
  8. update(true) // executes
  9. update()

Query.prototype.updateMany()

Parameters
  • [filter] «Object»
  • [update] «Object|Array» the update command

  • [options] «Object»

  • [options.multipleCastError] «Boolean» by default, mongoose only returns the first error that occurred in casting the query. Turn on this option to aggregate all the cast errors.

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

  • [callback] «Function» params are (error, writeOpResult)

Returns:
  • «Query» this

Declare and/or execute this query as an updateMany() operation. Same as update(), 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:

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

This function triggers the following middleware.

  • updateMany()

Query.prototype.updateOne()

Parameters
  • [filter] «Object»
  • [update] «Object|Array» the update command

  • [options] «Object»

  • [options.multipleCastError] «Boolean» by default, mongoose only returns the first error that occurred in casting the query. Turn on this option to aggregate all the cast errors.

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

  • [callback] «Function» params are (error, writeOpResult)

Returns:
  • «Query» this

Declare and/or execute this query as an updateOne() operation. Same as update(), except it does not support the multi option.

  • MongoDB will update only the first document that matches filter regardless of the value of the multi option.
  • Use replaceOne() if you want to overwrite an entire document rather than using atomic operators like $set.

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

Example:

  1. const res = await Person.updateOne({ name: 'Jean-Luc Picard' }, { ship: 'USS Enterprise' });
  2. res.n; // Number of documents matched
  3. res.nModified; // Number of documents modified

This function triggers the following middleware.

  • updateOne()

Query.prototype.use$geoWithin

Type:
  • «property»

Flag to opt out of using $geoWithin.

  1. mongoose.Query.use$geoWithin = false;

MongoDB 2.4 deprecated the use of $within, replacing it with $geoWithin. Mongoose uses $geoWithin by default (which is 100% backward compatible with $within). If you are running an older version of MongoDB, set this flag to false so your within() queries continue to work.


Query.prototype.w()

Parameters
  • val «String|number» 0 for fire-and-forget, 1 for acknowledged by one server, ‘majority’ for majority of the replica set, or any of the more advanced options.
Returns:
  • «Query» this

Sets the specified number of mongod servers, or tag set of mongod servers, that must acknowledge this write before this write is considered successful.

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

  • deleteOne()
  • deleteMany()
  • findOneAndDelete()
  • findOneAndReplace()
  • findOneAndUpdate()
  • remove()
  • update()
  • updateOne()
  • updateMany()

Defaults to the schema’s writeConcern.w option

Example:

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

Query.prototype.where()

Parameters
  • [path] «String|Object»
  • [val] «any»
Returns:
  • «Query» this

Specifies a path for use with chaining.

Example

  1. // instead of writing:
  2. User.find({age: {$gte: 21, $lte: 65}}, callback);
  3. // we can instead write:
  4. User.where('age').gte(21).lte(65);
  5. // passing query conditions is permitted
  6. User.find().where({ name: 'vonderful' })
  7. // chaining
  8. User
  9. .where('age').gte(21).lte(65)
  10. .where('name', /^vonderful/i)
  11. .where('friends').slice(10)
  12. .exec(callback)

Query.prototype.within()

Returns:
  • «Query» this

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

Example

  1. query.where(path).within().box()
  2. query.where(path).within().circle()
  3. query.where(path).within().geometry()
  4. query.where('loc').within({ center: [50,50], radius: 10, unique: true, spherical: true });
  5. query.where('loc').within({ box: [[40.73, -73.9], [40.7, -73.988]] });
  6. query.where('loc').within({ polygon: [[],[],[],[]] });
  7. query.where('loc').within([], [], []) // polygon
  8. query.where('loc').within([], []) // box
  9. query.where('loc').within({ type: 'LineString', coordinates: [...] }); // geometry

MUST be used after where().

NOTE:

As of Mongoose 3.7, $geoWithin is always used for queries. To change this behavior, see Query.use$geoWithin.

NOTE:

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


Query.prototype.writeConcern()

Parameters
  • writeConcern «Object» the write concern value to set
Returns:
  • «Query» this

Sets the 3 write concern parameters for this query

  • w: Sets the specified number of mongod servers, or tag set of mongod servers, that must acknowledge this write before this write is considered successful.
  • j: Boolean, set to true to request acknowledgement that this operation has been persisted to MongoDB’s on-disk journal.
  • wtimeout: If w > 1, the maximum amount of time to wait for this write to propagate through the replica set before this operation fails. The default is 0, which means no timeout.

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

  • deleteOne()
  • deleteMany()
  • findOneAndDelete()
  • findOneAndReplace()
  • findOneAndUpdate()
  • remove()
  • update()
  • updateOne()
  • updateMany()

Defaults to the schema’s writeConcern option

Example:

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

Query.prototype.wtimeout()

Parameters
  • ms «number» number of milliseconds to wait
Returns:
  • «Query» this

If w > 1, the maximum amount of time to wait for this write to propagate through the replica set before this operation fails. The default is 0, which means no timeout.

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

  • deleteOne()
  • deleteMany()
  • findOneAndDelete()
  • findOneAndReplace()
  • findOneAndUpdate()
  • remove()
  • update()
  • updateOne()
  • updateMany()

Defaults to the schema’s writeConcern.wtimeout option

Example:

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

QueryCursor


Query.prototype.Symbol.asyncIterator()

Returns an asyncIterator for use with for/await/of loops. You do not need to call this function explicitly, the JavaScript runtime will call it for you.

Example

  1. // Works without using `cursor()`
  2. for await (const doc of Model.find([{ $sort: { name: 1 } }])) {
  3. console.log(doc.name);
  4. }
  5. // Can also use `cursor()`
  6. for await (const doc of Model.find([{ $sort: { name: 1 } }]).cursor()) {
  7. console.log(doc.name);
  8. }

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

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


QueryCursor()

Parameters
  • query «Query»
  • options «Object» query options passed to .find()

A QueryCursor is a concurrency primitive for processing query results one document at a time. A QueryCursor fulfills the Node.js streams3 API, in addition to several other mechanisms for loading documents from MongoDB one at a time.

QueryCursors execute the model’s pre find hooks before loading any documents from MongoDB, and the model’s post find hooks after loading each document.

Unless you’re an advanced user, do not instantiate this class directly. Use Query#cursor() instead.


QueryCursor.prototype.addCursorFlag()

Parameters
  • flag «String»
  • value «Boolean»
Returns:
  • «AggregationCursor» this

Adds a cursor flag. Useful for setting the noCursorTimeout and tailable flags.


QueryCursor.prototype.close()

Parameters
  • callback «Function»
Returns:
  • «Promise»

Marks this cursor as closed. Will stop streaming and subsequent calls to next() will error.


QueryCursor.prototype.eachAsync()

Parameters
  • fn «Function»
  • [options] «Object»

  • [options.parallel] «Number» the number of promises to execute in parallel. Defaults to 1.

  • [callback] «Function» executed when all docs have been processed

Returns:
  • «Promise»

Execute fn for every document in the cursor. If fn returns a promise, will wait for the promise to resolve before iterating on to the next one. Returns a promise that resolves when done.

Example

  1. // Iterate over documents asynchronously
  2. Thing.
  3. find({ name: /^hello/ }).
  4. cursor().
  5. eachAsync(async function (doc, i) {
  6. doc.foo = doc.bar + i;
  7. await doc.save();
  8. })

QueryCursor.prototype.map()

Parameters
  • fn «Function»
Returns:
  • «QueryCursor»

Registers a transform function which subsequently maps documents retrieved via the streams interface or .next()

Example

  1. // Map documents returned by `data` events
  2. Thing.
  3. find({ name: /^hello/ }).
  4. cursor().
  5. map(function (doc) {
  6. doc.foo = "bar";
  7. return doc;
  8. })
  9. on('data', function(doc) { console.log(doc.foo); });
  10. // Or map documents returned by `.next()`
  11. const cursor = Thing.find({ name: /^hello/ }).
  12. cursor().
  13. map(function (doc) {
  14. doc.foo = "bar";
  15. return doc;
  16. });
  17. cursor.next(function(error, doc) {
  18. console.log(doc.foo);
  19. });

QueryCursor.prototype.next()

Parameters
  • callback «Function»
Returns:
  • «Promise»

Get the next document from this cursor. Will return null when there are no documents left.


function Object() { [native code] }.prototype.options

Type:
  • «property»

The options passed in to the QueryCursor constructor.


Aggregate


Aggregate()

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

  • [model] «Model» the model to use with this aggregate.

Aggregate constructor used for building aggregation pipelines. Do not instantiate this class directly, use Model.aggregate() instead.

Example:

  1. const aggregate = Model.aggregate([
  2. { $project: { a: 1, b: 1 } },
  3. { $skip: 5 }
  4. ]);
  5. Model.
  6. aggregate([{ $match: { age: { $gte: 21 }}}]).
  7. unwind('tags').
  8. exec(callback);

Note:

  • The documents returned are plain javascript objects, not mongoose documents (since any shape of document can be returned).
  • Mongoose does not cast pipeline stages. The below will not work unless _id is a string in the database
  1. new Aggregate([{ $match: { _id: '00000000000000000000000a' } }]);
  2. // Do this instead to cast to an ObjectId
  3. new Aggregate([{ $match: { _id: mongoose.Types.ObjectId('00000000000000000000000a') } }]);

Aggregate.prototype.Symbol.asyncIterator()

Returns an asyncIterator for use with [for/await/of loops](https://thecodebarbarian.com/getting-started-with-async-iterators-in-node-js You do not need to call this function explicitly, the JavaScript runtime will call it for you.

Example

  1. const agg = Model.aggregate([{ $match: { age: { $gte: 25 } } }]);
  2. for await (const doc of agg) {
  3. console.log(doc.name);
  4. }

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

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


Aggregate.prototype.addFields()

Parameters
  • arg «Object» field specification
Returns:
  • «Aggregate»

Appends a new $addFields operator to this aggregate pipeline. Requires MongoDB v3.4+ to work

Examples:

  1. // adding new fields based on existing fields
  2. aggregate.addFields({
  3. newField: '$b.nested'
  4. , plusTen: { $add: ['$val', 10]}
  5. , sub: {
  6. name: '$a'
  7. }
  8. })
  9. // etc
  10. aggregate.addFields({ salary_k: { $divide: [ "$salary", 1000 ] } });

Aggregate.prototype.allowDiskUse()

Parameters
  • value «Boolean» Should tell server it can use hard drive to store data during aggregation.

  • [tags] «Array» optional tags for this query

Sets the allowDiskUse option for the aggregation query (ignored for < 2.6.0)

Example:

  1. await Model.aggregate([{ $match: { foo: 'bar' } }]).allowDiskUse(true);

Aggregate.prototype.append()

Parameters
  • ops «Object» operator(s) to append
Returns:
  • «Aggregate»

Appends new operators to this aggregate pipeline

Examples:

  1. aggregate.append({ $project: { field: 1 }}, { $limit: 2 });
  2. // or pass an array
  3. const pipeline = [{ $match: { daw: 'Logic Audio X' }} ];
  4. aggregate.append(pipeline);

Aggregate.prototype.catch()

Parameters
  • [reject] «Function»
Returns:
  • «Promise»

Executes the query returning a Promise which will be resolved with either the doc(s) or rejected with the error. Like .then(), but only takes a rejection handler.


Aggregate.prototype.collation()

Parameters
  • collation «Object» options
Returns:
  • «Aggregate» this

Adds a collation

Example:

  1. Model.aggregate(..).collation({ locale: 'en_US', strength: 1 }).exec();

Aggregate.prototype.count()

Parameters
  • the «String» name of the count field
Returns:
  • «Aggregate»

Appends a new $count operator to this aggregate pipeline.

Examples:

  1. aggregate.count("userCount");

Aggregate.prototype.cursor()

Parameters
  • options «Object»
  • options.batchSize «Number» set the cursor batch size

  • [options.useMongooseAggCursor] «Boolean» use experimental mongoose-specific aggregation cursor (for eachAsync() and other query cursor semantics)

Returns:
  • «Aggregate» this

Sets the cursor option option for the aggregation query (ignored for < 2.6.0). Note the different syntax below: .exec() returns a cursor object, and no callback is necessary.

Example:

  1. const cursor = Model.aggregate(..).cursor({ batchSize: 1000 }).exec();
  2. cursor.eachAsync(function(doc, i) {
  3. // use doc
  4. });

Aggregate.prototype.exec()

Parameters
  • [callback] «Function»
Returns:
  • «Promise»

Executes the aggregate pipeline on the currently bound Model.

Example:

  1. aggregate.exec(callback);
  2. // Because a promise is returned, the `callback` is optional.
  3. const promise = aggregate.exec();
  4. promise.then(..);

Aggregate.prototype.explain()

Parameters
  • callback «Function»
Returns:
  • «Promise»

Execute the aggregation with explain

Example:

  1. Model.aggregate(..).explain(callback)

Aggregate.prototype.facet()

Parameters
  • facet «Object» options
Returns:
  • «Aggregate» this

Combines multiple aggregation pipelines.

Example:

  1. Model.aggregate(...)
  2. .facet({
  3. books: [{ groupBy: '$author' }],
  4. price: [{ $bucketAuto: { groupBy: '$price', buckets: 2 } }]
  5. })
  6. .exec();
  7. // Output: { books: [...], price: [{...}, {...}] }

Aggregate.prototype.graphLookup()

Parameters
  • options «Object» to $graphLookup as described in the above link
Returns:
  • «Aggregate»

Appends new custom $graphLookup operator(s) to this aggregate pipeline, performing a recursive search on a collection.

Note that graphLookup can only consume at most 100MB of memory, and does not allow disk use even if { allowDiskUse: true } is specified.

Examples:

  1. // Suppose we have a collection of courses, where a document might look like `{ _id: 0, name: 'Calculus', prerequisite: 'Trigonometry'}` and `{ _id: 0, name: 'Trigonometry', prerequisite: 'Algebra' }`
  2. aggregate.graphLookup({ from: 'courses', startWith: '$prerequisite', connectFromField: 'prerequisite', connectToField: 'name', as: 'prerequisites', maxDepth: 3 }) // this will recursively search the 'courses' collection up to 3 prerequisites

Aggregate.prototype.group()

Parameters
  • arg «Object» $group operator contents
Returns:
  • «Aggregate»

Appends a new custom $group operator to this aggregate pipeline.

Examples:

  1. aggregate.group({ _id: "$department" });

Aggregate.prototype.hint()

Parameters
  • value «Object|String» a hint object or the index name

Sets the hint option for the aggregation query (ignored for < 3.6.0)

Example:

  1. Model.aggregate(..).hint({ qty: 1, category: 1 }).exec(callback)

Aggregate.prototype.limit()

Parameters
  • num «Number» maximum number of records to pass to the next stage
Returns:
  • «Aggregate»

Appends a new $limit operator to this aggregate pipeline.

Examples:

  1. aggregate.limit(10);

Aggregate.prototype.lookup()

Parameters
  • options «Object» to $lookup as described in the above link
Returns:
  • «Aggregate*» @api public

Appends new custom $lookup operator to this aggregate pipeline.

Examples:

  1. aggregate.lookup({ from: 'users', localField: 'userId', foreignField: '_id', as: 'users' });

Aggregate.prototype.match()

Parameters
  • arg «Object» $match operator contents
Returns:
  • «Aggregate»

Appends a new custom $match operator to this aggregate pipeline.

Examples:

  1. aggregate.match({ department: { $in: [ "sales", "engineering" ] } });

Aggregate.prototype.model()

Parameters
  • [model] «Model» set the model associated with this aggregate.
Returns:
  • «Model»

Get/set the model that this aggregation will execute on.

Example:

  1. const aggregate = MyModel.aggregate([{ $match: { answer: 42 } }]);
  2. aggregate.model() === MyModel; // true
  3. // Change the model. There's rarely any reason to do this.
  4. aggregate.model(SomeOtherModel);
  5. aggregate.model() === SomeOtherModel; // true

Aggregate.prototype.near()

Parameters
  • arg «Object»
Returns:
  • «Aggregate»

Appends a new $geoNear operator to this aggregate pipeline.

NOTE:

MUST be used as the first operator in the pipeline.

Examples:

  1. aggregate.near({
  2. near: [40.724, -73.997],
  3. distanceField: "dist.calculated", // required
  4. maxDistance: 0.008,
  5. query: { type: "public" },
  6. includeLocs: "dist.location",
  7. uniqueDocs: true,
  8. num: 5
  9. });

Aggregate.prototype.option()

Parameters
Returns:
  • «Aggregate» this

Lets you set arbitrary options, for middleware or plugins.

Example:

  1. const agg = Model.aggregate(..).option({ allowDiskUse: true }); // Set the `allowDiskUse` option
  2. agg.options; // `{ allowDiskUse: true }`

Aggregate.prototype.options

Type:
  • «property»

Contains options passed down to the aggregate command.

Supported options are


Aggregate.prototype.pipeline()

Returns:
  • «Array»

Returns the current pipeline

Example:

  1. MyModel.aggregate().match({ test: 1 }).pipeline(); // [{ $match: { test: 1 } }]

Aggregate.prototype.project()

Parameters
  • arg «Object|String» field specification
Returns:
  • «Aggregate»

Appends a new $project operator to this aggregate pipeline.

Mongoose query selection syntax is also supported.

Examples:

  1. // include a, include b, exclude _id
  2. aggregate.project("a b -_id");
  3. // or you may use object notation, useful when
  4. // you have keys already prefixed with a "-"
  5. aggregate.project({a: 1, b: 1, _id: 0});
  6. // reshaping documents
  7. aggregate.project({
  8. newField: '$b.nested'
  9. , plusTen: { $add: ['$val', 10]}
  10. , sub: {
  11. name: '$a'
  12. }
  13. })
  14. // etc
  15. aggregate.project({ salary_k: { $divide: [ "$salary", 1000 ] } });

Aggregate.prototype.read()

Parameters
  • pref «String» one of the listed preference options or their aliases

  • [tags] «Array» optional tags for this query

Returns:
  • «Aggregate» this

Sets the readPreference option for the aggregation query.

Example:

  1. Model.aggregate(..).read('primaryPreferred').exec(callback)

Aggregate.prototype.readConcern()

Parameters
  • level «String» one of the listed read concern level or their aliases
Returns:
  • «Aggregate» this

Sets the readConcern level for the aggregation query.

Example:

  1. Model.aggregate(..).readConcern('majority').exec(callback)

Aggregate.prototype.redact()

Parameters
  • expression «Object» redact options or conditional expression

  • [thenExpr] «String|Object» true case for the condition

  • [elseExpr] «String|Object» false case for the condition

Returns:
  • «Aggregate» this

Appends a new $redact operator to this aggregate pipeline.

If 3 arguments are supplied, Mongoose will wrap them with if-then-else of $cond operator respectively If thenExpr or elseExpr is string, make sure it starts with , like DESCEND, PRUNE or KEEP.

Example:

  1. Model.aggregate(...)
  2. .redact({
  3. $cond: {
  4. if: { $eq: [ '$level', 5 ] },
  5. then: '$$PRUNE',
  6. else: '$$DESCEND'
  7. }
  8. })
  9. .exec();
  10. // $redact often comes with $cond operator, you can also use the following syntax provided by mongoose
  11. Model.aggregate(...)
  12. .redact({ $eq: [ '$level', 5 ] }, '$$PRUNE', '$$DESCEND')
  13. .exec();

Aggregate.prototype.replaceRoot()

Parameters
  • the «String|Object» field or document which will become the new root document
Returns:
  • «Aggregate»

Appends a new $replaceRoot operator to this aggregate pipeline.

Note that the $replaceRoot operator requires field strings to start with ‘$’. If you are passing in a string Mongoose will prepend ‘$’ if the specified field doesn’t start ‘$’. If you are passing in an object the strings in your expression will not be altered.

Examples:

  1. aggregate.replaceRoot("user");
  2. aggregate.replaceRoot({ x: { $concat: ['$this', '$that'] } });

Aggregate.prototype.sample()

Parameters
  • size «Number» number of random documents to pick
Returns:
  • «Aggregate»

Appends new custom $sample operator to this aggregate pipeline.

Examples:

  1. aggregate.sample(3); // Add a pipeline that picks 3 random documents

Aggregate.prototype.search()

Parameters
  • $search «Object» options
Returns:
  • «Aggregate» this

Helper for Atlas Text Search‘s $search stage.

Example:

  1. Model.aggregate().
  2. search({
  3. text: {
  4. query: 'baseball',
  5. path: 'plot'
  6. }
  7. });
  8. // Output: [{ plot: '...', title: '...' }]

Aggregate.prototype.session()

Parameters
  • session «ClientSession»

Sets the session for this aggregation. Useful for transactions.

Example:

  1. const session = await Model.startSession();
  2. await Model.aggregate(..).session(session);

Aggregate.prototype.skip()

Parameters
  • num «Number» number of records to skip before next stage
Returns:
  • «Aggregate»

Appends a new $skip operator to this aggregate pipeline.

Examples:

  1. aggregate.skip(10);

Aggregate.prototype.sort()

Parameters
  • arg «Object|String»
Returns:
  • «Aggregate» this

Appends a new $sort operator to this aggregate pipeline.

If an object is passed, values allowed are asc, desc, ascending, descending, 1, and -1.

If a string is passed, it must be a space delimited list of path names. The sort order of each path is ascending unless the path name is prefixed with - which will be treated as descending.

Examples:

  1. // these are equivalent
  2. aggregate.sort({ field: 'asc', test: -1 });
  3. aggregate.sort('field -test');

Aggregate.prototype.sortByCount()

Parameters
  • arg «Object|String»
Returns:
  • «Aggregate» this

Appends a new $sortByCount operator to this aggregate pipeline. Accepts either a string field name or a pipeline object.

Note that the $sortByCount operator requires the new root to start with ‘$’. Mongoose will prepend ‘$’ if the specified field name doesn’t start with ‘$’.

Examples:

  1. aggregate.sortByCount('users');
  2. aggregate.sortByCount({ $mergeObjects: [ "$employee", "$business" ] })

Aggregate.prototype.then()

Parameters
  • [resolve] «Function» successCallback

  • [reject] «Function» errorCallback

Returns:
  • «Promise»

Provides promise for aggregate.

Example:

  1. Model.aggregate(..).then(successCallback, errorCallback);

Aggregate.prototype.unwind()

Parameters
  • fields «String|Object» the field(s) to unwind, either as field names or as objects with options. If passing a string, prefixing the field name with ‘$’ is optional. If passing an object, path must start with ‘$’.
Returns:
  • «Aggregate»

Appends new custom $unwind operator(s) to this aggregate pipeline.

Note that the $unwind operator requires the path name to start with ‘$’. Mongoose will prepend ‘$’ if the specified field doesn’t start ‘$’.

Examples:

  1. aggregate.unwind("tags");
  2. aggregate.unwind("a", "b", "c");
  3. aggregate.unwind({ path: '$tags', preserveNullAndEmptyArrays: true });

AggregationCursor


AggregationCursor()

Parameters
  • agg «Aggregate»
  • options «Object»

An AggregationCursor is a concurrency primitive for processing aggregation results one document at a time. It is analogous to QueryCursor.

An AggregationCursor fulfills the Node.js streams3 API, in addition to several other mechanisms for loading documents from MongoDB one at a time.

Creating an AggregationCursor executes the model’s pre aggregate hooks, but not the model’s post aggregate hooks.

Unless you’re an advanced user, do not instantiate this class directly. Use Aggregate#cursor() instead.


AggregationCursor.prototype.Symbol.asyncIterator()

Returns an asyncIterator for use with [for/await/of loops](https://thecodebarbarian.com/getting-started-with-async-iterators-in-node-js You do not need to call this function explicitly, the JavaScript runtime will call it for you.

Example

  1. // Async iterator without explicitly calling `cursor()`. Mongoose still
  2. // creates an AggregationCursor instance internally.
  3. const agg = Model.aggregate([{ $match: { age: { $gte: 25 } } }]);
  4. for await (const doc of agg) {
  5. console.log(doc.name);
  6. }
  7. // You can also use an AggregationCursor instance for async iteration
  8. const cursor = Model.aggregate([{ $match: { age: { $gte: 25 } } }]).cursor();
  9. for await (const doc of cursor) {
  10. console.log(doc.name);
  11. }

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

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


AggregationCursor.prototype.addCursorFlag()

Parameters
  • flag «String»
  • value «Boolean»
Returns:
  • «AggregationCursor» this

Adds a cursor flag. Useful for setting the noCursorTimeout and tailable flags.


AggregationCursor.prototype.close()

Parameters
  • callback «Function»
Returns:
  • «Promise»

Marks this cursor as closed. Will stop streaming and subsequent calls to next() will error.


AggregationCursor.prototype.eachAsync()

Parameters
  • fn «Function»
  • [options] «Object»

  • [options.parallel] «Number» the number of promises to execute in parallel. Defaults to 1.

  • [callback] «Function» executed when all docs have been processed

Returns:
  • «Promise»

Execute fn for every document in the cursor. If fn returns a promise, will wait for the promise to resolve before iterating on to the next one. Returns a promise that resolves when done.


AggregationCursor.prototype.map()

Parameters
  • fn «Function»
Returns:
  • «AggregationCursor»

Registers a transform function which subsequently maps documents retrieved via the streams interface or .next()

Example

  1. // Map documents returned by `data` events
  2. Thing.
  3. find({ name: /^hello/ }).
  4. cursor().
  5. map(function (doc) {
  6. doc.foo = "bar";
  7. return doc;
  8. })
  9. on('data', function(doc) { console.log(doc.foo); });
  10. // Or map documents returned by `.next()`
  11. const cursor = Thing.find({ name: /^hello/ }).
  12. cursor().
  13. map(function (doc) {
  14. doc.foo = "bar";
  15. return doc;
  16. });
  17. cursor.next(function(error, doc) {
  18. console.log(doc.foo);
  19. });

AggregationCursor.prototype.next()

Parameters
  • callback «Function»
Returns:
  • «Promise»

Get the next document from this cursor. Will return null when there are no documents left.


Schematype


SchemaType()

Parameters

SchemaType constructor. Do not instantiate SchemaType directly. Mongoose converts your schema paths into SchemaTypes automatically.

Example:

  1. const schema = new Schema({ name: String });
  2. schema.path('name') instanceof SchemaType; // true

SchemaType.prototype.cast()

Parameters
  • value «Object» value to cast

  • doc «Document» document that triggers the casting

  • init «Boolean»

The function that Mongoose calls to cast arbitrary values to this SchemaType.


SchemaType.prototype.default()

Parameters
  • val «Function|any» the default value
Returns:
  • «defaultValue»

Sets a default value for this SchemaType.

Example:

  1. const schema = new Schema({ n: { type: Number, default: 10 })
  2. const M = db.model('M', schema)
  3. const m = new M;
  4. console.log(m.n) // 10

Defaults can be either functions which return the value to use as the default or the literal value itself. Either way, the value will be cast based on its schema type before being set during document creation.

Example:

  1. // values are cast:
  2. const schema = new Schema({ aNumber: { type: Number, default: 4.815162342 }})
  3. const M = db.model('M', schema)
  4. const m = new M;
  5. console.log(m.aNumber) // 4.815162342
  6. // default unique objects for Mixed types:
  7. const schema = new Schema({ mixed: Schema.Types.Mixed });
  8. schema.path('mixed').default(function () {
  9. return {};
  10. });
  11. // if we don't use a function to return object literals for Mixed defaults,
  12. // each document will receive a reference to the same object literal creating
  13. // a "shared" object instance:
  14. const schema = new Schema({ mixed: Schema.Types.Mixed });
  15. schema.path('mixed').default({});
  16. const M = db.model('M', schema);
  17. const m1 = new M;
  18. m1.mixed.added = 1;
  19. console.log(m1.mixed); // { added: 1 }
  20. const m2 = new M;
  21. console.log(m2.mixed); // { added: 1 }

SchemaType.prototype.get()

Parameters
  • fn «Function»
Returns:
  • «SchemaType» this

Adds a getter to this schematype.

Example:

  1. function dob (val) {
  2. if (!val) return val;
  3. return (val.getMonth() + 1) + "/" + val.getDate() + "/" + val.getFullYear();
  4. }
  5. // defining within the schema
  6. const s = new Schema({ born: { type: Date, get: dob })
  7. // or by retreiving its SchemaType
  8. const s = new Schema({ born: Date })
  9. s.path('born').get(dob)

Getters allow you to transform the representation of the data as it travels from the raw mongodb document to the value that you see.

Suppose you are storing credit card numbers and you want to hide everything except the last 4 digits to the mongoose user. You can do so by defining a getter in the following way:

  1. function obfuscate (cc) {
  2. return '****-****-****-' + cc.slice(cc.length-4, cc.length);
  3. }
  4. const AccountSchema = new Schema({
  5. creditCardNumber: { type: String, get: obfuscate }
  6. });
  7. const Account = db.model('Account', AccountSchema);
  8. Account.findById(id, function (err, found) {
  9. console.log(found.creditCardNumber); // '****-****-****-1234'
  10. });

Getters are also passed a second argument, the schematype on which the getter was defined. This allows for tailored behavior based on options passed in the schema.

  1. function inspector (val, schematype) {
  2. if (schematype.options.required) {
  3. return schematype.path + ' is required';
  4. } else {
  5. return schematype.path + ' is not';
  6. }
  7. }
  8. const VirusSchema = new Schema({
  9. name: { type: String, required: true, get: inspector },
  10. taxonomy: { type: String, get: inspector }
  11. })
  12. const Virus = db.model('Virus', VirusSchema);
  13. Virus.findById(id, function (err, virus) {
  14. console.log(virus.name); // name is required
  15. console.log(virus.taxonomy); // taxonomy is not
  16. })

SchemaType.prototype.immutable()

Parameters
  • bool «Boolean»
Returns:
  • «SchemaType» this

Defines this path as immutable. Mongoose prevents you from changing immutable paths unless the parent document has isNew: true.

Example:

  1. const schema = new Schema({
  2. name: { type: String, immutable: true },
  3. age: Number
  4. });
  5. const Model = mongoose.model('Test', schema);
  6. await Model.create({ name: 'test' });
  7. const doc = await Model.findOne();
  8. doc.isNew; // false
  9. doc.name = 'new name';
  10. doc.name; // 'test', because `name` is immutable

Mongoose also prevents changing immutable properties using updateOne() and updateMany() based on strict mode.

Example:

  1. // Mongoose will strip out the `name` update, because `name` is immutable
  2. Model.updateOne({}, { $set: { name: 'test2' }, $inc: { age: 1 } });
  3. // If `strict` is set to 'throw', Mongoose will throw an error if you
  4. // update `name`
  5. const err = await Model.updateOne({}, { name: 'test2' }, { strict: 'throw' }).
  6. then(() => null, err => err);
  7. err.name; // StrictModeError
  8. // If `strict` is `false`, Mongoose allows updating `name` even though
  9. // the property is immutable.
  10. Model.updateOne({}, { name: 'test2' }, { strict: false });

SchemaType.prototype.index()

Parameters
  • options «Object|Boolean|String»
Returns:
  • «SchemaType» this

Declares the index options for this schematype.

Example:

  1. const s = new Schema({ name: { type: String, index: true })
  2. const s = new Schema({ loc: { type: [Number], index: 'hashed' })
  3. const s = new Schema({ loc: { type: [Number], index: '2d', sparse: true })
  4. const s = new Schema({ loc: { type: [Number], index: { type: '2dsphere', sparse: true }})
  5. const s = new Schema({ date: { type: Date, index: { unique: true, expires: '1d' }})
  6. s.path('my.path').index(true);
  7. s.path('my.date').index({ expires: 60 });
  8. s.path('my.path').index({ unique: true, sparse: true });

NOTE:

Indexes are created in the background by default. If background is set to false, MongoDB will not execute any read/write operations you send until the index build. Specify background: false to override Mongoose’s default.


SchemaType.prototype.ref()

Parameters
  • ref «String|Model|Function» either a model name, a Model, or a function that returns a model name or model.
Returns:
  • «SchemaType» this

Set the model that this path refers to. This is the option that populate looks at to determine the foreign collection it should query.

Example:

  1. const userSchema = new Schema({ name: String });
  2. const User = mongoose.model('User', userSchema);
  3. const postSchema = new Schema({ user: mongoose.ObjectId });
  4. postSchema.path('user').ref('User'); // Can set ref to a model name
  5. postSchema.path('user').ref(User); // Or a model class
  6. postSchema.path('user').ref(() => 'User'); // Or a function that returns the model name
  7. postSchema.path('user').ref(() => User); // Or a function that returns the model class
  8. // Or you can just declare the `ref` inline in your schema
  9. const postSchema2 = new Schema({
  10. user: { type: mongoose.ObjectId, ref: User }
  11. });

SchemaType.prototype.required()

Parameters
  • required «Boolean|Function|Object» enable/disable the validator, or function that returns required boolean, or options object

  • [options.isRequired] «Boolean|Function» enable/disable the validator, or function that returns required boolean

  • [options.ErrorConstructor] «Function» custom error constructor. The constructor receives 1 parameter, an object containing the validator properties.

  • [message] «String» optional custom error message

Returns:
  • «SchemaType» this

Adds a required validator to this SchemaType. The validator gets added to the front of this SchemaType’s validators array using unshift().

Example:

  1. const s = new Schema({ born: { type: Date, required: true })
  2. // or with custom error message
  3. const s = new Schema({ born: { type: Date, required: '{PATH} is required!' })
  4. // or with a function
  5. const s = new Schema({
  6. userId: ObjectId,
  7. username: {
  8. type: String,
  9. required: function() { return this.userId != null; }
  10. }
  11. })
  12. // or with a function and a custom message
  13. const s = new Schema({
  14. userId: ObjectId,
  15. username: {
  16. type: String,
  17. required: [
  18. function() { return this.userId != null; },
  19. 'username is required if id is specified'
  20. ]
  21. }
  22. })
  23. // or through the path API
  24. s.path('name').required(true);
  25. // with custom error messaging
  26. s.path('name').required(true, 'grrr :( ');
  27. // or make a path conditionally required based on a function
  28. const isOver18 = function() { return this.age >= 18; };
  29. s.path('voterRegistrationId').required(isOver18);

The required validator uses the SchemaType’s checkRequired function to determine whether a given value satisfies the required validator. By default, a value satisfies the required validator if val != null (that is, if the value is not null nor undefined). However, most built-in mongoose schema types override the default checkRequired function:


SchemaType.prototype.select()

Parameters
  • val «Boolean»
Returns:
  • «SchemaType» this

Sets default select() behavior for this path.

Set to true if this path should always be included in the results, false if it should be excluded by default. This setting can be overridden at the query level.

Example:

  1. T = db.model('T', new Schema({ x: { type: String, select: true }}));
  2. T.find(..); // field x will always be selected ..
  3. // .. unless overridden;
  4. T.find().select('-x').exec(callback);

SchemaType.prototype.set()

Parameters
  • fn «Function»
Returns:
  • «SchemaType» this

Adds a setter to this schematype.

Example:

  1. function capitalize (val) {
  2. if (typeof val !== 'string') val = '';
  3. return val.charAt(0).toUpperCase() + val.substring(1);
  4. }
  5. // defining within the schema
  6. const s = new Schema({ name: { type: String, set: capitalize }});
  7. // or with the SchemaType
  8. const s = new Schema({ name: String })
  9. s.path('name').set(capitalize);

Setters allow you to transform the data before it gets to the raw mongodb document or query.

Suppose you are implementing user registration for a website. Users provide an email and password, which gets saved to mongodb. The email is a string that you will want to normalize to lower case, in order to avoid one email having more than one account — e.g., otherwise, avenue@q.com can be registered for 2 accounts via avenue@q.com and AvEnUe@Q.CoM.

You can set up email lower case normalization easily via a Mongoose setter.

  1. function toLower(v) {
  2. return v.toLowerCase();
  3. }
  4. const UserSchema = new Schema({
  5. email: { type: String, set: toLower }
  6. });
  7. const User = db.model('User', UserSchema);
  8. const user = new User({email: 'AVENUE@Q.COM'});
  9. console.log(user.email); // 'avenue@q.com'
  10. // or
  11. const user = new User();
  12. user.email = 'Avenue@Q.com';
  13. console.log(user.email); // 'avenue@q.com'
  14. User.updateOne({ _id: _id }, { $set: { email: 'AVENUE@Q.COM' } }); // update to 'avenue@q.com'

As you can see above, setters allow you to transform the data before it stored in MongoDB, or before executing a query.

NOTE: we could have also just used the built-in lowercase: true SchemaType option instead of defining our own function.

  1. new Schema({ email: { type: String, lowercase: true }})

Setters are also passed a second argument, the schematype on which the setter was defined. This allows for tailored behavior based on options passed in the schema.

  1. function inspector (val, schematype) {
  2. if (schematype.options.required) {
  3. return schematype.path + ' is required';
  4. } else {
  5. return val;
  6. }
  7. }
  8. const VirusSchema = new Schema({
  9. name: { type: String, required: true, set: inspector },
  10. taxonomy: { type: String, set: inspector }
  11. })
  12. const Virus = db.model('Virus', VirusSchema);
  13. const v = new Virus({ name: 'Parvoviridae', taxonomy: 'Parvovirinae' });
  14. console.log(v.name); // name is required
  15. console.log(v.taxonomy); // Parvovirinae

You can also use setters to modify other properties on the document. If you’re setting a property name on a document, the setter will run with this as the document. Be careful, in mongoose 5 setters will also run when querying by name with this as the query.

  1. const nameSchema = new Schema({ name: String, keywords: [String] });
  2. nameSchema.path('name').set(function(v) {
  3. // Need to check if `this` is a document, because in mongoose 5
  4. // setters will also run on queries, in which case `this` will be a
  5. // mongoose query object.
  6. if (this instanceof Document && v != null) {
  7. this.keywords = v.split(' ');
  8. }
  9. return v;
  10. });

SchemaType.prototype.sparse()

Parameters
  • bool «Boolean»
Returns:
  • «SchemaType» this

Declares a sparse index.

Example:

  1. const s = new Schema({ name: { type: String, sparse: true } });
  2. s.path('name').index({ sparse: true });

SchemaType.prototype.text()

Parameters
  • bool «Boolean»
Returns:
  • «SchemaType» this

Declares a full text index.

Example:

  1. const s = new Schema({name : {type: String, text : true })
  2. s.path('name').index({text : true});

SchemaType.prototype.transform()

Parameters
  • fn «Function»
Returns:
  • «SchemaType» this

Defines a custom function for transforming this path when converting a document to JSON.

Mongoose calls this function with one parameter: the current value of the path. Mongoose then uses the return value in the JSON output.

Example:

  1. const schema = new Schema({
  2. date: { type: Date, transform: v => v.getFullYear() }
  3. });
  4. const Model = mongoose.model('Test', schema);
  5. await Model.create({ date: new Date('2016-06-01') });
  6. const doc = await Model.findOne();
  7. doc.date instanceof Date; // true
  8. doc.toJSON().date; // 2016 as a number
  9. JSON.stringify(doc); // '{"_id":...,"date":2016}'

SchemaType.prototype.unique()

Parameters
  • bool «Boolean»
Returns:
  • «SchemaType» this

Declares an unique index.

Example:

  1. const s = new Schema({ name: { type: String, unique: true }});
  2. s.path('name').index({ unique: true });

NOTE: violating the constraint returns an E11000 error from MongoDB when saving, not a Mongoose validation error.


SchemaType.prototype.validate()

Parameters
  • obj «RegExp|Function|Object» validator function, or hash describing options

  • [obj.validator] «Function» validator function. If the validator function returns undefined or a truthy value, validation succeeds. If it returns falsy (except undefined) or throws an error, validation fails.

  • [obj.message] «String|Function» optional error message. If function, should return the error message as a string

  • [obj.propsParameter=false] «Boolean» If true, Mongoose will pass the validator properties object (with the validator function, message, etc.) as the 2nd arg to the validator function. This is disabled by default because many validators rely on positional args, so turning this on may cause unpredictable behavior in external validators.

  • [errorMsg] «String|Function» optional error message. If function, should return the error message as a string

  • [type] «String» optional validator type

Returns:
  • «SchemaType» this

Adds validator(s) for this document path.

Validators always receive the value to validate as their first argument and must return Boolean. Returning false or throwing an error means validation failed.

The error message argument is optional. If not passed, the default generic error message template will be used.

Examples:

  1. // make sure every value is equal to "something"
  2. function validator (val) {
  3. return val == 'something';
  4. }
  5. new Schema({ name: { type: String, validate: validator }});
  6. // with a custom error message
  7. const custom = [validator, 'Uh oh, {PATH} does not equal "something".']
  8. new Schema({ name: { type: String, validate: custom }});
  9. // adding many validators at a time
  10. const many = [
  11. { validator: validator, msg: 'uh oh' }
  12. , { validator: anotherValidator, msg: 'failed' }
  13. ]
  14. new Schema({ name: { type: String, validate: many }});
  15. // or utilizing SchemaType methods directly:
  16. const schema = new Schema({ name: 'string' });
  17. schema.path('name').validate(validator, 'validation of `{PATH}` failed with value `{VALUE}`');

Error message templates:

From the examples above, you may have noticed that error messages support basic templating. There are a few other template keywords besides {PATH} and {VALUE} too. To find out more, details are available here.

If Mongoose’s built-in error message templating isn’t enough, Mongoose supports setting the message property to a function.

  1. schema.path('name').validate({
  2. validator: function() { return v.length > 5; },
  3. // `errors['name']` will be "name must have length 5, got 'foo'"
  4. message: function(props) {
  5. return `${props.path} must have length 5, got '${props.value}'`;
  6. }
  7. });

To bypass Mongoose’s error messages and just copy the error message that the validator throws, do this:

  1. schema.path('name').validate({
  2. validator: function() { throw new Error('Oops!'); },
  3. // `errors['name']` will be "Oops!"
  4. message: function(props) { return props.reason.message; }
  5. });

Asynchronous validation:

Mongoose supports validators that return a promise. A validator that returns a promise is called an async validator. Async validators run in parallel, and validate() will wait until all async validators have settled.

  1. schema.path('name').validate({
  2. validator: function (value) {
  3. return new Promise(function (resolve, reject) {
  4. resolve(false); // validation failed
  5. });
  6. }
  7. });

You might use asynchronous validators to retreive other documents from the database to validate against or to meet other I/O bound validation needs.

Validation occurs pre('save') or whenever you manually execute document#validate.

If validation fails during pre('save') and no callback was passed to receive the error, an error event will be emitted on your Models associated db connection, passing the validation error object along.

  1. const conn = mongoose.createConnection(..);
  2. conn.on('error', handleError);
  3. const Product = conn.model('Product', yourSchema);
  4. const dvd = new Product(..);
  5. dvd.save(); // emits error on the `conn` above

If you want to handle these errors at the Model level, add an error listener to your Model as shown below.

  1. // registering an error listener on the Model lets us handle errors more locally
  2. Product.on('error', handleError);

Schematype.cast()

Parameters
  • caster «Function|false» Function that casts arbitrary values to this type, or throws an error if casting failed
Returns:
  • «Function»

Get/set the function used to cast arbitrary values to this type.

Example:

  1. // Disallow `null` for numbers, and don't try to cast any values to
  2. // numbers, so even strings like '123' will cause a CastError.
  3. mongoose.Number.cast(function(v) {
  4. assert.ok(v === undefined || typeof v === 'number');
  5. return v;
  6. });

Schematype.cast()

Parameters
  • caster «Function|false» Function that casts arbitrary values to this type, or throws an error if casting failed
Returns:
  • «Function»

Get/set the function used to cast arbitrary values to this particular schematype instance. Overrides SchemaType.cast().

Example:

  1. // Disallow `null` for numbers, and don't try to cast any values to
  2. // numbers, so even strings like '123' will cause a CastError.
  3. const number = new mongoose.Number('mypath', {});
  4. number.cast(function(v) {
  5. assert.ok(v === undefined || typeof v === 'number');
  6. return v;
  7. });

Schematype.checkRequired()

Parameters
  • fn «Function»
Returns:
  • «Function»

Override the function the required validator uses to check whether a value passes the required check. Override this on the individual SchemaType.

Example:

  1. // Use this to allow empty strings to pass the `required` validator
  2. mongoose.Schema.Types.String.checkRequired(v => typeof v === 'string');

Schematype.get()

Parameters
  • getter «Function»
Returns:
  • «this»

Attaches a getter for all instances of this schema type.

Example:

  1. // Make all numbers round down
  2. mongoose.Number.get(function(v) { return Math.floor(v); });

Schematype.set()

Parameters
  • option «String» The name of the option you’d like to set (e.g. trim, lowercase, etc…)

  • value «*» The value of the option you’d like to set.

Returns:
  • «void»

Sets a default option for this schema type.

Example:

  1. // Make all strings be trimmed by default
  2. mongoose.SchemaTypes.String.set('trim', true);

Virtualtype


VirtualType()

Parameters
  • options «Object»

  • [options.ref] «string|function» if ref is not nullish, this becomes a populated virtual

  • [options.localField] «string|function» the local field to populate on if this is a populated virtual.

  • [options.foreignField] «string|function» the foreign field to populate on if this is a populated virtual.

  • [options.justOne=false] «boolean» by default, a populated virtual is an array. If you set justOne, the populated virtual will be a single doc or null.

  • [options.getters=false] «boolean» if you set this to true, Mongoose will call any custom getters you defined on this virtual

  • [options.count=false] «boolean» if you set this to true, populate() will set this virtual to the number of populated documents, as opposed to the documents themselves, using Query#countDocuments()

  • [options.match=null] «Object|Function» add an extra match condition to populate()

  • [options.limit=null] «Number» add a default limit to the populate() query

  • [options.skip=null] «Number» add a default skip to the populate() query

  • [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.options=null] «Object» Additional options like limit and lean.

VirtualType constructor

This is what mongoose uses to define virtual attributes via Schema.prototype.virtual.

Example:

  1. const fullname = schema.virtual('fullname');
  2. fullname instanceof mongoose.VirtualType // true

VirtualType.prototype.applyGetters()

Parameters
  • value «Object»
  • doc «Document» The document this virtual is attached to
Returns:
  • «any» the value after applying all getters

Applies getters to value.


VirtualType.prototype.applySetters()

Parameters
  • value «Object»
  • doc «Document»
Returns:
  • «any» the value after applying all setters

Applies setters to value.


VirtualType.prototype.get()

Parameters
  • VirtualType, «Function(Any|» Document)} fn
Returns:
  • «VirtualType» this

Adds a custom getter to this virtual.

Mongoose calls the getter function with the below 3 parameters.

  • value: the value returned by the previous getter. If there is only one getter, value will be undefined.
  • virtual: the virtual object you called .get() on
  • doc: the document this virtual is attached to. Equivalent to this.

Example:

  1. const virtual = schema.virtual('fullname');
  2. virtual.get(function(value, virtual, doc) {
  3. return this.name.first + ' ' + this.name.last;
  4. });

VirtualType.prototype.set()

Parameters
  • VirtualType, «Function(Any|» Document)} fn
Returns:
  • «VirtualType» this

Adds a custom setter to this virtual.

Mongoose calls the setter function with the below 3 parameters.

  • value: the value being set
  • virtual: the virtual object you’re calling .set() on
  • doc: the document this virtual is attached to. Equivalent to this.

Example:

  1. const virtual = schema.virtual('fullname');
  2. virtual.set(function(value, virtual, doc) {
  3. const parts = value.split(' ');
  4. this.name.first = parts[0];
  5. this.name.last = parts[1];
  6. });
  7. const Model = mongoose.model('Test', schema);
  8. const doc = new Model();
  9. // Calls the setter with `value = 'Jean-Luc Picard'`
  10. doc.fullname = 'Jean-Luc Picard';
  11. doc.name.first; // 'Jean-Luc'
  12. doc.name.last; // 'Picard'

Error


Error()

Parameters
  • msg «String» Error message

MongooseError constructor. MongooseError is the base class for all Mongoose-specific errors.

Example:

  1. const Model = mongoose.model('Test', new Schema({ answer: Number }));
  2. const doc = new Model({ answer: 'not a number' });
  3. const err = doc.validateSync();
  4. err instanceof mongoose.Error; // true

Error.CastError

Type:
  • «property»

An instance of this error class will be returned when mongoose failed to cast a value.


Error.DivergentArrayError

Type:
  • «property»

An instance of this error will be returned if you used an array projection and then modified the array in an unsafe way.


Error.DocumentNotFoundError

Type:
  • «property»

An instance of this error class will be returned when save() fails because the underlying document was not found. The constructor takes one parameter, the conditions that mongoose passed to update() when trying to update the document.


Error.MissingSchemaError

Type:
  • «property»

Thrown when you try to access a model that has not been registered yet


Error.OverwriteModelError

Type:
  • «property»

Thrown when a model with the given name was already registered on the connection. See the FAQ about OverwriteModelError.


Error.ParallelSaveError

Type:
  • «property»

An instance of this error class will be returned when you call save() multiple times on the same document in parallel. See the FAQ for more information.


Error.StrictModeError

Type:
  • «property»

Thrown when your try to pass values to model contrtuctor that were not specified in schema or change immutable properties when strict mode is "throw"


Error.ValidationError

Type:
  • «property»

An instance of this error class will be returned when validation failed. The errors property contains an object whose keys are the paths that failed and whose values are instances of CastError or ValidationError.


Error.ValidatorError

Type:
  • «property»

A ValidationError has a hash of errors that contain individual ValidatorError instances.

Example:

  1. const schema = Schema({ name: { type: String, required: true } });
  2. const Model = mongoose.model('Test', schema);
  3. const doc = new Model({});
  4. // Top-level error is a ValidationError, **not** a ValidatorError
  5. const err = doc.validateSync();
  6. err instanceof mongoose.Error.ValidationError; // true
  7. // A ValidationError `err` has 0 or more ValidatorErrors keyed by the
  8. // path in the `err.errors` property.
  9. err.errors['name'] instanceof mongoose.Error.ValidatorError;
  10. err.errors['name'].kind; // 'required'
  11. err.errors['name'].path; // 'name'
  12. err.errors['name'].value; // undefined

Instances of ValidatorError have the following properties:

  • kind: The validator’s type, like 'required' or 'regexp'
  • path: The path that failed validation
  • value: The value that failed validation

Error.VersionError

Type:
  • «property»

An instance of this error class will be returned when you call save() after the document in the database was changed in a potentially unsafe way. See the versionKey option for more information.


Error.messages

Type:
  • «property»

The default built-in validator error messages.


Error.prototype.name

Type:
  • «String»

The name of the error. The name uniquely identifies this Mongoose error. The possible values are:

  • MongooseError: general Mongoose error
  • CastError: Mongoose could not convert a value to the type defined in the schema path. May be in a ValidationError class’ errors property.
  • DisconnectedError: This connection timed out in trying to reconnect to MongoDB and will not successfully reconnect to MongoDB unless you explicitly reconnect.
  • DivergentArrayError: You attempted to save() an array that was modified after you loaded it with a $elemMatch or similar projection
  • MissingSchemaError: You tried to access a model with mongoose.model() that was not defined
  • DocumentNotFoundError: The document you tried to save() was not found
  • ValidatorError: error from an individual schema path’s validator
  • ValidationError: error returned from validate() or validateSync(). Contains zero or more ValidatorError instances in .errors property.
  • MissingSchemaError: You called mongoose.Document() without a schema
  • ObjectExpectedError: Thrown when you set a nested path to a non-object value with strict mode set.
  • ObjectParameterError: Thrown when you pass a non-object value to a function which expects an object as a paramter
  • OverwriteModelError: Thrown when you call mongoose.model() to re-define a model that was already defined.
  • ParallelSaveError: Thrown when you call save() on a document when the same document instance is already saving.
  • StrictModeError: Thrown when you set a path that isn’t the schema and strict mode is set to throw.
  • VersionError: Thrown when the document is out of sync

SchemaArray


SchemaArray()

Parameters
  • key «String»
  • cast «SchemaType»
  • options «Object»

Array SchemaType constructor


SchemaArray.checkRequired()

Parameters
  • fn «Function»
Returns:
  • «Function»

Override the function the required validator uses to check whether an array passes the required check.

Example:

  1. // Require non-empty array to pass `required` check
  2. mongoose.Schema.Types.Array.checkRequired(v => Array.isArray(v) &amp;&amp; v.length);
  3. const M = mongoose.model({ arr: { type: Array, required: true } });
  4. new M({ arr: [] }).validateSync(); // `null`, validation fails!

SchemaArray.options

Type:
  • «property»

Options for all arrays.

  • castNonArrays: true by default. If false, Mongoose will throw a CastError when a value isn’t an array. If true, Mongoose will wrap the provided value in an array before casting.

SchemaArray.prototype.checkRequired()

Parameters
  • value «Any»
  • doc «Document»
Returns:
  • «Boolean»

Check if the given value satisfies the required validator.


SchemaArray.prototype.enum()

Parameters
  • [args…] «String|Object» enumeration values
Returns:
  • «SchemaArray» this

Adds an enum validator if this is an array of strings or numbers. Equivalent to SchemaString.prototype.enum() or SchemaNumber.prototype.enum()


SchemaArray.schemaName

Type:
  • «property»

This schema type’s name, to defend against minifiers that mangle function names.


SchemaArray.set()

Parameters
  • option «String»
    • The option you’d like to set the value for
  • value «*»
    • value for option
Returns:
  • «undefined»

Sets a default option for all Array instances.

Example:

  1. // Make all Array instances have `required` of true by default.
  2. mongoose.Schema.Array.set('required', true);
  3. const User = mongoose.model('User', new Schema({ test: Array }));
  4. new User({ }).validateSync().errors.test.message; // Path `test` is required.

DocumentArrayPath


DocumentArrayPath()

Parameters
  • key «String»
  • schema «Schema»
  • options «Object»

SubdocsArray SchemaType constructor


DocumentArrayPath.

Parameters
  • option «String»
    • The option you’d like to set the value for
  • value «*»
    • value for option
Returns:
  • «undefined»
Type:
  • «property»

Sets a default option for all DocumentArray instances.

Example:

  1. // Make all numbers have option `min` equal to 0.
  2. mongoose.Schema.DocumentArray.set('_id', false);

DocumentArrayPath.options

Type:
  • «property»

Options for all document arrays.

  • castNonArrays: true by default. If false, Mongoose will throw a CastError when a value isn’t an array. If true, Mongoose will wrap the provided value in an array before casting.

DocumentArrayPath.prototype.discriminator()

Parameters
  • name «String»
  • schema «Schema» fields to add to the schema for instances of this sub-class

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

Returns:
  • «Function» the constructor Mongoose will use for creating instances of this discriminator model

Adds a discriminator to this document array.

Example:

  1. const shapeSchema = Schema({ name: String }, { discriminatorKey: 'kind' });
  2. const schema = Schema({ shapes: [shapeSchema] });
  3. const docArrayPath = parentSchema.path('shapes');
  4. docArrayPath.discriminator('Circle', Schema({ radius: Number }));

DocumentArrayPath.schemaName

Type:
  • «property»

This schema type’s name, to defend against minifiers that mangle function names.


SubdocumentPath


SubdocumentPath()

Parameters
  • schema «Schema»
  • key «String»
  • options «Object»

Single nested subdocument SchemaType constructor.


SubdocumentPath.

Parameters
  • option «String»
    • The option you’d like to set the value for
  • value «*»
    • value for option
Returns:
  • «undefined»
Type:
  • «property»

Sets a default option for all SubdocumentPath instances.

Example:

  1. // Make all numbers have option `min` equal to 0.
  2. mongoose.Schema.Embedded.set('required', true);

SubdocumentPath.prototype.discriminator()

Parameters
  • name «String»
  • schema «Schema» fields to add to the schema for instances of this sub-class

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

Returns:
  • «Function» the constructor Mongoose will use for creating instances of this discriminator model

Adds a discriminator to this single nested subdocument.

Example:

  1. const shapeSchema = Schema({ name: String }, { discriminatorKey: 'kind' });
  2. const schema = Schema({ shape: shapeSchema });
  3. const singleNestedPath = parentSchema.path('shape');
  4. singleNestedPath.discriminator('Circle', Schema({ radius: Number }));

SchemaTypeOptions


SchemaTypeOptions()

The options defined on a schematype.

Example:

  1. const schema = new Schema({ name: String });
  2. schema.path('name').options instanceof mongoose.SchemaTypeOptions; // true

SchemaTypeOptions.prototype.cast

Type:
  • «String»

Allows overriding casting logic for this individual path. If a string, the given string overwrites Mongoose’s default cast error message.

Example:

  1. const schema = new Schema({
  2. num: {
  3. type: Number,
  4. cast: '{VALUE} is not a valid number'
  5. }
  6. });
  7. // Throws 'CastError: "bad" is not a valid number'
  8. schema.path('num').cast('bad');
  9. const Model = mongoose.model('Test', schema);
  10. const doc = new Model({ num: 'fail' });
  11. const err = doc.validateSync();
  12. err.errors['num']; // 'CastError: "fail" is not a valid number'

SchemaTypeOptions.prototype.default

Type:
  • «Function|Any»

The default value for this path. If a function, Mongoose executes the function and uses the return value as the default.


SchemaTypeOptions.prototype.immutable

Type:
  • «Function|Boolean»

If truthy, Mongoose will disallow changes to this path once the document is saved to the database for the first time. Read more about immutability in Mongoose here.


SchemaTypeOptions.prototype.index

Type:
  • «Boolean|Number|Object»

If truthy, Mongoose will build an index on this path when the model is compiled.


SchemaTypeOptions.prototype.ref

Type:
  • «Function|String»

The model that populate() should use if populating this path.


SchemaTypeOptions.prototype.required

Type:
  • «Function|Boolean»

If true, attach a required validator to this path, which ensures this path path cannot be set to a nullish value. If a function, Mongoose calls the function and only checks for nullish values if the function returns a truthy value.


SchemaTypeOptions.prototype.select

Type:
  • «Boolean|Number»

Whether to include or exclude this path by default when loading documents using find(), findOne(), etc.


SchemaTypeOptions.prototype.sparse

Type:
  • «Boolean|Number»

If truthy, Mongoose will build a sparse index on this path.


SchemaTypeOptions.prototype.text

Type:
  • «Boolean|Number|Object»

If truthy, Mongoose will build a text index on this path.


SchemaTypeOptions.prototype.transform

Type:
  • «Function»

Define a transform function for this individual schema type. Only called when calling toJSON() or toObject().

Example:

  1. const schema = Schema({
  2. myDate: {
  3. type: Date,
  4. transform: v => v.getFullYear()
  5. }
  6. });
  7. const Model = mongoose.model('Test', schema);
  8. const doc = new Model({ myDate: new Date('2019/06/01') });
  9. doc.myDate instanceof Date; // true
  10. const res = doc.toObject({ transform: true });
  11. res.myDate; // 2019

SchemaTypeOptions.prototype.type

Type:
  • «Function|String|Object»

The type to cast this path to.


SchemaTypeOptions.prototype.unique

Type:
  • «Boolean|Number»

If truthy, Mongoose will build a unique index on this path when the model is compiled. The unique option is not a validator.


SchemaTypeOptions.prototype.validate

Type:
  • «Function|Object»

Function or object describing how to validate this schematype.


SchemaArrayOptions


SchemaArrayOptions()

The options defined on an Array schematype.

Example:

  1. const schema = new Schema({ tags: [String] });
  2. schema.path('tags').options; // SchemaArrayOptions instance

SchemaArrayOptions.prototype.enum

Type:
  • «Array»

If this is an array of strings, an array of allowed values for this path. Throws an error if this array isn’t an array of strings.


SchemaArrayOptions.prototype.of

Type:
  • «Function|String»

If set, specifies the type of this array’s values. Equivalent to setting type to an array whose first element is of.

Example:

  1. // `arr` is an array of numbers.
  2. new Schema({ arr: [Number] });
  3. // Equivalent way to define `arr` as an array of numbers
  4. new Schema({ arr: { type: Array, of: Number } });

SchemaBufferOptions


SchemaBufferOptions()

The options defined on a Buffer schematype.

Example:

  1. const schema = new Schema({ bitmap: Buffer });
  2. schema.path('bitmap').options; // SchemaBufferOptions instance

SchemaBufferOptions.prototype.subtype

Type:
  • «Number»

Set the default subtype for this buffer.


SchemaDateOptions


SchemaDateOptions()

The options defined on a Date schematype.

Example:

  1. const schema = new Schema({ startedAt: Date });
  2. schema.path('startedAt').options; // SchemaDateOptions instance

SchemaDateOptions.prototype.expires

Type:
  • «Date»

If set, Mongoose creates a TTL index on this path.


SchemaDateOptions.prototype.max

Type:
  • «Date»

If set, Mongoose adds a validator that checks that this path is before the given max.


SchemaDateOptions.prototype.min

Type:
  • «Date»

If set, Mongoose adds a validator that checks that this path is after the given min.


SchemaNumberOptions


SchemaNumberOptions()

The options defined on a Number schematype.

Example:

  1. const schema = new Schema({ count: Number });
  2. schema.path('count').options; // SchemaNumberOptions instance

SchemaNumberOptions.prototype.enum

Type:
  • «Array»

If set, Mongoose adds a validator that checks that this path is strictly equal to one of the given values.

Example:

  1. const schema = new Schema({
  2. favoritePrime: {
  3. type: Number,
  4. enum: [3, 5, 7]
  5. }
  6. });
  7. schema.path('favoritePrime').options.enum; // [3, 5, 7]

SchemaNumberOptions.prototype.max

Type:
  • «Number»

If set, Mongoose adds a validator that checks that this path is less than the given max.


SchemaNumberOptions.prototype.min

Type:
  • «Number»

If set, Mongoose adds a validator that checks that this path is at least the given min.


SchemaNumberOptions.prototype.populate

Type:
  • «Object»

Sets default populate options.

Example:

  1. const schema = new Schema({
  2. child: {
  3. type: Number,
  4. ref: 'Child',
  5. populate: { select: 'name' }
  6. }
  7. });
  8. const Parent = mongoose.model('Parent', schema);
  9. // Automatically adds `.select('name')`
  10. Parent.findOne().populate('child');

SchemaObjectIdOptions


SchemaObjectIdOptions()

The options defined on an ObjectId schematype.

Example:

  1. const schema = new Schema({ testId: mongoose.ObjectId });
  2. schema.path('testId').options; // SchemaObjectIdOptions instance

SchemaObjectIdOptions.prototype.auto

Type:
  • «Boolean»

If truthy, uses Mongoose’s default built-in ObjectId path.


SchemaObjectIdOptions.prototype.populate

Type:
  • «Object»

Sets default populate options.

Example:

  1. const schema = new Schema({
  2. child: {
  3. type: 'ObjectId',
  4. ref: 'Child',
  5. populate: { select: 'name' }
  6. }
  7. });
  8. const Parent = mongoose.model('Parent', schema);
  9. // Automatically adds `.select('name')`
  10. Parent.findOne().populate('child');

SchemaStringOptions


SchemaStringOptions()

The options defined on a string schematype.

Example:

  1. const schema = new Schema({ name: String });
  2. schema.path('name').options; // SchemaStringOptions instance

SchemaStringOptions.prototype.enum

Type:
  • «Array»

Array of allowed values for this path


SchemaStringOptions.prototype.lowercase

Type:
  • «Boolean»

If truthy, Mongoose will add a custom setter that lowercases this string using JavaScript’s built-in String#toLowerCase().


SchemaStringOptions.prototype.match

Type:
  • «RegExp»

Attach a validator that succeeds if the data string matches the given regular expression, and fails otherwise.


SchemaStringOptions.prototype.maxLength

Type:
  • «Number»

If set, Mongoose will add a custom validator that ensures the given string’s length is at most the given number.

Mongoose supports two different spellings for this option: maxLength and maxlength. maxLength is the recommended way to specify this option, but Mongoose also supports maxlength (lowercase “l”).


SchemaStringOptions.prototype.minLength

Type:
  • «Number»

If set, Mongoose will add a custom validator that ensures the given string’s length is at least the given number.

Mongoose supports two different spellings for this option: minLength and minlength. minLength is the recommended way to specify this option, but Mongoose also supports minlength (lowercase “l”).


SchemaStringOptions.prototype.populate

Type:
  • «Object»

Sets default populate options.


SchemaStringOptions.prototype.trim

Type:
  • «Boolean»

If truthy, Mongoose will add a custom setter that removes leading and trailing whitespace using JavaScript’s built-in String#trim().


SchemaStringOptions.prototype.uppercase

Type:
  • «Boolean»

If truthy, Mongoose will add a custom setter that uppercases this string using JavaScript’s built-in String#toUpperCase().