API Docs
- Mongoose()
- Mongoose.prototype.Aggregate()
- Mongoose.prototype.CastError()
- Mongoose.prototype.Collection()
- Mongoose.prototype.Connection()
- Mongoose.prototype.ConnectionStates
- Mongoose.prototype.Date
- Mongoose.prototype.Decimal128
- Mongoose.prototype.Document()
- Mongoose.prototype.DocumentProvider()
- Mongoose.prototype.Error()
- Mongoose.prototype.Mixed
- Mongoose.prototype.Model()
- Mongoose.prototype.Mongoose()
- Mongoose.prototype.Number
- Mongoose.prototype.ObjectId
- Mongoose.prototype.Promise
- Mongoose.prototype.PromiseProvider()
- Mongoose.prototype.Query()
- Mongoose.prototype.STATES
- Mongoose.prototype.Schema()
- Mongoose.prototype.SchemaType()
- Mongoose.prototype.SchemaTypeOptions()
- Mongoose.prototype.SchemaTypes
- Mongoose.prototype.Types
- Mongoose.prototype.VirtualType()
- Mongoose.prototype.connect()
- Mongoose.prototype.connection
- Mongoose.prototype.connections
- Mongoose.prototype.createConnection()
- Mongoose.prototype.deleteModel()
- Mongoose.prototype.disconnect()
- Mongoose.prototype.driver
- Mongoose.prototype.get()
- Mongoose.prototype.isObjectIdOrHexString()
- Mongoose.prototype.isValidObjectId()
- Mongoose.prototype.model()
- Mongoose.prototype.modelNames()
- Mongoose.prototype.mongo
- Mongoose.prototype.mquery
- Mongoose.prototype.now()
- Mongoose.prototype.overwriteMiddlewareResult()
- Mongoose.prototype.plugin()
- Mongoose.prototype.pluralize()
- Mongoose.prototype.sanitizeFilter()
- Mongoose.prototype.set()
- Mongoose.prototype.setDriver()
- Mongoose.prototype.skipMiddlewareFunction()
- Mongoose.prototype.startSession()
- Mongoose.prototype.syncIndexes()
- Mongoose.prototype.trusted()
- Mongoose.prototype.version
Mongoose()
Parameters
- options
«Object» see
Mongoose#set()
docs
Mongoose constructor.
The exports object of the mongoose
module is an instance of this class.
Most apps will only use this one instance.
Example:
const mongoose = require('mongoose');
mongoose instanceof mongoose.Mongoose; // true
// Create a new Mongoose instance with its own `connect()`, `set()`, `model()`, etc.
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.ConnectionStates
Type:
- «property»
Expose connection states for user-land
Mongoose.prototype.Date
Type:
- «property»
The Mongoose Date SchemaType.
Example:
const schema = new Schema({ test: Date });
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:
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:
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:
const mongoose = require('mongoose');
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:
const schema = new Schema({ num: mongoose.Number });
// Equivalent to:
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:
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:
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
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»
Mongoose.prototype.Types
Type:
- «property»
The various Mongoose Types.
Example:
const mongoose = require('mongoose');
const array = mongoose.Types.Array;
Types:
Using this exposed access to the ObjectId
type, we can construct ids on demand.
const ObjectId = mongoose.Types.ObjectId;
const id1 = new ObjectId;
Mongoose.prototype.VirtualType()
The Mongoose VirtualType constructor
Mongoose.prototype.connect()
Parameters
- uri «String» mongodb URI to connect to
- [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 afterbufferTimeoutMS
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 forserverSelectionTimeoutMS
milliseconds before erroring out. If not set, the MongoDB driver defaults to using30000
(30 seconds). - [options.heartbeatFrequencyMS]
«Number» If
useUnifiedTopology = true
, the MongoDB driver sends a heartbeat everyheartbeatFrequencyMS
to check on the status of the connection. A heartbeat is subject toserverSelectionTimeoutMS
, 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.jssocket#setTimeout()
function after the MongoDB driver successfully completes. - [options.family=0]
«Number» Passed transparently to Node.js'
dns.lookup()
function. May be either0
,4
, or6
.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 callcreateCollection()
on every model created on this connection. - [callback] «Function»
Returns:
- «Promise» resolves to
this
if connection succeeded
Opens the default mongoose connection.
Example:
mongoose.connect('mongodb://user:pass@127.0.0.1:port/database');
// replica sets
const uri = 'mongodb://user:pass@127.0.0.1:port,anotherhost:port,yetanother:port/mydatabase';
mongoose.connect(uri);
// with options
mongoose.connect(uri, options);
// optional callback that gets fired when initial connection completed
const uri = 'mongodb://nonexistent.domain:27000';
mongoose.connect(uri, function(error) {
// if error is truthy, the initial connection failed.
})
Mongoose.prototype.connection
Type:
- «Connection»
The Mongoose module's default connection. Equivalent to mongoose.connections[0]
, see connections
.
Example:
const mongoose = require('mongoose');
mongoose.connect(...);
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:
const mongoose = require('mongoose');
mongoose.connections.length; // 1, just the default connection
mongoose.connections[0] === mongoose.connection; // true
mongoose.createConnection('mongodb://127.0.0.1:27017/test');
mongoose.connections.length; // 2
Mongoose.prototype.createConnection()
Parameters
- uri «String» mongodb URI to connect to
- [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.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.jssocket#setTimeout()
function after the MongoDB driver successfully completes. - [options.family=0]
«Number» Passed transparently to Node.js'
dns.lookup()
function. May be either0
,4
, or6
.4
means use IPv4 only,6
means use IPv6 only,0
means try both.
Returns:
- «Connection» the created Connection object. Connections are not thenable, so you can't do
await mongoose.createConnection()
. To await usemongoose.createConnection(uri).asPromise()
instead.
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:
// with mongodb:// URI
db = mongoose.createConnection('mongodb://user:pass@127.0.0.1:port/database');
// and options
const opts = { db: { native_parser: true }}
db = mongoose.createConnection('mongodb://user:pass@127.0.0.1:port/database', opts);
// replica sets
db = mongoose.createConnection('mongodb://user:pass@127.0.0.1:port,anotherhost:port,yetanother:port/database');
// and options
const opts = { replset: { strategy: 'ping', rs_name: 'testSet' }}
db = mongoose.createConnection('mongodb://user:pass@127.0.0.1:port,anotherhost:port,yetanother:port/database', opts);
// initialize now, connect later
db = mongoose.createConnection();
db.openUri('127.0.0.1', '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:
mongoose.model('User', new Schema({ name: String }));
console.log(mongoose.model('User')); // Model object
mongoose.deleteModel('User');
console.log(mongoose.model('User')); // undefined
// Usually useful in a Mocha `afterEach()` hook
afterEach(function() {
mongoose.deleteModel(/.+/); // Delete every model
});
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»
Mongoose.prototype.isObjectIdOrHexString()
Parameters
- v «Any»
Returns true if the given value is a Mongoose ObjectId (using instanceof
) or if the
given value is a 24 character hex string, which is the most commonly used string representation
of an ObjectId.
This function is similar to isValidObjectId()
, but considerably more strict, because
isValidObjectId()
will return true
for any value that Mongoose can convert to an
ObjectId. That includes Mongoose documents, any string of length 12, and any number.
isObjectIdOrHexString()
returns true only for ObjectId
instances or 24 character hex
strings, and will return false for numbers, documents, and strings of length 12.
Example:
mongoose.isObjectIdOrHexString(new mongoose.Types.ObjectId()); // true
mongoose.isObjectIdOrHexString('62261a65d66c6be0a63c051f'); // true
mongoose.isObjectIdOrHexString('0123456789ab'); // false
mongoose.isObjectIdOrHexString(6); // false
mongoose.isObjectIdOrHexString(new User({ name: 'test' })); // false
mongoose.isObjectIdOrHexString({ test: 42 }); // false
Mongoose.prototype.isValidObjectId()
Parameters
- v «Any»
Returns true if Mongoose can cast the given value to an ObjectId, or false otherwise.
Example:
mongoose.isValidObjectId(new mongoose.Types.ObjectId()); // true
mongoose.isValidObjectId('0123456789ab'); // true
mongoose.isValidObjectId(6); // true
mongoose.isValidObjectId(new User({ name: 'test' })); // true
mongoose.isValidObjectId({ test: 42 }); // 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:
const mongoose = require('mongoose');
// define an Actor model with this mongoose instance
const schema = new Schema({ name: String });
mongoose.model('Actor', schema);
// create a new connection
const conn = mongoose.createConnection(..);
// create Actor model
const Actor = conn.model('Actor', schema);
conn.model('Actor') === Actor; // true
conn.model('Actor', schema) === Actor; // true, same schema
conn.model('Actor', schema, 'actors') === Actor; // true, same schema and collection name
// This throws an `OverwriteModelError` because the schema is different.
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:
const schema = new Schema({ name: String }, { collection: 'actor' });
// or
schema.set('collection', 'actor');
// or
const collectionName = 'actor'
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.overwriteMiddlewareResult()
Parameters
- result «any»
Use this function in post()
middleware to replace the result
Example:
schema.post('find', function(res) {
// Normally you have to modify `res` in place. But with
// `overwriteMiddlewarResult()`, you can make `find()` return a
// completely different value.
return mongoose.overwriteMiddlewareResult(res.filter(doc => !doc.isDeleted));
});
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
.
const obj = { username: 'val', pwd: { $ne: null } };
sanitizeFilter(obj);
obj; // { username: 'val', pwd: { $eq: { $ne: null } } });
Mongoose.prototype.set()
Parameters
- key «String|Object» The name of the option or a object of multiple key-value pairs
- value «String|Function|Boolean» The value of the option, unused if "key" is a object
Sets mongoose options
key
can be used a object to set multiple options at once.
If a error gets thrown for one option, other options will still be evaluated.
Example:
mongoose.set('test', value) // sets the 'test' option to `value`
mongoose.set('debug', true) // enable logging collection methods + arguments to the console/file
mongoose.set('debug', function(collectionName, methodName, ...methodArgs) {}); // use custom function to log collection methods + arguments
mongoose.set({ debug: true, autoIndex: false }); // set multiple options at once
Currently supported options are:
allowDiskUse
: Set totrue
to setallowDiskUse
to true to all aggregation operations by default.applyPluginsToChildSchemas
:true
by default. Set to false to skip applying global plugins to child schemasapplyPluginsToDiscriminators
: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.autoCreate
: Set totrue
to make Mongoose callModel.createCollection()
automatically when you create a model withmongoose.model()
orconn.model()
. This is useful for testing transactions, change streams, and other features that require the collection to exist.autoIndex
:true
by default. Set to false to disable automatic index creation for all models associated with this Mongoose instance.bufferCommands
: enable/disable mongoose's buffering mechanism for all connections and modelsbufferTimeoutMS
: If bufferCommands is on, this option sets the maximum amount of time Mongoose buffering will wait before throwing an error. If not specified, Mongoose will use 10000 (10 seconds).cloneSchemas
:false
by default. Set totrue
toclone()
all schemas before compiling into a model.debug
: Iftrue
, 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 arguments passed to the method. For example, if you wanted to replicate the default logging, you could output from the callbackMongoose: ${collectionName}.${methodName}(${methodArgs.join(', ')})
.id
: Iftrue
, adds aid
virtual to all schemas unless overwritten on a per-schema basis.timestamps.createdAt.immutable
:true
by default. Iffalse
, it will change thecreatedAt
field to beimmutable: false
which means you can update thecreatedAt
maxTimeMS
: If set, attaches maxTimeMS to every queryobjectIdGetter
:true
by default. Mongoose adds a getter to MongoDB ObjectId's called_id
that returnsthis
for convenience with populate. Set this to false to remove the getter.overwriteModels
: Set totrue
to default to overwriting models with the same name when callingmongoose.model()
, as opposed to throwing anOverwriteModelError
.returnOriginal
: Iffalse
, changes the defaultreturnOriginal
option tofindOneAndUpdate()
,findByIdAndUpdate
, andfindOneAndReplace()
to false. This is equivalent to setting thenew
option totrue
forfindOneAndX()
calls by default. Read ourfindOneAndUpdate()
tutorial for more information.runValidators
:false
by default. Set to true to enable update validators for all validators by default.sanitizeFilter
:false
by default. Set to true to enable the sanitization of the query filters against query selector injection attacks by wrapping any nested objects that have a property whose name starts with$
in a$eq
.selectPopulatedPaths
:true
by default. Set to false to opt out of Mongoose adding all fields that youpopulate()
to yourselect()
. The schema-level optionselectPopulatedPaths
overwrites this one.strict
:true
by default, may befalse
,true
, or'throw'
. Sets the default strict mode for schemas.strictQuery
: same value as 'strict' by default (true
), may befalse
,true
, or'throw'
. Sets the default strictQuery mode for schemas. The default value will be switched back tofalse
in Mongoose 7, usemongoose.set('strictQuery', false);
if you want to prepare for the change.toJSON
:{ transform: true, flattenDecimals: true }
by default. Overwrites default objects totoJSON()
, for determining how Mongoose documents get serialized byJSON.stringify()
toObject
:{ transform: true, flattenDecimals: true }
by default. Overwrites default objects totoObject()
Mongoose.prototype.setDriver()
Overwrites the current driver used by this Mongoose instance. A driver is a
Mongoose-specific interface that defines functions like find()
.
Mongoose.prototype.skipMiddlewareFunction()
Parameters
- result «any»
Use this function in pre()
middleware to skip calling the wrapped function.
Example:
schema.pre('save', function() {
// Will skip executing `save()`, but will execute post hooks as if
// `save()` had executed with the result `{ matchedCount: 0 }`
return mongoose.skipMiddlewareFunction({ matchedCount: 0 });
});
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.syncIndexes()
Parameters
- options «Object»
- options.continueOnError
«Boolean»
false
by default. If set totrue
, mongoose will not throw an error if one model syncing failed, and will return an object where the keys are the names of the models, and the values are the results/errors for each model.
Returns:
- «Promise» Returns a Promise, when the Promise resolves the value is a list of the dropped indexes.
Syncs all the indexes for the models registered with this 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.
const obj = { username: 'val', pwd: trusted({ $type: 'string', $eq: 'my secret' }) };
sanitizeFilter(obj);
// Note that `sanitizeFilter()` did not add `$eq` around `$type`.
obj; // { username: 'val', pwd: { $type: 'string', $eq: 'my secret' } });
Mongoose.prototype.version
Type:
- «property»
- Schema()
- Schema.Types
- Schema.indexTypes
- Schema.prototype.add()
- Schema.prototype.alias()
- Schema.prototype.childSchemas
- Schema.prototype.clearIndexes()
- Schema.prototype.clone()
- Schema.prototype.discriminator()
- Schema.prototype.eachPath()
- Schema.prototype.get()
- Schema.prototype.index()
- Schema.prototype.indexes()
- Schema.prototype.loadClass()
- Schema.prototype.method()
- Schema.prototype.obj
- Schema.prototype.omit()
- Schema.prototype.path()
- Schema.prototype.pathType()
- Schema.prototype.paths
- Schema.prototype.pick()
- Schema.prototype.plugin()
- Schema.prototype.post()
- Schema.prototype.pre()
- Schema.prototype.queue()
- Schema.prototype.remove()
- Schema.prototype.removeIndex()
- Schema.prototype.removeVirtual()
- Schema.prototype.requiredPaths()
- Schema.prototype.set()
- Schema.prototype.static()
- Schema.prototype.virtual()
- Schema.prototype.virtualpath()
- Schema.prototype.virtuals
- Schema.reserved
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:
const child = new Schema({ name: String });
const schema = new Schema({ name: String, age: Number, children: [child] });
const Tree = mongoose.model('Tree', schema);
// setting schema options
new Schema({ name: String }, { _id: false, autoIndex: false })
Options:
- autoIndex: bool - defaults to null (which means use the connection's autoIndex option)
- autoCreate: bool - defaults to null (which means use the connection's autoCreate option)
- bufferCommands: bool - defaults to true
- bufferTimeoutMS: number - defaults to 10000 (10 seconds). If
bufferCommands
is enabled, the amount of time Mongoose will wait for connectivity to be restablished before erroring out. - capped: bool | number | object - defaults to false
- collection: string - no default
- discriminatorKey: string - defaults to
__t
- id: bool - defaults to true
- _id: bool - defaults to true
- minimize: bool - controls document#toObject behavior when called manually - defaults to true
- read: string
- writeConcern: object - defaults to null, use to override the MongoDB server's default write concern settings
- shardKey: object - defaults to
null
- strict: bool - defaults to true
- strictQuery: bool - defaults to false
- toJSON - object - no default
- toObject - object - no default
- typeKey - string - defaults to 'type'
- validateBeforeSave - bool - defaults to
true
- versionKey: string or object - defaults to "__v"
- optimisticConcurrency: bool - defaults to false. Set to true to enable optimistic concurrency.
- collation: object - defaults to null (which means use no collation)
- timeseries: object - defaults to null (which means this schema's collection won't be a timeseries collection)
- selectPopulatedPaths: boolean - defaults to
true
- skipVersioning: object - paths to exclude from versioning
- timestamps: object or boolean - defaults to
false
. If true, Mongoose addscreatedAt
andupdatedAt
properties to your schema and manages those properties for you. - pluginTags: array of strings - defaults to
undefined
. If set and plugin called withtags
option, will only apply that plugin to schemas with a matching tag.
Options for Nested Schemas:
excludeIndexes
: bool - defaults tofalse
. Iftrue
, 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:
const mongoose = require('mongoose');
const ObjectId = mongoose.Schema.Types.ObjectId;
Types:
Using this exposed access to the Mixed
SchemaType, we can use them in our schema.
const Mixed = mongoose.Schema.Types.Mixed;
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:
const ToySchema = new Schema();
ToySchema.add({ name: 'string', color: 'string', price: 'number' });
const TurboManSchema = new Schema();
// You can also `add()` another schema and copy over all paths, virtuals,
// getters, setters, indexes, methods, and statics.
TurboManSchema.add(ToySchema).add({ year: Number });
Schema.prototype.alias()
Parameters
- path «String» real path to alias
- alias
«String|Array[String]» the path(s) to use as an alias for
path
Returns:
- «Schema» the Schema instance
Add an alias for path
. This means getting or setting the alias
is equivalent to getting or setting the path
.
Example:
const toySchema = new Schema({ n: String });
// Make 'name' an alias for 'n'
toySchema.alias('n', 'name');
const Toy = mongoose.model('Toy', toySchema);
const turboMan = new Toy({ n: 'Turbo Man' });
turboMan.name; // 'Turbo Man'
turboMan.n; // 'Turbo Man'
turboMan.name = 'Turbo Man Action Figure';
turboMan.n; // 'Turbo Man Action Figure'
await turboMan.save(); // Saves { _id: ..., n: 'Turbo Man Action Figure' }
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.clearIndexes()
Returns:
- «Schema» the Schema instance
Remove all indexes from this schema.
clearIndexes only removes indexes from your schema object. Does not affect the indexes in MongoDB.
Example:
const ToySchema = new Schema({ name: String, color: String, price: Number });
ToySchema.index({ name: 1 });
ToySchema.index({ color: 1 });
// Remove all indexes on this schema
ToySchema.clearIndexes();
ToySchema.indexes(); // []
Schema.prototype.clone()
Returns:
- «Schema» the cloned schema
Returns a deep copy of the schema
Example:
const schema = new Schema({ name: String });
const clone = schema.clone();
clone === schema; // false
clone.path('name'); // SchemaString { ... }
Schema.prototype.discriminator()
Parameters
- name «String» the name of the discriminator
- schema «Schema» the discriminated Schema
Returns:
- «Schema» the Schema instance
Inherit a Schema by applying a discriminator on an existing Schema.
Example:
const eventSchema = new mongoose.Schema({ timestamp: Date }, { discriminatorKey: 'kind' });
const clickedEventSchema = new mongoose.Schema({ element: String }, { discriminatorKey: 'kind' });
const ClickedModel = eventSchema.discriminator('clicked', clickedEventSchema);
const Event = mongoose.model('Event', eventSchema);
Event.discriminators['clicked']; // Model { clicked }
const doc = await Event.create({ kind: 'clicked', element: '#hero' });
doc.element; // '#hero'
doc instanceof ClickedModel; // true
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:
const userSchema = new Schema({ name: String, registeredAt: Date });
userSchema.eachPath((pathname, schematype) => {
// Prints twice:
// name SchemaString { ... }
// registeredAt SchemaDate { ... }
console.log(pathname, schematype);
});
Schema.prototype.get()
Parameters
- key «String» The name of the Option to get the current value for
Returns:
- «Any» the option's value
Gets a schema option.
Example:
schema.get('strict'); // true
schema.set('strict', false);
schema.get('strict'); // false
Schema.prototype.index()
Parameters
- fields
«Object» The Fields to index, with the order, available values:
1 | -1 | '2d' | '2dsphere' | 'geoHaystack' | 'hashed' | 'text'
- [options]
«Object» Options to pass to MongoDB driver's
createIndex()
function - [options.expires=null]
«String|number» Mongoose-specific syntactic sugar, uses ms to convert
expires
option into seconds for theexpireAfterSeconds
in the above link. - [options.language_override=null]
«String» Tells mongodb to use the specified field instead of
language
for parsing text indexes.
Defines an index (most likely compound) for this schema.
Example:
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:
const userSchema = new Schema({
email: { type: String, required: true, unique: true },
registeredAt: { type: Date, index: true }
});
// [ [ { email: 1 }, { unique: true, background: true } ],
// [ { registeredAt: 1 }, { background: true } ] ]
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.
function myPlugin(schema) {
for (const index of schema.indexes()) {
if (index[1].unique === undefined) {
index[1].unique = true;
}
}
}
Schema.prototype.loadClass()
Parameters
- model «Function» The Class to load
- [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:
const md5 = require('md5');
const userSchema = new Schema({ email: String });
class UserClass {
// `gravatarImage` becomes a virtual
get gravatarImage() {
const hash = md5(this.email.toLowerCase());
return `https://www.gravatar.com/avatar/${hash}`;
}
// `getProfileUrl()` becomes a document method
getProfileUrl() {
return `https://mysite.com/${this.email}`;
}
// `findByEmail()` becomes a static
static findByEmail(email) {
return this.findOne({ email });
}
}
// `schema` will now have a `gravatarImage` virtual, a `getProfileUrl()` method,
// and a `findByEmail()` static
userSchema.loadClass(UserClass);
Schema.prototype.method()
Parameters
- name «String|Object» The Method Name for a single function, or a Object of "string-function" pairs.
- [fn] «Function» The Function in a single-function definition.
Adds an instance method to documents constructed from Models compiled from this schema.
Example:
const schema = kittySchema = new Schema(..);
schema.method('meow', function () {
console.log('meeeeeoooooooooooow');
})
const Kitty = mongoose.model('Kitty', schema);
const fizz = new Kitty;
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.
schema.method({
purr: function () {}
, scratch: function () {}
});
// later
const fizz = new Kitty;
fizz.purr();
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:
const schema = new Schema({ a: String }).add({ b: String });
schema.obj; // { a: String }
Schema.prototype.omit()
Parameters
- paths «Array[String]» List of Paths to omit for the new Schema
- [options]
«Object» Options to pass to the new Schema Constructor (same as
new Schema(.., Options)
). Defaults tothis.options
if not set.
Returns:
- «Schema»
Returns a new schema that has the paths
from the original schema, minus the omitted ones.
This method is analagous to Lodash's omit()
function for Mongoose schemas.
Example:
const schema = Schema({ name: String, age: Number });
// Creates a new schema omitting the `age` path
const newSchema = schema.omit(['age']);
newSchema.path('name'); // SchemaString { ... }
newSchema.path('age'); // undefined
Schema.prototype.path()
Parameters
- path «String» The name of the Path to get / set
- [obj] «Object» The Type to set the path to, if provided the path will be SET, otherwise the path will be GET
Gets/sets schema paths.
Sets a path (if arity 2) Gets a path (if arity 1)
Example:
schema.path('name') // returns a SchemaType
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:
const s = new Schema({ name: String, nested: { foo: String } });
s.virtual('foo').get(() => 42);
s.pathType('name'); // "real"
s.pathType('nested'); // "nested"
s.pathType('foo'); // "virtual"
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:
const schema = new Schema({ name: String }, { _id: false });
schema.paths; // { name: SchemaString { ... } }
schema.add({ age: Number });
schema.paths; // { name: SchemaString { ... }, age: SchemaNumber { ... } }
Schema.prototype.pick()
Parameters
- paths «Array[String]» List of Paths to pick for the new Schema
- [options]
«Object» Options to pass to the new Schema Constructor (same as
new Schema(.., Options)
). Defaults tothis.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:
const schema = Schema({ name: String, age: Number });
// Creates a new schema with the same `name` path as `schema`,
// but no `age` path.
const newSchema = schema.pick(['name']);
newSchema.path('name'); // SchemaString { ... }
newSchema.path('age'); // undefined
Schema.prototype.plugin()
Parameters
- plugin «Function» The Plugin's callback
- [opts] «Object» Options to pass to the plugin
- [opts.deduplicate=false]
«Boolean» If true, ignore duplicate plugins (same
fn
argument using===
)
Registers a plugin for this schema.
Example:
const s = new Schema({ name: String });
s.plugin(schema => console.log(schema.path('name').path));
mongoose.model('Test', s); // Prints 'name'
Or with Options:
const s = new Schema({ name: String });
s.plugin((schema, opts) => console.log(opts.text, schema.path('name').path), { text: "Schema Path Name:" });
mongoose.model('Test', s); // Prints 'Schema Path Name: name'
Schema.prototype.post()
Parameters
- methodName «String|RegExp|Array[String]» The 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 totrue
to run on document middleware. - [options.query]
«Boolean» If
name
is a hook for both document and query middleware, set totrue
to run on query middleware. - fn «Function» callback
Defines a post hook for the document
const schema = new Schema(..);
schema.post('save', function (doc) {
console.log('this fired after a document was saved');
});
schema.post('find', function(docs) {
console.log('this fired after you ran a find query');
});
schema.post(/Many$/, function(res) {
console.log('this fired after you ran `updateMany()` or `deleteMany()`');
});
const Model = mongoose.model('Model', schema);
const m = new Model(..);
m.save(function(err) {
console.log('this fires after the `post` hook');
});
m.find(function(err, docs) {
console.log('this fires after the post find hook');
});
Schema.prototype.pre()
Parameters
- methodName «String|RegExp|Array[String]» The 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 totrue
to run on document middleware. For example, setoptions.document
totrue
to apply this hook toDocument#deleteOne()
rather thanQuery#deleteOne()
. - [options.query]
«Boolean» If
name
is a hook for both document and query middleware, set totrue
to run on query middleware. - callback «Function»
Defines a pre hook for the model.
Example:
const toySchema = new Schema({ name: String, created: Date });
toySchema.pre('save', function(next) {
if (!this.created) this.created = new Date;
next();
});
toySchema.pre('validate', function(next) {
if (this.name !== 'Woody') this.name = 'Woody';
next();
});
// Equivalent to calling `pre()` on `find`, `findOne`, `findOneAndUpdate`.
toySchema.pre(/^find/, function(next) {
console.log(this.getFilter());
});
// Equivalent to calling `pre()` on `updateOne`, `findOneAndUpdate`.
toySchema.pre(['updateOne', 'findOneAndUpdate'], function(next) {
console.log(this.getFilter());
});
toySchema.pre('deleteOne', function() {
// Runs when you call `Toy.deleteOne()`
});
toySchema.pre('deleteOne', { document: true }, function() {
// Runs when you call `doc.deleteOne()`
});
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:
schema.methods.print = function() { console.log(this); };
schema.queue('print', []); // Print the doc every one is instantiated
const Model = mongoose.model('Test', schema);
new Model({ name: 'test' }); // Prints '{"_id": ..., "name": "test" }'
Schema.prototype.remove()
Parameters
- path «String|Array» The Path(s) to remove
Returns:
- «Schema» the Schema instance
Removes the given path
(or [paths
]).
Example:
const schema = new Schema({ name: String, age: Number });
schema.remove('name');
schema.path('name'); // Undefined
schema.path('age'); // SchemaNumber { ... }
Or as a Array:
schema.remove(['name', 'age']);
schema.path('name'); // Undefined
schema.path('age'); // Undefined
Schema.prototype.removeIndex()
Parameters
- index «Object|string» name or index specification
Returns:
- «Schema» the Schema instance
Remove an index by name or index specification.
removeIndex only removes indexes from your schema object. Does not affect the indexes in MongoDB.
Example:
const ToySchema = new Schema({ name: String, color: String, price: Number });
// Add a new index on { name, color }
ToySchema.index({ name: 1, color: 1 });
// Remove index on { name, color }
// Keep in mind that order matters! `removeIndex({ color: 1, name: 1 })` won't remove the index
ToySchema.removeIndex({ name: 1, color: 1 });
// Add an index with a custom name
ToySchema.index({ color: 1 }, { name: 'my custom index name' });
// Remove index by name
ToySchema.removeIndex('my custom index name');
Schema.prototype.removeVirtual()
Parameters
- path «String|Array» The virutal path(s) to remove.
Removes the given virtual or virtuals from the schema.
Schema.prototype.requiredPaths()
Parameters
- invalidate «Boolean» Refresh the cache
Returns:
- «Array»
Returns an Array of path strings that are required by this schema.
Example:
const s = new Schema({
name: { type: String, required: true },
age: { type: String, required: true },
notes: String
});
s.requiredPaths(); // [ 'age', 'name' ]
Schema.prototype.set()
Parameters
- key «String» The name of the option to set the value to
- [value] «Object» The value to set the option to, if not passed, the option will be reset to default
Sets a schema option.
Example:
schema.set('strict'); // 'true' by default
schema.set('strict', false); // Sets 'strict' to false
schema.set('strict'); // 'false'
Schema.prototype.static()
Parameters
- name «String|Object» The Method Name for a single function, or a Object of "string-function" pairs.
- [fn] «Function» The Function in a single-function definition.
Adds static "class" methods to Models compiled from this schema.
Example:
const schema = new Schema(..);
// Equivalent to `schema.statics.findByName = function(name) {}`;
schema.static('findByName', function(name) {
return this.find({ name: name });
});
const Drink = mongoose.model('Drink', schema);
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 methods.
schema.static({
findByName: function () {..}
, findByCost: function () {..}
});
const Drink = mongoose.model('Drink', schema);
await Drink.findByName('LaCroix');
await Drink.findByCost(3);
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» The name of the Virtual
- [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» The name of the Virtual to get
Returns:
- «VirtualType,null»
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:
const schema = new Schema({});
schema.virtual('answer').get(() => 42);
console.log(schema.virtuals); // { answer: VirtualType { path: 'answer', ... } }
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.
const schema = new Schema(..);
schema.methods.init = function () {} // potentially breaking
- Connection()
- Connection.prototype.asPromise()
- Connection.prototype.client
- Connection.prototype.close()
- Connection.prototype.collection()
- Connection.prototype.collections
- Connection.prototype.config
- Connection.prototype.createCollection()
- Connection.prototype.db
- Connection.prototype.deleteModel()
- Connection.prototype.destroy()
- Connection.prototype.dropCollection()
- Connection.prototype.dropDatabase()
- Connection.prototype.get()
- Connection.prototype.getClient()
- Connection.prototype.host
- Connection.prototype.id
- Connection.prototype.model()
- Connection.prototype.modelNames()
- Connection.prototype.models
- Connection.prototype.name
- Connection.prototype.openUri()
- Connection.prototype.pass
- Connection.prototype.plugin()
- Connection.prototype.plugins
- Connection.prototype.port
- Connection.prototype.readyState
- Connection.prototype.set()
- Connection.prototype.setClient()
- Connection.prototype.startSession()
- Connection.prototype.syncIndexes
- Connection.prototype.transaction()
- Connection.prototype.useDb()
- Connection.prototype.user
- Connection.prototype.watch()
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:
const conn = await mongoose.createConnection('mongodb://127.0.0.1:27017/test').
asPromise();
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» Returns a Promise if no
callback
is given.
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» Returns a Promise if no
callback
is given.
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:
conn.model('User', new Schema({ name: String }));
console.log(conn.model('User')); // Model object
conn.deleteModel('User');
console.log(conn.model('User')); // undefined
// Usually useful in a Mocha `afterEach()` hook
afterEach(function() {
conn.deleteModel(/.+/); // Delete every model
});
Connection.prototype.destroy()
Parameters
- [force] «Boolean»
- [callback] «Function»
Destory the connection (not just a alias of .close
)
Connection.prototype.dropCollection()
Parameters
- collection «string» The collection to delete
- [callback] «Function»
Returns:
- «Promise» Returns a Promise if no
callback
is given.
Helper for dropCollection()
. Will delete the given collection, including
all documents and indexes.
Connection.prototype.dropDatabase()
Parameters
- [callback] «Function»
Returns:
- «Promise» Returns a Promise if no
callback
is given.
Helper for dropDatabase()
. Deletes the given database, including all
collections, documents, and indexes.
Example:
const conn = mongoose.createConnection('mongodb://127.0.0.1:27017/mydb');
// Deletes the entire 'mydb' database
await conn.dropDatabase();
Connection.prototype.get()
Parameters
- key «String»
Gets the value of the option key
. Equivalent to conn.options[key]
Example:
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:
const conn = await mongoose.createConnection('mongodb://127.0.0.1:27017/test').
asPromise();
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:
mongoose.createConnection('mongodb://127.0.0.1:27017/mydb').host; // "127.0.0.1"
Connection.prototype.id
Type:
- «property»
A number identifier for this connection. Used for debugging when you have multiple connections.
Example:
// The default connection has `id = 0`
mongoose.connection.id; // 0
// If you create a new connection, Mongoose increments id
const conn = mongoose.createConnection();
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.
const mongoose = require('mongoose');
const db = mongoose.createConnection(..);
db.model('Venue', new Schema(..));
const Ticket = db.model('Ticket', new Schema(..));
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:
const schema = new Schema({ name: String }, { collection: 'actor' });
// or
schema.set('collection', 'actor');
// or
const collectionName = 'actor'
const M = conn.model('Actor', schema, collectionName)
Connection.prototype.modelNames()
Returns:
- «Array[String]»
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:
const conn = mongoose.createConnection();
const Test = conn.model('Test', mongoose.Schema({ name: String }));
Object.keys(conn.models).length; // 1
conn.models.Test === Test; // true
Connection.prototype.name
Type:
- «property»
The name of the database this connection points to.
Example:
mongoose.createConnection('mongodb://127.0.0.1:27017/mydb').name; // "mydb"
Connection.prototype.openUri()
Parameters
- uri «String» The URI to connect with.
- [options]
«Object» Passed on to
MongoClient.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 afterbufferTimeoutMS
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 forserverSelectionTimeoutMS
milliseconds before erroring out. If not set, the MongoDB driver defaults to using30000
(30 seconds). - [options.heartbeatFrequencyMS]
«Number» If
useUnifiedTopology = true
, the MongoDB driver sends a heartbeat everyheartbeatFrequencyMS
to check on the status of the connection. A heartbeat is subject toserverSelectionTimeoutMS
, 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.jssocket#setTimeout()
function after the MongoDB driver successfully completes. - [options.family=0]
«Number» Passed transparently to Node.js'
dns.lookup()
function. May be either0,
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 callcreateCollection()
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:
mongoose.createConnection('mongodb://val:psw@127.0.0.1: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:
const db = mongoose.createConnection('mongodb://127.0.0.1:27017/mydb');
db.plugin(() => console.log('Applied'));
db.plugins.length; // 1
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:
const db = mongoose.createConnection('mongodb://127.0.0.1:27017/mydb');
db.plugin(() => console.log('Applied'));
db.plugins.length; // 1
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:
mongoose.createConnection('mongodb://127.0.0.1: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:
conn.on('connected', callback);
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
: SetmaxTimeMS
for all queries on this connection.- '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 callbackMongoose: ${collectionName}.${methodName}(${methodArgs.join(', ')})
.
Example:
conn.set('test', 'foo');
conn.get('test'); // 'foo'
conn.options.test; // 'foo'
Connection.prototype.setClient()
Parameters
- client «MongClient» The Client to set to be used.
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:
const client = await mongodb.MongoClient.connect('mongodb://127.0.0.1:27017/test');
const conn = mongoose.createConnection().setClient(client);
conn.getClient(); // MongoClient { ... }
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:
const session = await conn.startSession();
let doc = await Person.findOne({ name: 'Ned Stark' }, null, { session });
await doc.remove();
// `doc` will always be null, even if reading from a replica set
// secondary. Without causal consistency, it is possible to
// get a doc back from the below query if the query reads from a
// secondary that is experiencing replication lag.
doc = await Person.findOne({ name: 'Ned Stark' }, null, { session, readPreference: 'secondary' });
Connection.prototype.syncIndexes
Parameters
- [options] «Object»
- [options.continueOnError]
«Boolean»
false
by default. If set totrue
, mongoose will not throw an error if one model syncing failed, and will return an object where the keys are the names of the models, and the values are the results/errors for each model.
Returns:
- «Promise<Object>» Returns a Promise, when the Promise resolves the value is a list of the dropped indexes.
Type:
- «property»
Syncs all the indexes for the models registered with this connection.
Connection.prototype.transaction()
Parameters
- fn «Function» Function to execute in a transaction
- [options] «[object Object]» 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:
const doc = new Person({ name: 'Will Riker' });
await db.transaction(async function setRank(session) {
doc.rank = 'Captain';
await doc.save({ session });
doc.isNew; // false
// Throw an error to abort the transaction
throw new Error('Oops!');
},{ readPreference: 'primary' }).catch(() => {});
// true, `transaction()` reset the document's state because the
// transaction was aborted.
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.
Example:
// Connect to `initialdb` first
const conn = await mongoose.createConnection('mongodb://127.0.0.1:27017/initialdb').asPromise();
// Creates an un-cached connection to `mydb`
const db = conn.useDb('mydb');
// Creates a cached connection to `mydb2`. All calls to `conn.useDb('mydb2', { useCache: true })` will return the same
// connection instance as opposed to creating a new connection instance
const db2 = conn.useDb('mydb2', { useCache: true });
Connection.prototype.user
Type:
- «property»
The username specified in the URI
Example:
mongoose.createConnection('mongodb://val:psw@127.0.0.1:27017/mydb').user; // "val"
Connection.prototype.watch()
Parameters
- [pipeline] «Array»
- [options]
«Object» passed without changes to the MongoDB driver's
Db#watch()
function
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:
const User = conn.model('User', new Schema({ name: String }));
const changeStream = conn.watch().on('change', data => console.log(data));
// Triggers a 'change' event on the change stream.
await User.create({ name: 'test' });
- Document.prototype.$assertPopulated()
- Document.prototype.$clone()
- Document.prototype.$errors
- Document.prototype.$getAllSubdocs()
- Document.prototype.$getPopulatedDocs()
- Document.prototype.$ignore()
- Document.prototype.$inc()
- Document.prototype.$init()
- Document.prototype.$isDefault()
- Document.prototype.$isDeleted()
- Document.prototype.$isEmpty()
- Document.prototype.$isModified()
- Document.prototype.$isNew
- Document.prototype.$locals
- Document.prototype.$markValid()
- Document.prototype.$op
- Document.prototype.$parent()
- Document.prototype.$populated()
- Document.prototype.$session()
- Document.prototype.$set()
- Document.prototype.$timestamps()
- Document.prototype.$validate()
- Document.prototype.$where
- Document.prototype.depopulate()
- Document.prototype.directModifiedPaths()
- Document.prototype.equals()
- Document.prototype.errors
- Document.prototype.get()
- Document.prototype.getChanges()
- Document.prototype.id
- Document.prototype.init()
- Document.prototype.inspect()
- Document.prototype.invalidate()
- Document.prototype.isDirectModified()
- Document.prototype.isDirectSelected()
- Document.prototype.isInit()
- Document.prototype.isModified()
- Document.prototype.isNew
- Document.prototype.isSelected()
- Document.prototype.markModified()
- Document.prototype.modifiedPaths()
- Document.prototype.overwrite()
- Document.prototype.parent()
- Document.prototype.populate()
- Document.prototype.populated()
- Document.prototype.replaceOne()
- Document.prototype.save()
- Document.prototype.schema
- Document.prototype.set()
- Document.prototype.toJSON()
- Document.prototype.toObject()
- Document.prototype.toString()
- Document.prototype.unmarkModified()
- Document.prototype.update()
- Document.prototype.updateOne()
- Document.prototype.validate()
- Document.prototype.validateSync()
Document.prototype.$assertPopulated()
Parameters
- path
«String|Array[String]» path or array of paths to check.
$assertPopulated
throws if any of the given paths is not populated. - [values]
«Object» optional values to
$set()
. Convenient if you want to manually populate a path and assert that the path was populated in 1 call.
Returns:
- «Document» this
Throws an error if a given path is not populated
Example:
const doc = await Model.findOne().populate('author');
doc.$assertPopulated('author'); // does not throw
doc.$assertPopulated('other path'); // throws an error
// Manually populate and assert in one call. The following does
// `doc.$set({ likes })` before asserting.
doc.$assertPopulated('likes', { likes });
Document.prototype.$clone()
Returns:
- «Document» a copy of this document
Returns a copy of this document with a deep clone of _doc
and $__
.
Document.prototype.$errors
Type:
- «property»
Hash containing current validation $errors.
Document.prototype.$getAllSubdocs()
Returns:
- «Array»
Get all subdocs (by bfs)
Document.prototype.$getPopulatedDocs()
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.$ignore()
Parameters
- path «String» the path to ignore
Don't run validation on this path or persist changes to this path.
Example:
doc.foo = null;
doc.$ignore('foo');
doc.save(); // changes to foo will not be persisted and validators won't be run
Document.prototype.$inc()
Parameters
- path «String|Array» path or paths to update
- val
«Number» increment
path
by this value
Returns:
- «Document» this
Increments the numeric value at path
by the given val
.
When you call save()
on this document, Mongoose will send a
$inc
as opposed to a $set
.
Example:
const schema = new Schema({ counter: Number });
const Test = db.model('Test', schema);
const doc = await Test.create({ counter: 0 });
doc.$inc('counter', 2);
await doc.save(); // Sends a `{ $inc: { counter: 2 } }` to MongoDB
doc.counter; // 2
doc.counter += 2;
await doc.save(); // Sends a `{ $set: { counter: 2 } }` to MongoDB
Document.prototype.$init()
Alias for .init
Document.prototype.$isDefault()
Parameters
- [path] «String»
Returns:
- «Boolean»
Checks if a path is set to its default.
Example:
MyModel = mongoose.model('test', { name: { type: String, default: 'Val '} });
const m = new MyModel();
m.$isDefault('name'); // true
Document.prototype.$isDeleted()
Parameters
- [val] «Boolean» optional, overrides whether mongoose thinks the doc is deleted
Returns:
- «Boolean,Document» whether mongoose thinks this doc is deleted.
Getter/setter, determines whether the document was removed or not.
Example:
const product = await product.remove();
product.$isDeleted(); // true
product.remove(); // no-op, doesn't send anything to the db
product.$isDeleted(false);
product.$isDeleted(); // false
product.remove(); // will execute a remove against the db
Document.prototype.$isEmpty()
Parameters
- [path] «String»
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:
const schema = new Schema({ nested: { foo: String } });
const Model = mongoose.model('Test', schema);
const doc = new Model({});
doc.$isEmpty('nested'); // true
doc.nested.$isEmpty(); // true
doc.nested.foo = 'bar';
doc.$isEmpty('nested'); // false
doc.nested.$isEmpty(); // false
Document.prototype.$isModified()
Alias of .isModified
Document.prototype.$isNew
Type:
- «property»
Boolean flag specifying if the document is new. If you create a document
using new
, this document will be considered "new". $isNew
is how
Mongoose determines whether save()
should use insertOne()
to create
a new document or updateOne()
to update an existing document.
Example:
const user = new User({ name: 'John Smith' });
user.$isNew; // true
await user.save(); // Sends an `insertOne` to MongoDB
On the other hand, if you load an existing document from the database
using findOne()
or another query operation,
$isNew
will be false.
Example:
const user = await User.findOne({ name: 'John Smith' });
user.$isNew; // false
Mongoose sets $isNew
to false
immediately after save()
succeeds.
That means Mongoose sets $isNew
to false before post('save')
hooks run.
In post('save')
hooks, $isNew
will be false
if save()
succeeded.
Example:
userSchema.post('save', function() {
this.$isNew; // false
});
await User.create({ name: 'John Smith' });
For subdocuments, $isNew
is true if either the parent has $isNew
set,
or if you create a new subdocument.
Example:
// Assume `Group` has a document array `users`
const group = await Group.findOne();
group.users[0].$isNew; // false
group.users.push({ name: 'John Smith' });
group.users[1].$isNew; // true
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:
schema.pre('save', function() {
// Mongoose will set `isNew` to `false` if `save()` succeeds
this.$locals.wasNew = this.isNew;
});
schema.post('save', function() {
// Prints true if `isNew` was set before `save()`
console.log(this.$locals.wasNew);
});
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:
const doc = new Model({ name: 'test' });
doc.$op; // null
const promise = doc.save();
doc.$op; // 'save'
await promise;
doc.$op; // null
Document.prototype.$parent()
Returns:
- «Document»
Alias for parent()
. If this document is a subdocument or populated
document, returns the document's parent. Returns undefined
otherwise.
Document.prototype.$populated()
Alias of .populated
.
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:
const session = MyModel.startSession();
const doc = await MyModel.findOne().session(session);
doc.$session() === session; // true
doc.$session(null);
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|[object Object]» optionally specify a type for "on-the-fly" attributes
- [options] «Object» optionally specify options that modify the behavior of the set
- [options.merge=false]
«Boolean» if true, setting a nested path will merge existing values rather than overwrite the whole object. So
doc.set('nested', { a: 1, b: 2 })
becomesdoc.set('nested.a', 1); doc.set('nested.b', 2);
Returns:
- «Document» this
Alias for set()
, used internally to avoid conflicts
Document.prototype.$timestamps()
Parameters
- [value] «Boolean» overwrite the current session
Returns:
- «Document,boolean,undefined,void» When used as a getter (no argument), a boolean will be returned indicating the timestamps option state or if unset "undefined" will be used, otherwise will return "this"
Getter/setter around whether this document will apply timestamps by
default when using save()
and bulkSave()
.
Example:
const TestModel = mongoose.model('Test', new Schema({ name: String }, { timestamps: true }));
const doc = new TestModel({ name: 'John Smith' });
doc.$timestamps(); // true
doc.$timestamps(false);
await doc.save(); // Does **not** apply timestamps
Document.prototype.$validate()
Alias of .validate
Document.prototype.$where
Type:
- «property»
Set this property to add additional query filters when Mongoose saves this document and isNew
is false.
Example:
// Make sure `save()` never updates a soft deleted document.
schema.pre('save', function() {
this.$where = { isDeleted: false };
});
Document.prototype.depopulate()
Parameters
- [path] «String|Array[String]» Specific Path to depopulate. If unset, will depopulate all paths on the Document. Or multiple space-delimited paths.
Returns:
- «Document» this
Takes a populated field and returns it to its unpopulated state.
Example:
Model.findOne().populate('author').exec(function (err, doc) {
console.log(doc.author.name); // Dr.Seuss
console.log(doc.depopulate('author'));
console.log(doc.author); // '5144cf8050f071d979c118a7'
})
If the path was not provided, then all populated fields are returned to their unpopulated state.
Document.prototype.directModifiedPaths()
Returns:
- «Array[String]»
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:
const schema = new Schema({ foo: String, nested: { bar: String } });
const Model = mongoose.model('Test', schema);
await Model.create({ foo: 'original', nested: { bar: 'original' } });
const doc = await Model.findOne();
doc.nested.bar = 'modified';
doc.directModifiedPaths(); // ['nested.bar']
doc.modifiedPaths(); // ['nested', 'nested.bar']
Document.prototype.equals()
Parameters
- [doc] «Document» a document to compare. If falsy, will always return "false".
Returns:
- «Boolean»
Returns true if this document is equal to another document.
Documents are considered equal when they have matching _id
s, 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|[object Object]» 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:
- «Any»
Returns the value of a path.
Example:
// path
doc.get('age') // 47
// dynamic casting to a string
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:
const userSchema = new Schema({
name: String,
age: Number,
country: String
});
const User = mongoose.model('User', userSchema);
const user = await User.create({
name: 'Hafez',
age: 25,
country: 'Egypt'
});
// returns an empty object, no changes happened yet
user.getChanges(); // { }
user.country = undefined;
user.age = 26;
user.getChanges(); // { $set: { age: 26 }, { $unset: { country: 1 } } }
await user.save();
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.
new Schema({ name: String }, { id: false });
Document.prototype.init()
Parameters
- doc «Object» document returned by mongo
- [opts] «Object»
- [fn] «Function»
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()
Returns:
- «String»
Helper for console.log
Document.prototype.invalidate()
Parameters
- path
«String» the field to invalidate. For array elements, use the
array.i.field
syntax, wherei
is the 0-based index in the array. - err
«String|Error» the error which states the reason
path
was invalid - val «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.
doc.invalidate('size', 'must be less than 20', 14);
doc.validate(function (err) {
console.log(err)
// prints
{ message: 'Validation failed',
name: 'ValidationError',
errors:
{ size:
{ message: 'must be less than 20',
name: 'ValidatorError',
path: 'size',
type: 'user defined',
value: 14 } } }
})
Document.prototype.isDirectModified()
Parameters
- [path] «String|Array[String]»
Returns:
- «Boolean»
Returns true if path
was directly set and modified, else false.
Example:
doc.set('documents.0.title', 'changed');
doc.isDirectModified('documents.0.title') // true
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:
Thing.findOne().select('nested.name').exec(function (err, doc) {
doc.isDirectSelected('nested.name') // true
doc.isDirectSelected('nested.otherName') // false
doc.isDirectSelected('nested') // false
})
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
- [options] «Object»
- [options.ignoreAtomics=false]
«Boolean» If true, doesn't return true if path is underneath an array that was modified with atomic operations like
push()
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:
doc.set('documents.0.title', 'changed');
doc.isModified() // true
doc.isModified('documents') // true
doc.isModified('documents.0.title') // true
doc.isModified('documents otherProp') // true
doc.isDirectModified('documents') // false
Document.prototype.isNew
Type:
- «property»
Legacy alias for $isNew
.
Document.prototype.isSelected()
Parameters
- path «String|Array[String]»
Returns:
- «Boolean»
Checks if path
was selected in the source query which initialized this document.
Example:
const doc = await Thing.findOne().select('name');
doc.isSelected('name') // true
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:
doc.mixed.type = 'changed';
doc.markModified('mixed.type');
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 containcolors.primary
. If true,modifiedPaths()
will return an array that containscolors.primary
.
Returns:
- «Array[String]»
Returns the list of paths that have been modified.
Document.prototype.overwrite()
Parameters
- obj «Object» the object to overwrite this document with
Returns:
- «Document» this
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()
Returns:
- «Document»
If this document is a subdocument or populated document, returns the document's parent. Returns the original document if there is no parent.
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.populate=null] «string|PopulateOptions» Recursively populate paths in the populated documents. See deep populate docs.
- [options.retainNullValues=false]
«boolean» by default, Mongoose removes null and undefined values from populated arrays. Use this option to make
populate()
retainnull
andundefined
array entries. - [options.getters=false]
«boolean» if true, Mongoose will call any getters defined on the
localField
. By default, Mongoose gets the raw value oflocalField
. For example, you would need to set this option totrue
if you wanted to add alowercase
getter to yourlocalField
. - [options.clone=false]
«boolean» When you do
BlogPost.find().populate('author')
, blog posts with the same author will share 1 copy of anauthor
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
andlean
. - [callback] «Function» Callback
Returns:
- «Promise,null» Returns a Promise if no
callback
is given.
Populates paths on an existing document.
Example:
// Given a document, `populate()` lets you pull in referenced docs
await doc.populate([
'stories',
{ path: 'fans', sort: { name: -1 } }
]);
doc.populated('stories'); // Array of ObjectIds
doc.stories[0].title; // 'Casino Royale'
doc.populated('fans'); // Array of ObjectIds
// If the referenced doc has been deleted, `populate()` will
// remove that entry from the array.
await Story.delete({ title: 'Casino Royale' });
await doc.populate('stories'); // Empty array
// You can also pass additional query options to `populate()`,
// like projections:
await doc.populate('fans', '-email');
doc.fans[0].email // undefined because of 2nd param `select`
Document.prototype.populated()
Parameters
- path «String»
- [val] «Any»
- [options] «Object»
Returns:
- «Array,ObjectId,Number,Buffer,String,undefined,void»
Gets _id(s) used during population of the given path
.
Example:
const doc = await Model.findOne().populate('author');
console.log(doc.author.name); // Dr.Seuss
console.log(doc.populated('author')); // '5144cf8050f071d979c118a7'
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:
- same as in Model.replaceOne
Document.prototype.save()
Parameters
- [options] «Object» options optional options
- [options.session=null] «Session» the session associated with this save operation. If not specified, defaults to the document's associated session.
- [options.safe]
«Object» (DEPRECATED) overrides schema's safe option. Use the
w
option instead. - [options.validateBeforeSave] «Boolean» set to false to save without validating.
- [options.validateModifiedOnly=false]
«Boolean» If
true
, Mongoose will only validate modified paths, as opposed to modified paths andrequired
paths. - [options.w]
«Number|String» set the write concern. Overrides the schema-level
writeConcern
option - [options.j]
«Boolean» set to true for MongoDB to wait until this
save()
has been journaled before resolving the returned promise. Overrides the schema-levelwriteConcern
option - [options.wtimeout]
«Number» sets a timeout for the write concern. Overrides the schema-level
writeConcern
option. - [options.checkKeys=true]
«Boolean» the MongoDB driver prevents you from saving keys that start with '$' or contain '.' by default. Set this option to
false
to skip that check. See restrictions on field names - [options.timestamps=true]
«Boolean» if
false
and timestamps are enabled, skip timestamps for thissave()
. - [fn] «Function» optional callback
Returns:
- «Promise,undefined,void» 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:
product.sold = Date.now();
product = await product.save();
If save is successful, the returned promise will fulfill with the document saved.
Example:
const newProduct = await product.save();
newProduct === product; // true
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|[object Object]» optionally specify a type for "on-the-fly" attributes
- [options] «Object» optionally specify options that modify the behavior of the set
Returns:
- «Document» this
Sets the value of a path, or many paths.
Alias for .$set
.
Example:
// path, value
doc.set(path, value)
// object
doc.set({
path : value
, path2 : {
path : value
}
})
// on-the-fly cast to number
doc.set(path, value, Number)
// on-the-fly cast to string
doc.set(path, value, String)
// changing strict mode behavior
doc.set(path, value, { strict: false });
Document.prototype.toJSON()
Parameters
- options «Object»
- [options.flattenMaps=true]
«Boolean» if true, convert Maps to POJOs. Useful if you want to
JSON.stringify()
the result.
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.
schema.set('toJSON', { virtuals: true });
There is one difference between toJSON()
and toObject()
options.
When you call toJSON()
, the flattenMaps
option defaults to true
, because JSON.stringify()
doesn't convert maps to objects by default.
When you call toObject()
, the flattenMaps
option is false
by default.
See schema options for more information on setting toJSON
option defaults.
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 setoptions.aliases = false
to skip applying aliases. This option is a no-op ifoptions.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 oftoObject()
. - [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.
- If true, omits fields that are excluded in this document's projection. Unless you specified a projection, this will omit any field that has
Returns:
- «Object» js object (not a POJO)
Converts this document into a plain-old JavaScript object (POJO).
Buffers are converted to instances of mongodb.Binary for proper storage.
Getters/Virtuals
Example of only applying path getters
doc.toObject({ getters: true, virtuals: false })
Example of only applying virtual getters
doc.toObject({ virtuals: true })
Example of applying both path and virtual getters
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.
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
function (doc, ret, options) {}
doc
The mongoose document which is being convertedret
The plain object representation which has been convertedoptions
The options in use (either schema options or the options passed inline)
Example:
// specify the transform schema option
if (!schema.options.toObject) schema.options.toObject = {};
schema.options.toObject.transform = function (doc, ret, options) {
// remove the _id of every document before returning the result
delete ret._id;
return ret;
}
// without the transformation in the schema
doc.toObject(); // { _id: 'anId', name: 'Wreck-it Ralph' }
// with the transformation
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:
if (!schema.options.toObject) schema.options.toObject = {};
schema.options.toObject.transform = function (doc, ret, options) {
return { movie: ret.name }
}
// without the transformation in the schema
doc.toObject(); // { _id: 'anId', name: 'Wreck-it Ralph' }
// with the transformation
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:
function xform (doc, ret, options) {
return { inline: ret.name, custom: true }
}
// pass the transform as an inline option
doc.toObject({ transform: xform }); // { inline: 'Wreck-it Ralph', custom: true }
If you want to skip transformations, use transform: false
:
schema.options.toObject.hide = '_id';
schema.options.toObject.transform = function (doc, ret, options) {
if (options.hide) {
options.hide.split(' ').forEach(function (prop) {
delete ret[prop];
});
}
return ret;
}
const doc = new Doc({ _id: 'anId', secret: 47, name: 'Wreck-it Ralph' });
doc.toObject(); // { secret: 47, name: 'Wreck-it Ralph' }
doc.toObject({ hide: 'secret _id', transform: false });// { _id: 'anId', secret: 47, name: 'Wreck-it Ralph' }
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 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.
const memberSchema = new Schema({ name: String, email: String });
const groupSchema = new Schema({ members: [memberSchema], name: String, email });
const Group = mongoose.model('Group', groupSchema);
const doc = new Group({
name: 'Engineering',
email: 'dev@mongoosejs.io',
members: [{ name: 'Val', email: 'val@mongoosejs.io' }]
});
// Removes `email` from both top-level document **and** array elements
// { name: 'Engineering', members: [{ name: 'Val' }] }
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()
Returns:
- «String»
Helper for console.log
Document.prototype.unmarkModified()
Parameters
- path «String» the path to unmark modified
Clears the modified state on the specified path.
Example:
doc.foo = 'bar';
doc.unmarkModified('foo');
doc.save(); // changes to foo will not be persisted
Document.prototype.update()
Parameters
- ...ops «Object»
- [options] «Object»
- [callback] «Function»
Returns:
- «Query» this
Sends an update command with this document _id
as the query selector.
Example:
weirdCar.update({ $inc: { wheels:1 } }, { w: 1 }, callback);
Valid options:
- same as in Model.update
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:
weirdCar.updateOne({$inc: {wheels:1}}, { w: 1 }, callback);
Valid options:
- same as in Model.updateOne
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» Returns a Promise if no
callback
is given.
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:
doc.validate(function (err) {
if (err) handleError(err);
else // validation passed
});
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 andrequired
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,void» 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:
const err = doc.validateSync();
if (err) {
handleError(err);
} else {
// validation passed
}
- Model()
- Model.$where()
- Model.aggregate()
- Model.applyDefaults()
- Model.bulkSave
- Model.bulkWrite()
- Model.castObject()
- Model.cleanIndexes()
- Model.count()
- Model.countDocuments()
- Model.create()
- Model.createCollection()
- Model.createIndexes()
- Model.db
- Model.deleteMany()
- Model.deleteOne()
- Model.diffIndexes()
- Model.discriminator()
- Model.distinct()
- Model.ensureIndexes()
- Model.estimatedDocumentCount()
- Model.events
- Model.exists()
- Model.find()
- Model.findById()
- Model.findByIdAndDelete()
- Model.findByIdAndRemove()
- Model.findByIdAndUpdate()
- Model.findOne()
- Model.findOneAndDelete()
- Model.findOneAndRemove()
- Model.findOneAndReplace()
- Model.findOneAndUpdate()
- Model.hydrate()
- Model.init()
- Model.insertMany()
- Model.inspect()
- Model.listIndexes()
- Model.mapReduce()
- Model.populate()
- Model.prototype.$model()
- Model.prototype.$remove()
- Model.prototype.$where
- Model.prototype.base
- Model.prototype.baseModelName
- Model.prototype.collection
- Model.prototype.collection
- Model.prototype.db
- Model.prototype.deleteOne()
- Model.prototype.discriminators
- Model.prototype.increment()
- Model.prototype.model()
- Model.prototype.modelName
- Model.prototype.remove()
- Model.prototype.save()
- Model.remove()
- Model.replaceOne()
- Model.schema
- Model.startSession()
- Model.syncIndexes()
- Model.translateAliases()
- Model.update()
- Model.updateMany()
- Model.updateOne()
- Model.validate()
- Model.watch()
- Model.where()
Model()
Parameters
- doc «Object» values for initial set
- [fields] «Object» optional object containing the fields that were selected in the query which returned this document. You do not need to set this parameter to ensure Mongoose handles your query projection.
- [skipId=false]
«Boolean» optional boolean. If true, mongoose doesn't add an
_id
field to the document.
A Model is a class that's your primary tool for interacting with MongoDB. An instance of a Model is called a Document.
In Mongoose, the term "Model" refers to subclasses of the mongoose.Model
class. You should not use the mongoose.Model
class directly. The
mongoose.model()
and
connection.model()
functions
create subclasses of mongoose.Model
as shown below.
Example:
// `UserModel` is a "Model", a subclass of `mongoose.Model`.
const UserModel = mongoose.model('User', new Schema({ name: String }));
// You can use a Model to create new documents using `new`:
const userDoc = new UserModel({ name: 'Foo' });
await userDoc.save();
// You also use a model to create queries:
const userFromDb = await UserModel.findOne({ name: 'Foo' });
Model.$where()
Parameters
- argument «String|Function» is a javascript string or anonymous function
Returns:
- «Query»
Creates a Query
and specifies a $where
condition.
Sometimes you need to query for things in mongodb using a JavaScript expression. You can do so via find({ $where: javascript })
, or you can use the mongoose shortcut method $where via a Query chain or from your mongoose Model.
Blog.$where('this.username.indexOf("val") !== -1').exec(function (err, docs) {});
Model.aggregate()
Parameters
- [pipeline] «Array» aggregation pipeline as an array of objects
- [options] «Object» aggregation options
- [callback] «Function»
Returns:
- «Aggregate»
Performs aggregations on the models collection.
If a callback
is passed, the aggregate
is executed and a Promise
is returned. If a callback is not passed, the aggregate
itself is returned.
This function triggers the following middleware.
aggregate()
Example:
// Find the max balance of all accounts
const res = await Users.aggregate([
{ $group: { _id: null, maxBalance: { $max: '$balance' }}},
{ $project: { _id: 0, maxBalance: 1 }}
]);
console.log(res); // [ { maxBalance: 98000 } ]
// Or use the aggregation pipeline builder.
const res = await Users.aggregate().
group({ _id: null, maxBalance: { $max: '$balance' } }).
project('-id maxBalance').
exec();
console.log(res); // [ { maxBalance: 98 } ]
Note:
- Mongoose does not cast aggregation pipelines to the model's schema because
$project
and$group
operators allow redefining the "shape" of the documents at any stage of the pipeline, which may leave documents in an incompatible format. You can use the mongoose-cast-aggregation plugin to enable minimal casting for aggregation pipelines. - The documents returned are plain javascript objects, not mongoose documents (since any shape of document can be returned).
More About Aggregations:
Model.applyDefaults()
Parameters
- obj «Object|Document» object or document to apply defaults on
Apply defaults to the given document or POJO.
Model.bulkSave
Parameters
- documents «Array<Document>»
- [options]
«Object» options passed to the underlying
bulkWrite()
- [options.timestamps]
«Boolean» defaults to
null
, when set to false, mongoose will not add/update timestamps to the documents. - [options.session=null] «ClientSession» The session associated with this bulk write. See transactions docs.
- [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
Type:
- «property»
takes an array of documents, gets the changes and inserts/updates documents in the database according to whether or not the document is new, or whether it has changes or not.
bulkSave
uses bulkWrite
under the hood, so it's mostly useful when dealing with many documents (10K+)
Model.bulkWrite()
Parameters
- ops «Array»
- [ops.insertOne.document] «Object» The document to insert
- [ops.updateOne.filter] «Object» Update the first document that matches this filter
- [ops.updateOne.update] «Object» An object containing update operators
- [ops.updateOne.upsert=false] «Boolean» If true, insert a doc if none match
- [ops.updateOne.timestamps=true] «Boolean» If false, do not apply timestamps to the operation
- [ops.updateOne.collation] «Object» The MongoDB collation to use
- [ops.updateOne.arrayFilters]
«Array» The array filters used in
update
- [ops.updateMany.filter] «Object» Update all the documents that match this filter
- [ops.updateMany.update] «Object» An object containing update operators
- [ops.updateMany.upsert=false]
«Boolean» If true, insert a doc if no documents match
filter
- [ops.updateMany.timestamps=true] «Boolean» If false, do not apply timestamps to the operation
- [ops.updateMany.collation] «Object» The MongoDB collation to use
- [ops.updateMany.arrayFilters]
«Array» The array filters used in
update
- [ops.deleteOne.filter] «Object» Delete the first document that matches this filter
- [ops.deleteMany.filter] «Object» Delete all documents that match this filter
- [ops.replaceOne.filter] «Object» Replace the first document that matches this filter
- [ops.replaceOne.replacement] «Object» The replacement document
- [ops.replaceOne.upsert=false]
«Boolean» If true, insert a doc if no documents match
filter
- [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.skipValidation=false]
«Boolean» Set to true to skip Mongoose schema validation on bulk write operations. Mongoose currently runs validation on
insertOne
andreplaceOne
operations by default. - [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. - [options.throwOnValidationError=false]
«Boolean» If true and
ordered: false
, throw an error if one of the operations failed validation, but all valid operations completed successfully. - [callback]
«Function» callback
function(error, bulkWriteOpResult) {}
Returns:
- «Promise» resolves to a
BulkWriteOpResult
if the operation succeeds
Sends multiple insertOne
, updateOne
, updateMany
, replaceOne
,
deleteOne
, and/or deleteMany
operations to the MongoDB server in one
command. This is faster than sending multiple independent operations (e.g.
if you use create()
) because with bulkWrite()
there is only one round
trip to MongoDB.
Mongoose will perform casting on all operations you provide.
This function does not trigger any middleware, neither save()
, nor update()
.
If you need to trigger
save()
middleware for every document use create()
instead.
Example:
Character.bulkWrite([
{
insertOne: {
document: {
name: 'Eddard Stark',
title: 'Warden of the North'
}
}
},
{
updateOne: {
filter: { name: 'Eddard Stark' },
// If you were using the MongoDB driver directly, you'd need to do
// `update: { $set: { title: ... } }` but mongoose adds $set for
// you.
update: { title: 'Hand of the King' }
}
},
{
deleteOne: {
filter: { name: 'Eddard Stark' }
}
}
]).then(res => {
// Prints "1 1 1"
console.log(res.insertedCount, res.modifiedCount, res.deletedCount);
});
The supported operations are:
insertOne
updateOne
updateMany
deleteOne
deleteMany
replaceOne
Model.castObject()
Parameters
- obj «Object» object or document to cast
- options «Object» options passed to castObject
- options.ignoreCastErrors
«Boolean» If set to
true
will not throw a ValidationError and only return values that were successfully cast.
Cast the given POJO to the model's schema
Example:
const Test = mongoose.model('Test', Schema({ num: Number }));
const obj = Test.castObject({ num: '42' });
obj.num; // 42 as a number
Test.castObject({ num: 'not a number' }); // Throws a ValidationError
Model.cleanIndexes()
Parameters
- [callback] «Function» optional callback
Returns:
- «Promise,undefined,void» Returns
undefined
if callback is specified, returns a promise if no callback.
Deletes all indexes that aren't defined in this model's schema. Used by
syncIndexes()
.
The returned promise resolves to a list of the dropped indexes' names as an array
Model.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:
const count = await Adventure.count({ type: 'jungle' });
console.log('there are %d jungle adventures', count);
Model.countDocuments()
Parameters
- filter «Object»
- [callback] «Function»
Returns:
- «Query»
Counts number of documents matching filter
in a database collection.
Example:
Adventure.countDocuments({ type: 'jungle' }, function (err, count) {
console.log('there are %d jungle adventures', count);
});
If you want to count all documents in a large collection,
use the estimatedDocumentCount()
function
instead. If you call countDocuments({})
, MongoDB will always execute
a full collection scan and not use any indexes.
The countDocuments()
function is similar to count()
, but there are a
few operators that countDocuments()
does not support.
Below are the operators that count()
supports but countDocuments()
does not,
and the suggested replacement:
$where
:$expr
$near
:$geoWithin
with$center
$nearSphere
:$geoWithin
with$centerSphere
Model.create()
Parameters
- docs «Array|Object» Documents to insert, as a spread or array
- [options]
«Object» Options passed down to
save()
. To specifyoptions
,docs
must be an array, not a spread. See Model.save for available options. - [callback] «Function» callback
Returns:
- «Promise»
Shortcut for saving one or more documents to the database.
MyModel.create(docs)
does new MyModel(doc).save()
for every doc in
docs.
This function triggers the following middleware.
save()
Example:
// Insert one new `Character` document
await Character.create({ name: 'Jean-Luc Picard' });
// Insert multiple new `Character` documents
await Character.create([{ name: 'Will Riker' }, { name: 'Geordi LaForge' }]);
// Create a new character within a transaction. Note that you **must**
// pass an array as the first parameter to `create()` if you want to
// specify options.
await Character.create([{ name: 'Jean-Luc Picard' }], { session });
Model.createCollection()
Parameters
- [options] «Object» see MongoDB driver docs
- [callback] «Function»
Create the collection for this model. By default, if no indexes are specified, mongoose will not create the collection for the model until any documents are created. Use this method to create the collection explicitly.
Note 1: You may need to call this before starting a transaction See https://www.mongodb.com/docs/manual/core/transactions/#transactions-and-operations
Note 2: You don't have to call this if your schema contains index or unique field.
In that case, just use Model.init()
Example:
const userSchema = new Schema({ name: String })
const User = mongoose.model('User', userSchema);
User.createCollection().then(function(collection) {
console.log('Collection is created!');
});
Model.createIndexes()
Parameters
- [options] «Object» internal options
- [cb] «Function» optional callback
Returns:
- «Promise»
Similar to ensureIndexes()
, except for it uses the createIndex
function.
Model.db
Type:
- «property»
Connection instance the model uses.
Model.deleteMany()
Parameters
- conditions «Object»
- [options]
«Object» optional see
Query.prototype.setOptions()
- [callback] «Function»
Returns:
- «Query»
Deletes all of the documents that match conditions
from the collection.
It returns an object with the property deletedCount
containing the number of documents deleted.
Behaves like remove()
, but deletes all documents that match conditions
regardless of the single
option.
Example:
await Character.deleteMany({ name: /Stark/, age: { $gte: 18 } }); // returns {deletedCount: x} where x is the number of documents deleted.
Note:
This function triggers deleteMany
query hooks. Read the
middleware docs to learn more.
Model.deleteOne()
Parameters
- conditions «Object»
- [options]
«Object» optional see
Query.prototype.setOptions()
- [callback] «Function»
Returns:
- «Query»
Deletes the first document that matches conditions
from the collection.
It returns an object with the property deletedCount
indicating how many documents were deleted.
Behaves like remove()
, but deletes at most one document regardless of the
single
option.
Example:
await Character.deleteOne({ name: 'Eddard Stark' }); // returns {deletedCount: 1}
Note:
This function triggers deleteOne
query hooks. Read the
middleware docs to learn more.
Model.diffIndexes()
Parameters
- [options] «Object»
- [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 thename
parameter. - [options.clone=true]
«Boolean» By default,
discriminator()
clones the givenschema
. Set tofalse
to skip cloning. - [options.overwriteModels=false] «Boolean» by default, Mongoose does not allow you to define a discriminator with the same name as another discriminator. Set this to allow overwriting discriminators with the same name.
- [options.mergeHooks=true]
«Boolean» By default, Mongoose merges the base schema's hooks with the discriminator schema's hooks. Set this option to
false
to make Mongoose use the discriminator schema's hooks instead. - [options.mergePlugins=true]
«Boolean» By default, Mongoose merges the base schema's plugins with the discriminator schema's plugins. Set this option to
false
to make Mongoose use the discriminator schema's plugins instead.
Returns:
- «Model» The newly created discriminator model
Adds a discriminator type.
Example:
function BaseSchema() {
Schema.apply(this, arguments);
this.add({
name: String,
createdAt: Date
});
}
util.inherits(BaseSchema, Schema);
const PersonSchema = new BaseSchema();
const BossSchema = new BaseSchema({ department: String });
const Person = mongoose.model('Person', PersonSchema);
const Boss = Person.discriminator('Boss', BossSchema);
new Boss().__t; // "Boss". `__t` is the default `discriminatorKey`
const employeeSchema = new Schema({ boss: ObjectId });
const Employee = Person.discriminator('Employee', employeeSchema, 'staff');
new Employee().__t; // "staff" because of 3rd argument above
Model.distinct()
Parameters
- field «String»
- [conditions] «Object» optional
- [callback] «Function»
Returns:
- «Query»
Creates a Query for a distinct
operation.
Passing a callback
executes the query.
Example:
Link.distinct('url', { clicks: { $gt: 100 } }, function (err, result) {
if (err) return handleError(err);
assert(Array.isArray(result));
console.log('unique urls with more than 100 clicks', result);
})
const query = Link.distinct('url');
query.exec(callback);
Model.ensureIndexes()
Parameters
- [options] «Object» internal options
- [cb] «Function» optional callback
Returns:
- «Promise»
Sends createIndex
commands to mongo for each index declared in the schema.
The createIndex
commands are sent in series.
Example:
Event.ensureIndexes(function (err) {
if (err) return handleError(err);
});
After completion, an index
event is emitted on this Model
passing an error if one occurred.
Example:
const eventSchema = new Schema({ thing: { type: 'string', unique: true } })
const Event = mongoose.model('Event', eventSchema);
Event.on('index', function (err) {
if (err) console.error(err); // error occurred during index creation
})
NOTE: It is not recommended that you run this in production. Index creation may impact database performance depending on your load. Use with caution.
Model.estimatedDocumentCount()
Parameters
- [options] «Object»
- [callback] «Function»
Returns:
- «Query»
Estimates the number of documents in the MongoDB collection. Faster than
using countDocuments()
for large collections because
estimatedDocumentCount()
uses collection metadata rather than scanning
the entire collection.
Example:
const numAdventures = await Adventure.estimatedDocumentCount();
Model.events
Type:
- «property»
Event emitter that reports any errors that occurred. Useful for global error handling.
Example:
MyModel.events.on('error', err => console.log(err.message));
// Prints a 'CastError' because of the above handler
await MyModel.findOne({ _id: 'Not a valid ObjectId' }).catch(noop);
Model.exists()
Parameters
- filter «Object»
- [options]
«Object» optional see
Query.prototype.setOptions()
- [callback] «Function» callback
Returns:
- «Query»
Returns a document with _id
only if at least one document exists in the database that matches
the given filter
, and null
otherwise.
Under the hood, MyModel.exists({ answer: 42 })
is equivalent to
MyModel.findOne({ answer: 42 }).select({ _id: 1 }).lean()
Example:
await Character.deleteMany({});
await Character.create({ name: 'Jean-Luc Picard' });
await Character.exists({ name: /picard/i }); // { _id: ... }
await Character.exists({ name: /riker/i }); // null
This function triggers the following middleware.
findOne()
Model.find()
Parameters
- filter «Object|ObjectId»
- [projection]
«Object|String|Array[String]» optional fields to return, see
Query.prototype.select()
- [options]
«Object» optional see
Query.prototype.setOptions()
- [callback] «Function»
Returns:
- «Query»
Finds documents.
Mongoose casts the filter
to match the model's schema before the command is sent.
See our query casting tutorial for
more information on how Mongoose casts filter
.
Example:
// find all documents
await MyModel.find({});
// find all documents named john and at least 18
await MyModel.find({ name: 'john', age: { $gte: 18 } }).exec();
// executes, passing results to callback
MyModel.find({ name: 'john', age: { $gte: 18 }}, function (err, docs) {});
// executes, name LIKE john and only selecting the "name" and "friends" fields
await MyModel.find({ name: /john/i }, 'name friends').exec();
// passing options
await MyModel.find({ name: /john/i }, null, { skip: 10 }).exec();
Model.findById()
Parameters
- id
«Any» value of
_id
to query by - [projection]
«Object|String|Array[String]» optional fields to return, see
Query.prototype.select()
- [options]
«Object» optional see
Query.prototype.setOptions()
- [callback] «Function»
Returns:
- «Query»
Finds a single document by its _id field. findById(id)
is almost*
equivalent to findOne({ _id: id })
. If you want to query by a document's
_id
, use findById()
instead of findOne()
.
The id
is cast based on the Schema before sending the command.
This function triggers the following middleware.
findOne()
* Except for how it treats undefined
. If you use findOne()
, you'll see
that findOne(undefined)
and findOne({ _id: undefined })
are equivalent
to findOne({})
and return arbitrary documents. However, mongoose
translates findById(undefined)
into findOne({ _id: null })
.
Example:
// Find the adventure with the given `id`, or `null` if not found
await Adventure.findById(id).exec();
// using callback
Adventure.findById(id, function (err, adventure) {});
// select only the adventures name and length
await Adventure.findById(id, 'name length').exec();
Model.findByIdAndDelete()
Parameters
- id
«Object|Number|String» value of
_id
to query by - [options]
«Object» optional see
Query.prototype.setOptions()
- [options.strict] «Boolean|String» overwrites the schema's strict mode option
- [callback] «Function»
Returns:
- «Query»
Issue a MongoDB findOneAndDelete()
command by a document's _id field.
In other words, findByIdAndDelete(id)
is a shorthand for
findOneAndDelete({ _id: id })
.
This function triggers the following middleware.
findOneAndDelete()
Model.findByIdAndRemove()
Parameters
- id
«Object|Number|String» value of
_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()
- [options.sort] «Object|String» if multiple docs are found by the conditions, sets the sort order to choose which doc to update.
- [options.rawResult] «Boolean» if true, returns the raw result from the MongoDB driver
- [options.select] «Object|String» sets the document fields to return.
- [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()
Example:
A.findByIdAndRemove(id, options, callback) // executes
A.findByIdAndRemove(id, options) // return Query
A.findByIdAndRemove(id, callback) // executes
A.findByIdAndRemove(id) // returns Query
A.findByIdAndRemove() // returns Query
Model.findByIdAndUpdate()
Parameters
- id
«Object|Number|String» value of
_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 wrapupdate
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). - [options.sort] «Object|String» if multiple docs are found by the conditions, sets the sort order to choose which doc to update.
- [options.runValidators] «Boolean» if true, runs update validators on this command. Update validators validate the update operation against the model's schema
- [options.setDefaultsOnInsert=true]
«Boolean» If
setDefaultsOnInsert
andupsert
are true, mongoose will apply the defaults specified in the model's schema if a new document is created - [options.rawResult] «Boolean» if true, returns the raw result from the MongoDB driver
- [options.upsert=false] «Boolean» if true, and no documents found, insert a new document
- [options.new=false] «Boolean» if true, return the modified document rather than the original
- [options.select] «Object|String» sets the document fields to return.
- [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()
Example:
A.findByIdAndUpdate(id, update, options, callback) // executes
A.findByIdAndUpdate(id, update, options) // returns Query
A.findByIdAndUpdate(id, update, callback) // executes
A.findByIdAndUpdate(id, update) // returns Query
A.findByIdAndUpdate() // returns Query
Note:
All top level update keys which are not atomic
operation names are treated as set operations:
Example:
Model.findByIdAndUpdate(id, { name: 'jason bourne' }, options, callback)
// is sent as
Model.findByIdAndUpdate(id, { $set: { name: 'jason bourne' }}, options, callback)
This helps prevent accidentally overwriting your document with { name: 'jason bourne' }
.
To prevent this behaviour, see the overwrite
option
Note:
findOneAndX
and findByIdAndX
functions support limited validation. You can
enable validation by setting the runValidators
option.
If you need full-fledged validation, use the traditional approach of first retrieving the document.
const doc = await Model.findById(id)
doc.name = 'jason bourne';
await doc.save();
Model.findOne()
Parameters
- [conditions] «Object»
- [projection]
«Object|String|Array[String]» optional fields to return, see
Query.prototype.select()
- [options]
«Object» optional see
Query.prototype.setOptions()
- [callback] «Function»
Returns:
- «Query»
Finds one document.
The conditions
are cast to their respective SchemaTypes before the command is sent.
Note: conditions
is optional, and if conditions
is null or undefined,
mongoose will send an empty findOne
command to MongoDB, which will return
an arbitrary document. If you're querying by _id
, use findById()
instead.
Example:
// Find one adventure whose `country` is 'Croatia', otherwise `null`
await Adventure.findOne({ country: 'Croatia' }).exec();
// using callback
Adventure.findOne({ country: 'Croatia' }, function (err, adventure) {});
// select only the adventures name and length
await Adventure.findOne({ country: 'Croatia' }, 'name length').exec();
Model.findOneAndDelete()
Parameters
- conditions «Object»
- [options]
«Object» optional see
Query.prototype.setOptions()
- [options.strict] «Boolean|String» overwrites the schema's strict mode option
- [options.projection=null]
«Object|String|Array[String]» optional fields to return, see
Query.prototype.select()
- [options.session=null] «ClientSession» The session associated with this query. See transactions docs.
- [options.rawResult] «Boolean» if true, returns the raw result from the MongoDB driver
- [options.sort] «Object|String» if multiple docs are found by the conditions, sets the sort order to choose which doc to update.
- [options.select] «Object|String» sets the document fields to return.
- [options.maxTimeMS] «Number» puts a time limit on the query - requires mongodb >= 2.6.0
- [callback] «Function»
Returns:
- «Query»
Issue a MongoDB findOneAndDelete()
command.
Finds a matching document, removes it, and passes the found document (if any) to the callback.
Executes the query if callback
is passed.
This function triggers the following middleware.
findOneAndDelete()
This function differs slightly from Model.findOneAndRemove()
in that
findOneAndRemove()
becomes a MongoDB findAndModify()
command,
as opposed to a findOneAndDelete()
command. For most mongoose use cases,
this distinction is purely pedantic. You should use findOneAndDelete()
unless you have a good reason not to.
Example:
A.findOneAndDelete(conditions, options, callback) // executes
A.findOneAndDelete(conditions, options) // return Query
A.findOneAndDelete(conditions, callback) // executes
A.findOneAndDelete(conditions) // returns Query
A.findOneAndDelete() // returns Query
findOneAndX
and findByIdAndX
functions support limited validation. You can
enable validation by setting the runValidators
option.
If you need full-fledged validation, use the traditional approach of first retrieving the document.
const doc = await Model.findById(id)
doc.name = 'jason bourne';
await doc.save();
Model.findOneAndRemove()
Parameters
- conditions «Object»
- [options]
«Object» optional see
Query.prototype.setOptions()
- [options.session=null] «ClientSession» The session associated with this query. See transactions docs.
- [options.strict] «Boolean|String» overwrites the schema's strict mode option
- [options.projection=null]
«Object|String|Array[String]» optional fields to return, see
Query.prototype.select()
- [options.sort] «Object|String» if multiple docs are found by the conditions, sets the sort order to choose which doc to update.
- [options.rawResult] «Boolean» if true, returns the raw result from the MongoDB driver
- [options.select] «Object|String» sets the document fields to return.
- [options.maxTimeMS] «Number» puts a time limit on the query - requires mongodb >= 2.6.0
- [callback] «Function»
Returns:
- «Query»
Issue a mongodb findAndModify remove command.
Finds a matching document, removes it, passing the found document (if any) to the callback.
Executes the query if callback
is passed.
This function triggers the following middleware.
findOneAndRemove()
Example:
A.findOneAndRemove(conditions, options, callback) // executes
A.findOneAndRemove(conditions, options) // return Query
A.findOneAndRemove(conditions, callback) // executes
A.findOneAndRemove(conditions) // returns Query
A.findOneAndRemove() // returns Query
findOneAndX
and findByIdAndX
functions support limited validation. You can
enable validation by setting the runValidators
option.
If you need full-fledged validation, use the traditional approach of first retrieving the document.
const doc = await Model.findById(id);
doc.name = 'jason bourne';
await doc.save();
Model.findOneAndReplace()
Parameters
- filter «Object» Replace the first document that matches this filter
- [replacement] «Object» Replace with this document
- [options]
«Object» optional see
Query.prototype.setOptions()
- [options.returnDocument='before']
«String» Has two possible values,
'before'
and'after'
. By default, it will return the document before the update was applied. - [options.lean]
«Object» if truthy, mongoose will return the document as a plain JavaScript object rather than a mongoose document. See
Query.lean()
and the Mongoose lean tutorial. - [options.session=null] «ClientSession» The session associated with this query. See transactions docs.
- [options.strict] «Boolean|String» overwrites the schema's strict mode option
- [options.timestamps=null]
«Boolean» If set to
false
and schema-level timestamps are enabled, skip timestamps for this update. Note that this allows you to overwrite timestamps. Does nothing if schema-level timestamps are not set. - [options.projection=null]
«Object|String|Array[String]» optional fields to return, see
Query.prototype.select()
- [options.sort] «Object|String» if multiple docs are found by the conditions, sets the sort order to choose which doc to update.
- [options.rawResult] «Boolean» if true, returns the raw result from the MongoDB driver
- [options.select] «Object|String» sets the document fields to return.
- [options.maxTimeMS] «Number» puts a time limit on the query - requires mongodb >= 2.6.0
- [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()
Example:
A.findOneAndReplace(filter, replacement, options, callback) // executes
A.findOneAndReplace(filter, replacement, options) // return Query
A.findOneAndReplace(filter, replacement, callback) // executes
A.findOneAndReplace(filter, replacement) // returns Query
A.findOneAndReplace() // returns Query
Model.findOneAndUpdate()
Parameters
- [conditions] «Object»
- [update] «Object»
- [options]
«Object» optional see
Query.prototype.setOptions()
- [options.returnDocument='before']
«String» Has two possible values,
'before'
and'after'
. By default, it will return the document before the update was applied. - [options.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 wrapupdate
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()
- [options.new=false] «Boolean» if true, return the modified document rather than the original
- [options.fields]
«Object|String» Field selection. Equivalent to
.select(fields).findOneAndUpdate()
- [options.maxTimeMS] «Number» puts a time limit on the query - requires mongodb >= 2.6.0
- [options.sort] «Object|String» if multiple docs are found by the conditions, sets the sort order to choose which doc to update.
- [options.runValidators] «Boolean» if true, runs update validators on this command. Update validators validate the update operation against the model's schema
- [options.setDefaultsOnInsert=true]
«Boolean» If
setDefaultsOnInsert
andupsert
are true, mongoose will apply the defaults specified in the model's schema if a new document is created - [options.rawResult] «Boolean» if true, returns the raw result from the MongoDB driver
- [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.
Example:
A.findOneAndUpdate(conditions, update, options, callback) // executes
A.findOneAndUpdate(conditions, update, options) // returns Query
A.findOneAndUpdate(conditions, update, callback) // executes
A.findOneAndUpdate(conditions, update) // returns Query
A.findOneAndUpdate() // returns Query
Note:
All top level update keys which are not atomic
operation names are treated as set operations:
Example:
const query = { name: 'borne' };
Model.findOneAndUpdate(query, { name: 'jason bourne' }, options, callback)
// is sent as
Model.findOneAndUpdate(query, { $set: { name: 'jason bourne' }}, options, callback)
This helps prevent accidentally overwriting your document with { name: 'jason bourne' }
.
To prevent this behaviour, see the overwrite
option
Note:
findOneAndX
and findByIdAndX
functions support limited validation that
you can enable by setting the runValidators
option.
If you need full-fledged validation, use the traditional approach of first retrieving the document.
const doc = await Model.findById(id);
doc.name = 'jason bourne';
await doc.save();
Model.hydrate()
Parameters
- obj «Object»
- [projection] «Object|String|Array[String]» optional projection containing which fields should be selected for this document
- [options] «Object» optional options
- [options.setters=false] «Boolean» if true, apply schema setters when hydrating
Returns:
- «Document» document instance
Shortcut for creating a new Document from existing raw data, pre-saved in the DB. The document returned has no paths marked as modified initially.
Example:
// hydrate previous data into a Mongoose document
const mongooseCandy = Candy.hydrate({ _id: '54108337212ffb6d459f854c', type: 'jelly bean' });
Model.init()
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 init()
to trigger index builds.
However, you may need to call init()
to get back a promise that will resolve when your indexes are finished.
Calling await Model.init()
is helpful if you need to wait for indexes to build before continuing.
For example, if you want to wait for unique indexes to build before continuing with a test case.
Example:
const eventSchema = new Schema({ thing: { type: 'string', unique: true } })
// This calls `Event.init()` implicitly, so you don't need to call
// `Event.init()` on your own.
const Event = mongoose.model('Event', eventSchema);
await Event.init();
console.log('Indexes are done building!');
Model.insertMany()
Parameters
- doc(s) «Array|Object|[object Object]»
- [options] «Object» see the mongodb driver options
- [options.ordered=true]
«Boolean» if true, will fail fast on the first error encountered. If false, will insert all the documents it can and report errors later. An
insertMany()
withordered = false
is called an "unordered"insertMany()
. - [options.rawResult=false]
«Boolean» if false, the returned promise resolves to the documents that passed mongoose document validation. If
true
, will return the raw result from the MongoDB driver with amongoose
property that containsvalidationErrors
andresults
if this is an unorderedinsertMany
. - [options.lean=false]
«Boolean» if
true
, skips hydrating the documents. This means Mongoose will not cast or validate any of the documents passed toinsertMany()
. This option is useful if you need the extra performance, but comes with data integrity risk. Consider using withcastObject()
. - [options.limit=null] «Number» this limits the number of documents being processed (validation/casting) by mongoose in parallel, this does NOT send the documents in batches to MongoDB. Use this option if you're processing a large number of documents and your app is running out of memory.
- [options.populate=null]
«String|Object|Array» populates the result documents. This option is a no-op if
rawResult
is set. - [options.throwOnValidationError=false]
«Boolean» If true and
ordered: false
, throw an error if one of the operations failed validation, but all valid operations completed successfully. - [callback] «Function» callback
Returns:
- «Promise» resolving to the raw result from the MongoDB driver if
options.rawResult
wastrue
, 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:
const arr = [{ name: 'Star Wars' }, { name: 'The Empire Strikes Back' }];
Movies.insertMany(arr, function(error, docs) {});
Model.inspect()
Helper for console.log. Given a model named 'MyModel', returns the string
'Model { MyModel }'
.
Example:
const MyModel = mongoose.model('Test', Schema({ name: String }));
MyModel.inspect(); // 'Model { Test }'
console.log(MyModel); // Prints 'Model { Test }'
Model.listIndexes()
Parameters
- [cb] «Function» optional callback
Returns:
- «Promise,undefined,void» 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
- opts «Object» an object specifying map-reduce options
- [opts.verbose=false] «Boolean» provide statistics on job execution time
- [opts.readPreference] «ReadPreference|String» a read-preference string or a read-preference instance
- [opts.jsMode=false] «Boolean» it is possible to make the execution stay in JS. Provided in MongoDB > 2.0.X
- [opts.scope] «Object» scope variables exposed to map/reduce/finalize during execution
- [opts.finalize] «Function» finalize function
- [opts.keeptemp=false] «Boolean» keep temporary data
- [opts.limit] «Number» max number of documents
- [opts.sort] «Object» sort input objects using this key
- [opts.query] «Object» query filter object
- [opts.out] «Object» sets the output target for the map reduce job
- [opts.out.inline=1] «Number» the results are returned in an array
- [opts.out.replace] «String» add the results to collectionName: the results replace the collection
- [opts.out.reduce] «String» add the results to collectionName: if dups are detected, uses the reducer / finalize functions
- [opts.out.merge] «String» add the results to collectionName: if dups exist the new docs overwrite the old
- [callback] «Function» optional callback
Returns:
- «Promise»
Executes a mapReduce command.
opts
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:
const opts = {};
// `map()` and `reduce()` are run on the MongoDB server, not Node.js,
// these functions are converted to strings
opts.map = function () { emit(this.name, 1) };
opts.reduce = function (k, vals) { return vals.length };
User.mapReduce(opts, function (err, results) {
console.log(results)
})
If opts.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:
const opts = {};
// You can also define `map()` and `reduce()` as strings if your
// linter complains about `emit()` not being defined
opts.map = 'function () { emit(this.name, 1) }';
opts.reduce = 'function (k, vals) { return vals.length }';
opts.out = { replace: 'createdCollectionNameForResults' }
opts.verbose = true;
User.mapReduce(opts, function (err, model, stats) {
console.log('map reduce took %d ms', stats.processtime)
model.find().where('value').gt(10).exec(function (err, docs) {
console.log(docs);
});
})
// `mapReduce()` returns a promise. However, ES6 promises can only
// resolve to exactly one value,
opts.resolveToObject = true;
const promise = User.mapReduce(opts);
promise.then(function (res) {
const model = res.model;
const stats = res.stats;
console.log('map reduce took %d ms', stats.processtime)
return model.find().where('value').gt(10).exec();
}).then(function (docs) {
console.log(docs);
}).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.populate=null] «string|PopulateOptions» Recursively populate paths in the populated documents. See deep populate docs.
- [options.retainNullValues=false]
«boolean» By default, Mongoose removes null and undefined values from populated arrays. Use this option to make
populate()
retainnull
andundefined
array entries. - [options.getters=false]
«boolean» If true, Mongoose will call any getters defined on the
localField
. By default, Mongoose gets the raw value oflocalField
. For example, you would need to set this option totrue
if you wanted to add alowercase
getter to yourlocalField
. - [options.clone=false]
«boolean» When you do
BlogPost.find().populate('author')
, blog posts with the same author will share 1 copy of anauthor
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
andforeignField
schemas don't line up. If you enable this option, Mongoose will instead filter out anylocalField
properties that cannot be casted toforeignField
's schema type. - [options.perDocumentLimit=null]
«Number» For legacy reasons,
limit
withpopulate()
may give incorrect results because it only executes a single query for every document being populated. If you setperDocumentLimit
, Mongoose will ensure correctlimit
per document by executing a separate query for each document topopulate()
. 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
andlean
. - [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 thedoc(s)
.
Returns:
- «Promise»
Populates document references.
Changed in Mongoose 6: the model you call populate()
on should be the
"local field" model, not the "foreign field" model.
Available top-level options:
- path: space delimited path(s) to populate
- select: optional fields to select
- match: optional query conditions to match
- model: optional name of the model to use for population
- options: optional query options like sort, limit, etc
- justOne: optional boolean, if true Mongoose will always set
path
to a document, ornull
if no document was found. If false, Mongoose will always setpath
to an array, which will be empty if no documents are found. Inferred from schema by default. - strictPopulate: optional boolean, set to
false
to allow populating paths that aren't in the schema.
Example:
const Dog = mongoose.model('Dog', new Schema({ name: String, breed: String }));
const Person = mongoose.model('Person', new Schema({
name: String,
pet: { type: mongoose.ObjectId, ref: 'Dog' }
}));
const pets = await Pet.create([
{ name: 'Daisy', breed: 'Beagle' },
{ name: 'Einstein', breed: 'Catalan Sheepdog' }
]);
// populate many plain objects
const users = [
{ name: 'John Wick', dog: pets[0]._id },
{ name: 'Doc Brown', dog: pets[1]._id }
];
await User.populate(users, { path: 'dog', select: 'name' });
users[0].dog.name; // 'Daisy'
users[0].dog.breed; // undefined because of `select`
Model.prototype.$model()
Parameters
- name «String» model name
Returns:
- «Model»
Returns another Model instance.
Example:
const doc = new Tank;
doc.model('User').findById(id, callback);
Model.prototype.$remove()
Alias for remove
Model.prototype.$where
Type:
- «property»
Additional properties to attach to the query when calling save()
and
isNew
is false.
Model.prototype.base
Type:
- «property»
Base Mongoose instance the model uses.
Model.prototype.baseModelName
Type:
- «property»
If this is a discriminator model, baseModelName
is the name of
the base model.
Model.prototype.collection
Type:
- «property»
Collection the model uses.
This property is read-only. Modifying this property is a no-op.
Model.prototype.collection
Type:
- «property»
Collection the model uses.
Model.prototype.db
Type:
- «property»
Connection the model uses.
Model.prototype.deleteOne()
Parameters
- [fn] «[object Object]» optional callback
Returns:
- «Promise» Promise
Removes this document from the db. Equivalent to .remove()
.
Example:
product = await product.deleteOne();
await Product.findById(product._id); // null
Model.prototype.discriminators
Type:
- «property»
Registered discriminators for this model.
Model.prototype.increment()
Signal that we desire an increment of this documents version.
Example:
const doc = await Model.findById(id);
doc.increment();
await doc.save();
Model.prototype.model()
Parameters
- name «String» model name
Returns:
- «Model»
Returns another Model instance.
Example:
const doc = new Tank;
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] «[object Object]» optional callback
Returns:
- «Promise» Promise
Removes this document from the db.
Example:
const product = await product.remove().catch(function (err) {
assert.ok(err);
});
const foundProduct = await Product.findById(product._id);
console.log(foundProduct) // null
Model.prototype.save()
Parameters
- [options] «Object» options optional options
- [options.session=null] «Session» the session associated with this save operation. If not specified, defaults to the document's associated session.
- [options.safe]
«Object» (DEPRECATED) overrides schema's safe option. Use the
w
option instead. - [options.validateBeforeSave] «Boolean» set to false to save without validating.
- [options.validateModifiedOnly=false]
«Boolean» if
true
, Mongoose will only validate modified paths, as opposed to modified paths andrequired
paths. - [options.w]
«Number|String» set the write concern. Overrides the schema-level
writeConcern
option - [options.j]
«Boolean» set to true for MongoDB to wait until this
save()
has been journaled before resolving the returned promise. Overrides the schema-levelwriteConcern
option - [options.wtimeout]
«Number» sets a timeout for the write concern. Overrides the schema-level
writeConcern
option. - [options.checkKeys=true]
«Boolean» the MongoDB driver prevents you from saving keys that start with '$' or contain '.' by default. Set this option to
false
to skip that check. See restrictions on field names - [options.timestamps=true]
«Boolean» if
false
and timestamps are enabled, skip timestamps for thissave()
. - [fn] «Function» optional callback
Returns:
- «Promise,undefined,void» 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:
product.sold = Date.now();
product = await product.save();
If save is successful, the returned promise will fulfill with the document saved.
Example:
const newProduct = await product.save();
newProduct === product; // true
Model.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:
const res = await Character.remove({ name: 'Eddard Stark' });
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) {}
whereres
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:
const res = await Person.replaceOne({ _id: 24601 }, { name: 'Jean Valjean' });
res.matchedCount; // Number of documents matched
res.modifiedCount; // Number of documents modified
res.acknowledged; // Boolean indicating everything went smoothly.
res.upsertedId; // null or an id containing a document that had to be upserted.
res.upsertedCount; // Number indicating how many documents had to be upserted. Will either be 0 or 1.
This function triggers the following middleware.
replaceOne()
Model.schema
Type:
- «property»
Schema the model uses.
Model.startSession()
Parameters
- [options] «Object» see the mongodb driver options
- [options.causalConsistency=true] «Boolean» set to false to disable causal consistency
- [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:
const session = await Person.startSession();
let doc = await Person.findOne({ name: 'Ned Stark' }, null, { session });
await doc.remove();
// `doc` will always be null, even if reading from a replica set
// secondary. Without causal consistency, it is possible to
// get a doc back from the below query if the query reads from a
// secondary that is experiencing replication lag.
doc = await Person.findOne({ name: 'Ned Stark' }, null, { session, readPreference: 'secondary' });
Model.syncIndexes()
Parameters
- [options]
«Object» options to pass to
ensureIndexes()
- [options.background=null]
«Boolean» if specified, overrides each index's
background
property - [callback] «Function» optional callback
Returns:
- «Promise,undefined,void» Returns
undefined
if callback is specified, returns a promise if no callback, when the Promise resolves the value is a list of the dropped indexes.
Makes the indexes in MongoDB match the indexes defined in this model's
schema. This function will drop any indexes that are not defined in
the model's schema except the _id
index, and build any indexes that
are in your schema but not in MongoDB.
See the introductory blog post for more information.
Example:
const schema = new Schema({ name: { type: String, unique: true } });
const Customer = mongoose.model('Customer', schema);
await Customer.collection.createIndex({ age: 1 }); // Index is not in schema
// Will drop the 'age' index and create an index on `name`
await Customer.syncIndexes();
Model.translateAliases()
Parameters
- fields «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:
Character
.find(Character.translateAliases({
'名': 'Eddard Stark' // Alias for 'name'
})
.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. IfsetDefaultsOnInsert
andupsert
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 wrapdoc
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)
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.
Example:
MyModel.update({ age: { $gt: 18 } }, { oldEnough: true }, fn);
const res = await MyModel.update({ name: 'Tobi' }, { ferret: true });
res.n; // Number of documents that matched `{ name: 'Tobi' }`
// Number of documents that were changed. If every doc matched already
// had `ferret` set to `true`, `nModified` will be 0.
res.nModified;
Valid options:
strict
(boolean): overrides the schema-levelstrict
option for this updateupsert
(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 concernmulti
(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 andupsert
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 tofalse
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 occurredrawResponse
is the full response from Mongo
Note:
All top level keys which are not atomic
operation names are treated as set operations:
Example:
const query = { name: 'borne' };
Model.update(query, { name: 'jason bourne' }, options, callback);
// is sent as
Model.update(query, { $set: { name: 'jason bourne' }}, options, function(err, res));
// 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) {}
whereres
has 5 properties:modifiedCount
,matchedCount
,acknowledged
,upsertedId
, andupsertedCount
.
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:
const res = await Person.updateMany({ name: /Stark$/ }, { isDeleted: true });
res.matchedCount; // Number of documents matched
res.modifiedCount; // Number of documents modified
res.acknowledged; // Boolean indicating everything went smoothly.
res.upsertedId; // null or an id containing a document that had to be upserted.
res.upsertedCount; // Number indicating how many documents had to be upserted. Will either be 0 or 1.
This function triggers the following middleware.
updateMany()
Model.updateOne()
Parameters
- filter «Object»
- update «Object|Array»
- [options]
«Object» optional see
Query.prototype.setOptions()
- [options.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 themulti
option. - Use
replaceOne()
if you want to overwrite an entire document rather than using atomic operators like$set
.
Example:
const res = await Person.updateOne({ name: 'Jean-Luc Picard' }, { ship: 'USS Enterprise' });
res.matchedCount; // Number of documents matched
res.modifiedCount; // Number of documents modified
res.acknowledged; // Boolean indicating everything went smoothly.
res.upsertedId; // null or an id containing a document that had to be upserted.
res.upsertedCount; // Number indicating how many documents had to be upserted. Will either be 0 or 1.
This function triggers the following middleware.
updateOne()
Model.validate()
Parameters
- obj «Object»
- pathsToValidate «Array|String»
- [context] «Object»
- [callback] «Function»
Returns:
- «Promise,undefined,void»
Casts and validates the given object against this model's schema, passing the
given context
to custom validators.
Example:
const Model = mongoose.model('Test', Schema({
name: { type: String, required: true },
age: { type: Number, required: true }
});
try {
await Model.validate({ name: null }, ['name'])
} catch (err) {
err instanceof mongoose.Error.ValidationError; // true
Object.keys(err.errors); // ['name']
}
Model.watch()
Parameters
- [pipeline] «Array»
- [options] «Object» see the mongodb driver options
- [options.hydrate=false]
«Boolean» if true and
fullDocument: 'updateLookup'
is set, Mongoose will automatically hydratefullDocument
into a fully fledged Mongoose document
Returns:
- «ChangeStream» mongoose-specific change stream wrapper, inherits from EventEmitter
Requires a replica set running MongoDB >= 3.6.0. Watches the underlying collection for changes using MongoDB change streams.
This function does not trigger any middleware. In particular, it does not trigger aggregate middleware.
The ChangeStream object is an event emitter that emits the following events:
- 'change': A change occurred, see below example
- 'error': An unrecoverable error occurred. In particular, change streams currently error out if they lose connection to the replica set primary. Follow this GitHub issue for updates.
- 'end': Emitted if the underlying stream is closed
- 'close': Emitted if the underlying stream is closed
Example:
const doc = await Person.create({ name: 'Ned Stark' });
const changeStream = Person.watch().on('change', change => console.log(change));
// Will print from the above `console.log()`:
// { _id: { _data: ... },
// operationType: 'delete',
// ns: { db: 'mydb', coll: 'Person' },
// documentKey: { _id: 5a51b125c5500f5aa094c7bd } }
await doc.remove();
Model.where()
Parameters
- path «String»
- [val] «Object» optional value
Returns:
- «Query»
Creates a Query, applies the passed conditions, and returns the Query.
For example, instead of writing:
User.find({ age: { $gte: 21, $lte: 65 } }, callback);
we can instead write:
User.where('age').gte(21).lte(65).exec(callback);
Since the Query class also supports where
you can continue chaining
User
.where('age').gte(21).lte(65)
.where('name', /^b/i)
... etc
- Query()
- Query.prototype.$where()
- Query.prototype.all()
- Query.prototype.allowDiskUse()
- Query.prototype.and()
- Query.prototype.batchSize()
- Query.prototype.box()
- Query.prototype.cast()
- Query.prototype.catch()
- Query.prototype.center()
- Query.prototype.centerSphere()
- Query.prototype.circle()
- Query.prototype.clone()
- Query.prototype.collation()
- Query.prototype.comment()
- Query.prototype.count()
- Query.prototype.countDocuments()
- Query.prototype.cursor()
- Query.prototype.deleteMany()
- Query.prototype.deleteOne()
- Query.prototype.distinct()
- Query.prototype.elemMatch()
- Query.prototype.equals()
- Query.prototype.error()
- Query.prototype.estimatedDocumentCount()
- Query.prototype.exec()
- Query.prototype.exists()
- Query.prototype.explain()
- Query.prototype.find()
- Query.prototype.findOne()
- Query.prototype.findOneAndDelete()
- Query.prototype.findOneAndRemove()
- Query.prototype.findOneAndReplace()
- Query.prototype.findOneAndUpdate()
- Query.prototype.geometry()
- Query.prototype.get()
- Query.prototype.getFilter()
- Query.prototype.getOptions()
- Query.prototype.getPopulatedPaths()
- Query.prototype.getQuery()
- Query.prototype.getUpdate()
- Query.prototype.gt()
- Query.prototype.gte()
- Query.prototype.hint()
- Query.prototype.in()
- Query.prototype.intersects()
- Query.prototype.j()
- Query.prototype.lean()
- Query.prototype.limit()
- Query.prototype.lt()
- Query.prototype.lte()
- Query.prototype.maxDistance()
- Query.prototype.maxScan()
- Query.prototype.maxTimeMS()
- Query.prototype.maxscan()
- Query.prototype.merge()
- Query.prototype.mod()
- Query.prototype.model
- Query.prototype.mongooseOptions()
- Query.prototype.ne()
- Query.prototype.near()
- Query.prototype.nearSphere()
- Query.prototype.nin()
- Query.prototype.nor()
- Query.prototype.or()
- Query.prototype.orFail()
- Query.prototype.polygon()
- Query.prototype.populate()
- Query.prototype.post()
- Query.prototype.pre()
- Query.prototype.projection()
- Query.prototype.read()
- Query.prototype.readConcern()
- Query.prototype.regex()
- Query.prototype.remove()
- Query.prototype.replaceOne()
- Query.prototype.select()
- Query.prototype.selected()
- Query.prototype.selectedExclusively()
- Query.prototype.selectedInclusively()
- Query.prototype.session()
- Query.prototype.set()
- Query.prototype.setOptions()
- Query.prototype.setQuery()
- Query.prototype.setUpdate()
- Query.prototype.size()
- Query.prototype.skip()
- Query.prototype.slice()
- Query.prototype.snapshot()
- Query.prototype.sort()
- Query.prototype.tailable()
- Query.prototype.then()
- Query.prototype.toConstructor()
- Query.prototype.transform()
- Query.prototype.update()
- Query.prototype.updateMany()
- Query.prototype.updateOne()
- Query.prototype.w()
- Query.prototype.where()
- Query.prototype.within()
- Query.prototype.writeConcern()
- Query.prototype.wtimeout()
- Query.prototype[Symbol.asyncIterator]()
- Query.use$geoWithin
Query()
Parameters
- [options] «Object»
- [model] «Object»
- [conditions] «Object»
- [collection] «Object» Mongoose collection
Query constructor used for building queries. You do not need
to instantiate a Query
directly. Instead use Model functions like
Model.find()
.
Example:
const query = MyModel.find(); // `query` is an instance of `Query`
query.setOptions({ lean : true });
query.collection(MyModel.collection);
query.where('age').gte(21).exec(callback);
// You can instantiate a query directly. There is no need to do
// this unless you're an advanced user with a very good reason to.
const query = new mongoose.Query();
Query.prototype.$where()
Parameters
- js «String|Function» javascript string or function
Returns:
- «Query» this
Specifies a javascript function or expression to pass to MongoDBs query system.
Example:
query.$where('this.comments.length === 10 || this.name.length === 5')
// or
query.$where(function () {
return this.comments.length === 10 || this.name.length === 5;
})
Note:
Only use $where
when you have a condition that cannot be met using other MongoDB operators like $lt
.
Be sure to read about all of its caveats before using.
Query.prototype.all()
Parameters
- [path] «String»
- val «Array»
Specifies an $all
query condition.
When called with one argument, the most recent path passed to where()
is used.
Example:
MyModel.find().where('pets').all(['dog', 'cat', 'ferret']);
// Equivalent:
MyModel.find().all('pets', ['dog', 'cat', 'ferret']);
Query.prototype.allowDiskUse()
Parameters
- [v]
«Boolean» Enable/disable
allowDiskUse
. If called with 0 arguments, setsallowDiskUse: true
Returns:
- «Query» this
Sets the allowDiskUse
option,
which allows the MongoDB server to use more than 100 MB for this query's sort()
. This option can
let you work around QueryExceededMemoryLimitNoDiskUseAllowed
errors from the MongoDB server.
Note that this option requires MongoDB server >= 4.4. Setting this option is a no-op for MongoDB 4.2 and earlier.
Calling query.allowDiskUse(v)
is equivalent to query.setOptions({ allowDiskUse: v })
Example:
await query.find().sort({ name: 1 }).allowDiskUse(true);
// Equivalent:
await query.find().sort({ name: 1 }).allowDiskUse();
Query.prototype.and()
Parameters
- array «Array» array of conditions
Returns:
- «Query» this
Specifies arguments for a $and
condition.
Example:
query.and([{ color: 'green' }, { status: 'ok' }])
Query.prototype.batchSize()
Parameters
- val «Number»
Query.prototype.box()
Parameters
- val1 «Object|Array<Number>» Lower Left Coordinates OR a object of lower-left(ll) and upper-right(ur) Coordinates
- [val2] «Array<Number>» Upper Right Coordinates
Returns:
- «Query» this
Specifies a $box
condition
Example:
const lowerLeft = [40.73083, -73.99756]
const upperRight= [40.741404, -73.988135]
query.where('loc').within().box(lowerLeft, upperRight)
query.box({ ll : lowerLeft, ur : upperRight })
Query.prototype.cast()
Parameters
- [model]
«Model» the model to cast to. If not set, defaults to
this.model
- [obj] «Object»
Returns:
- «Object»
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()
Query.prototype.centerSphere()
Parameters
- [path] «String»
- val «Object»
Returns:
- «Query» this
DEPRECATED Specifies a $centerSphere
condition
Deprecated. Use circle instead.
Example:
const area = { center: [50, 50], radius: 10 };
query.where('loc').within().centerSphere(area);
Query.prototype.circle()
Parameters
- [path] «String»
- area «Object»
Returns:
- «Query» this
Specifies a $center
or $centerSphere
condition.
Example:
const area = { center: [50, 50], radius: 10, unique: true }
query.where('loc').within().circle(area)
// alternatively
query.circle('loc', area);
// spherical calculations
const area = { center: [50, 50], radius: 10, unique: true, spherical: true }
query.where('loc').within().circle(area)
// alternatively
query.circle('loc', area);
Query.prototype.clone()
Returns:
- «Query» copy
Make a copy of this query so you can re-execute it.
Example:
const q = Book.findOne({ title: 'Casino Royale' });
await q.exec();
await q.exec(); // Throws an error because you can't execute a query twice
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:
query.comment('login query')
Note:
Cannot be used with distinct()
Query.prototype.count()
Parameters
- [filter] «Object» count documents that match this object
- [callback] «Function» optional params are (error, count)
Returns:
- «Query» this
Specifies this query as a count
query.
This method is deprecated. If you want to count the number of documents in
a collection, e.g. count({})
, use the estimatedDocumentCount()
function
instead. Otherwise, use the countDocuments()
function instead.
Passing a callback
executes the query.
This function triggers the following middleware.
count()
Example:
const countQuery = model.where({ 'color': 'black' }).count();
query.count({ color: 'black' }).count(callback)
query.count({ color: 'black' }, callback)
query.where('color', 'black').count(function (err, count) {
if (err) return handleError(err);
console.log('there are %d kittens', count);
})
Query.prototype.countDocuments()
Parameters
- [filter] «Object» mongodb selector
- [options] «Object»
- [callback] «Function» optional params are (error, count)
Returns:
- «Query» this
Specifies this query as a countDocuments()
query. Behaves like count()
,
except it always does a full collection scan when passed an empty filter {}
.
There are also minor differences in how countDocuments()
handles
$where
and a couple geospatial operators.
versus count()
.
Passing a callback
executes the query.
This function triggers the following middleware.
countDocuments()
Example:
const countQuery = model.where({ 'color': 'black' }).countDocuments();
query.countDocuments({ color: 'black' }).count(callback);
query.countDocuments({ color: 'black' }, callback);
query.where('color', 'black').countDocuments(function(err, count) {
if (err) return handleError(err);
console.log('there are %d kittens', count);
});
The countDocuments()
function is similar to count()
, but there are a
few operators that countDocuments()
does not support.
Below are the operators that count()
supports but countDocuments()
does not,
and the suggested replacement:
$where
:$expr
$near
:$geoWithin
with$center
$nearSphere
:$geoWithin
with$centerSphere
Query.prototype.cursor()
Parameters
- [options] «Object»
Returns:
- «QueryCursor»
Returns a wrapper around a mongodb driver cursor.
A QueryCursor exposes a Streams3 interface, as well as a .next()
function.
The .cursor()
function triggers pre find hooks, but not post find hooks.
Example:
// There are 2 ways to use a cursor. First, as a stream:
Thing.
find({ name: /^hello/ }).
cursor().
on('data', function(doc) { console.log(doc); }).
on('end', function() { console.log('Done!'); });
// Or you can use `.next()` to manually get the next doc in the stream.
// `.next()` returns a promise, so you can use promises or callbacks.
const cursor = Thing.find({ name: /^hello/ }).cursor();
cursor.next(function(error, doc) {
console.log(doc);
});
// Because `.next()` returns a promise, you can use co
// to easily iterate through all documents without loading them
// all into memory.
const cursor = Thing.find({ name: /^hello/ }).cursor();
for (let doc = await cursor.next(); doc != null; doc = await cursor.next()) {
console.log(doc);
}
Valid options
transform
: optional function which accepts a mongoose document. The return value of the function will be emitted ondata
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:
await Character.deleteMany({ name: /Stark/, age: { $gte: 18 } });
// Using callbacks:
Character.deleteMany({ name: /Stark/, age: { $gte: 18 } }, callback);
This function calls the MongoDB driver's Collection#deleteMany()
function.
The returned promise resolves to an
object that contains 3 properties:
ok
:1
if no errors occurreddeletedCount
: the number of documents deletedn
: the number of documents deleted. Equal todeletedCount
.
Example:
const res = await Character.deleteMany({ name: /Stark/, age: { $gte: 18 } });
// `0` if no docs matched the filter, number of docs deleted otherwise
res.deletedCount;
Query.prototype.deleteOne()
Parameters
- [filter] «Object|Query» mongodb selector
- [options]
«Object» optional see
Query.prototype.setOptions()
- [callback] «Function» optional params are (error, mongooseDeleteResult)
Returns:
- «Query» this
Declare and/or execute this query as a deleteOne()
operation. Works like
remove, except it deletes at most one document regardless of the single
option.
This function triggers deleteOne
middleware.
Example:
await Character.deleteOne({ name: 'Eddard Stark' });
// Using callbacks:
Character.deleteOne({ name: 'Eddard Stark' }, callback);
This function calls the MongoDB driver's Collection#deleteOne()
function.
The returned promise resolves to an
object that contains 3 properties:
ok
:1
if no errors occurreddeletedCount
: the number of documents deletedn
: the number of documents deleted. Equal todeletedCount
.
Example:
const res = await Character.deleteOne({ name: 'Eddard Stark' });
// `1` if MongoDB deleted a doc, `0` if no docs matched the filter `{ name: ... }`
res.deletedCount;
Query.prototype.distinct()
Parameters
- [field] «String»
- [filter] «Object|Query»
- [callback] «Function» optional params are (error, arr)
Returns:
- «Query» this
Declares or executes a distinct() operation.
Passing a callback
executes the query.
This function does not trigger any middleware.
Example:
distinct(field, conditions, callback)
distinct(field, conditions)
distinct(field, callback)
distinct(field)
distinct(callback)
distinct()
Query.prototype.elemMatch()
Parameters
- path «String|Object|Function»
- filter «Object|Function»
Returns:
- «Query» this
Specifies an $elemMatch
condition
Example:
query.elemMatch('comment', { author: 'autobot', votes: {$gte: 5}})
query.where('comment').elemMatch({ author: 'autobot', votes: {$gte: 5}})
query.elemMatch('comment', function (elem) {
elem.where('author').equals('autobot');
elem.where('votes').gte(5);
})
query.where('comment').elemMatch(function (elem) {
elem.where({ author: 'autobot' });
elem.where('votes').gte(5);
})
Query.prototype.equals()
Parameters
- val «Object»
Returns:
- «Query» this
Specifies the complementary comparison value for paths specified with where()
Example:
User.where('age').equals(49);
// is the same as
User.where('age', 49);
Query.prototype.error()
Parameters
- err
«Error|null» if set,
exec()
will fail fast before sending the query to MongoDB
Returns:
- «Query» this
Gets/sets the error flag on this query. If this flag is not null or
undefined, the exec()
promise will reject without executing.
Example:
Query().error(); // Get current error value
Query().error(null); // Unset the current error
Query().error(new Error('test')); // `exec()` will resolve with test
Schema.pre('find', function() {
if (!this.getQuery().userId) {
this.error(new Error('Not allowed to query without setting userId'));
}
});
Note that query casting runs after hooks, so cast errors will override custom errors.
Example:
const TestSchema = new Schema({ num: Number });
const TestModel = db.model('Test', TestSchema);
TestModel.find({ num: 'not a number' }).error(new Error('woops')).exec(function(error) {
// `error` will be a cast error because `num` failed to cast
});
Query.prototype.estimatedDocumentCount()
Parameters
- [options] «Object» passed transparently to the MongoDB driver
- [callback] «Function» optional params are (error, count)
Returns:
- «Query» this
Specifies this query as a estimatedDocumentCount()
query. Faster than
using countDocuments()
for large collections because
estimatedDocumentCount()
uses collection metadata rather than scanning
the entire collection.
estimatedDocumentCount()
does not accept a filter. Model.find({ foo: bar }).estimatedDocumentCount()
is equivalent to Model.find().estimatedDocumentCount()
This function triggers the following middleware.
estimatedDocumentCount()
Example:
await Model.find().estimatedDocumentCount();
Query.prototype.exec()
Parameters
- [operation] «String|Function»
- [callback] «Function» optional params depend on the function being called
Returns:
- «Promise»
Executes the query
Example:
const promise = query.exec();
const promise = query.exec('update');
query.exec(callback);
query.exec('find', callback);
Query.prototype.exists()
Parameters
- [path] «String»
- val «Boolean»
Returns:
- «Query» this
Specifies an $exists
condition
Example:
// { name: { $exists: true }}
Thing.where('name').exists()
Thing.where('name').exists(true)
Thing.find().exists('name')
// { name: { $exists: false }}
Thing.where('name').exists(false);
Thing.find().exists('name', false);
Query.prototype.explain()
Parameters
- [verbose] «String» The verbosity mode. Either 'queryPlanner', 'executionStats', or 'allPlansExecution'. The default is 'queryPlanner'
Returns:
- «Query» this
Sets the explain
option,
which makes this query return detailed execution stats instead of the actual
query result. This method is useful for determining what index your queries
use.
Calling query.explain(v)
is equivalent to query.setOptions({ explain: v })
Example:
const query = new Query();
const res = await query.find({ a: 1 }).explain('queryPlanner');
console.log(res);
Query.prototype.find()
Parameters
- [filter] «Object|ObjectId» mongodb selector. If not specified, returns all documents.
- [callback] «Function»
Returns:
- «Query» this
Find all documents that match selector
. The result will be an array of documents.
If there are too many documents in the result to fit in memory, use
Query.prototype.cursor()
Example:
// Using async/await
const arr = await Movie.find({ year: { $gte: 1980, $lte: 1989 } });
// Using callbacks
Movie.find({ year: { $gte: 1980, $lte: 1989 } }, function(err, arr) {});
Query.prototype.findOne()
Parameters
- [filter] «Object» mongodb selector
- [projection] «Object» optional fields to return
- [options]
«Object» see
setOptions()
- [callback] «Function» optional params are (error, document)
Returns:
- «Query» this
Declares the query a findOne operation. When executed, the first found document is passed to the callback.
Passing a callback
executes the query. The result of the query is a single document.
- Note:
conditions
is optional, and ifconditions
is null or undefined, mongoose will send an emptyfindOne
command to MongoDB, which will return an arbitrary document. If you're querying by_id
, useModel.findById()
instead.
This function triggers the following middleware.
findOne()
Example:
const query = Kitten.where({ color: 'white' });
query.findOne(function (err, kitten) {
if (err) return handleError(err);
if (kitten) {
// doc may be null if no document matched
}
});
Query.prototype.findOneAndDelete()
Parameters
- [filter] «Object»
- [options] «Object»
- [options.rawResult] «Boolean» if true, returns the raw result from the MongoDB driver
- [options.session=null] «ClientSession» The session associated with this query. See transactions docs.
- [options.strict] «Boolean|String» overwrites the schema's strict mode option
- [callback] «Function» optional params are (error, document)
Returns:
- «Query» this
Issues a MongoDB findOneAndDelete command.
Finds a matching document, removes it, and passes the found document (if any)
to the callback. Executes if callback
is passed.
This function triggers the following middleware.
findOneAndDelete()
This function differs slightly from Model.findOneAndRemove()
in that
findOneAndRemove()
becomes a MongoDB findAndModify()
command,
as opposed to a findOneAndDelete()
command. For most mongoose use cases,
this distinction is purely pedantic. You should use findOneAndDelete()
unless you have a good reason not to.
Available options
sort
: if multiple docs are found by the conditions, sets the sort order to choose which doc to updatemaxTimeMS
: puts a time limit on the query - requires mongodb >= 2.6.0rawResult
: if true, resolves to the raw result from the MongoDB driver
Callback Signature
function(error, doc) {
// error: any errors that occurred
// doc: the document before updates are applied if `new: false`, or after updates if `new = true`
}
Example:
A.where().findOneAndDelete(conditions, options, callback) // executes
A.where().findOneAndDelete(conditions, options) // return Query
A.where().findOneAndDelete(conditions, callback) // executes
A.where().findOneAndDelete(conditions) // returns Query
A.where().findOneAndDelete(callback) // executes
A.where().findOneAndDelete() // returns Query
Query.prototype.findOneAndRemove()
Parameters
- [conditions] «Object»
- [options] «Object»
- [options.rawResult] «Boolean» if true, returns the raw result from the MongoDB driver
- [options.session=null] «ClientSession» The session associated with this query. See transactions docs.
- [options.strict] «Boolean|String» overwrites the schema's strict mode option
- [callback] «Function» optional params are (error, document)
Returns:
- «Query» this
Issues a mongodb findAndModify remove command.
Finds a matching document, removes it, passing the found document (if any) to
the callback. Executes if callback
is passed.
This function triggers the following middleware.
findOneAndRemove()
Available options
sort
: if multiple docs are found by the conditions, sets the sort order to choose which doc to updatemaxTimeMS
: puts a time limit on the query - requires mongodb >= 2.6.0rawResult
: if true, resolves to the raw result from the MongoDB driver
Callback Signature
function(error, doc) {
// error: any errors that occurred
// doc: the document before updates are applied if `new: false`, or after updates if `new = true`
}
Example:
A.where().findOneAndRemove(conditions, options, callback) // executes
A.where().findOneAndRemove(conditions, options) // return Query
A.where().findOneAndRemove(conditions, callback) // executes
A.where().findOneAndRemove(conditions) // returns Query
A.where().findOneAndRemove(callback) // executes
A.where().findOneAndRemove() // returns Query
Query.prototype.findOneAndReplace()
Parameters
- [filter] «Object»
- [replacement] «Object»
- [options] «Object»
- [options.rawResult] «Boolean» if true, returns the raw result from the MongoDB driver
- [options.session=null] «ClientSession» The session associated with this query. See transactions docs.
- [options.strict] «Boolean|String» overwrites the schema's strict mode option
- [options.new=false]
«Boolean» By default,
findOneAndUpdate()
returns the document as it was beforeupdate
was applied. If you setnew: true
,findOneAndUpdate()
will instead give you the object afterupdate
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 tonew: true
. - [callback] «Function» optional params are (error, document)
Returns:
- «Query» this
Issues a MongoDB findOneAndReplace command.
Finds a matching document, removes it, and passes the found document (if any)
to the callback. Executes if callback
is passed.
This function triggers the following middleware.
findOneAndReplace()
Available options
sort
: if multiple docs are found by the conditions, sets the sort order to choose which doc to updatemaxTimeMS
: puts a time limit on the query - requires mongodb >= 2.6.0rawResult
: if true, resolves to the raw result from the MongoDB driver
Callback Signature
function(error, doc) {
// error: any errors that occurred
// doc: the document before updates are applied if `new: false`, or after updates if `new = true`
}
Example:
A.where().findOneAndReplace(filter, replacement, options, callback); // executes
A.where().findOneAndReplace(filter, replacement, options); // return Query
A.where().findOneAndReplace(filter, replacement, callback); // executes
A.where().findOneAndReplace(filter); // returns Query
A.where().findOneAndReplace(callback); // executes
A.where().findOneAndReplace(); // returns Query
Query.prototype.findOneAndUpdate()
Parameters
- [filter] «Object|Query»
- [doc] «Object»
- [options] «Object»
- [options.rawResult] «Boolean» if true, returns the raw result from the MongoDB driver
- [options.strict] «Boolean|String» overwrites the schema's strict mode option
- [options.session=null] «ClientSession» The session associated with this query. See transactions docs.
- [options.multipleCastError] «Boolean» by default, mongoose only returns the first error that occurred in casting the query. Turn on this option to aggregate all the cast errors.
- [options.new=false]
«Boolean» By default,
findOneAndUpdate()
returns the document as it was beforeupdate
was applied. If you setnew: true
,findOneAndUpdate()
will instead give you the object afterupdate
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 tonew: 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 updatemaxTimeMS
: puts a time limit on the query - requires mongodb >= 2.6.0runValidators
: if true, runs update validators on this command. Update validators validate the update operation against the model's schema.setDefaultsOnInsert
:true
by default. IfsetDefaultsOnInsert
andupsert
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
function(error, doc) {
// error: any errors that occurred
// doc: the document before updates are applied if `new: false`, or after updates if `new = true`
}
Example:
query.findOneAndUpdate(conditions, update, options, callback) // executes
query.findOneAndUpdate(conditions, update, options) // returns Query
query.findOneAndUpdate(conditions, update, callback) // executes
query.findOneAndUpdate(conditions, update) // returns Query
query.findOneAndUpdate(update, callback) // returns Query
query.findOneAndUpdate(update) // returns Query
query.findOneAndUpdate(callback) // executes
query.findOneAndUpdate() // returns Query
Query.prototype.geometry()
Parameters
- object
«Object» Must contain a
type
property which is a String and acoordinates
property which is an Array. See the examples.
Returns:
- «Query» this
Specifies a $geometry
condition
Example:
const polyA = [[[ 10, 20 ], [ 10, 40 ], [ 30, 40 ], [ 30, 20 ]]]
query.where('loc').within().geometry({ type: 'Polygon', coordinates: polyA })
// or
const polyB = [[ 0, 0 ], [ 1, 1 ]]
query.where('loc').within().geometry({ type: 'LineString', coordinates: polyB })
// or
const polyC = [ 0, 0 ]
query.where('loc').within().geometry({ type: 'Point', coordinates: polyC })
// or
query.where('loc').intersects().geometry({ type: 'Point', coordinates: polyC })
The argument is assigned to the most recent path passed to where()
.
Note:
geometry()
must come after either intersects()
or within()
.
The object
argument must contain type
and coordinates
properties.
- type {String}
- coordinates {Array}
Query.prototype.get()
Parameters
- path «String|Object» path or object of key/value pairs to get
Returns:
- «Query» this
For update operations, returns the value of a path in the update's $set
.
Useful for writing getters/setters that can work with both update operations
and save()
.
Example:
const query = Model.updateOne({}, { $set: { name: 'Jean-Luc Picard' } });
query.get('name'); // 'Jean-Luc Picard'
Query.prototype.getFilter()
Returns:
- «Object» current query filter
Returns the current query filter (also known as conditions) as a POJO.
Example:
const query = new Query();
query.find({ a: 1 }).where('b').gt(2);
query.getFilter(); // { a: 1, b: { $gt: 2 } }
Query.prototype.getOptions()
Returns:
- «Object» the options
Gets query options.
Example:
const query = new Query();
query.limit(10);
query.setOptions({ maxTimeMS: 1000 });
query.getOptions(); // { limit: 10, maxTimeMS: 1000 }
Query.prototype.getPopulatedPaths()
Returns:
- «Array» an array of strings representing populated paths
Gets a list of paths to be populated by this query
Example:
bookSchema.pre('findOne', function() {
let keys = this.getPopulatedPaths(); // ['author']
});
...
Book.findOne({}).populate('author');
Example:
// Deep populate
const q = L1.find().populate({
path: 'level2',
populate: { path: 'level3' }
});
q.getPopulatedPaths(); // ['level2', 'level2.level3']
Query.prototype.getQuery()
Returns:
- «Object» current query filter
Returns the current query filter. Equivalent to getFilter()
.
You should use getFilter()
instead of getQuery()
where possible. getQuery()
will likely be deprecated in a future release.
Example:
const query = new Query();
query.find({ a: 1 }).where('b').gt(2);
query.getQuery(); // { a: 1, b: { $gt: 2 } }
Query.prototype.getUpdate()
Returns:
- «Object» current update operations
Returns the current update operations as a JSON object.
Example:
const query = new Query();
query.update({}, { $set: { a: 5 } });
query.getUpdate(); // { $set: { a: 5 } }
Query.prototype.gt()
Parameters
- [path] «String»
- val «Number»
Specifies a $gt
query condition.
When called with one argument, the most recent path passed to where()
is used.
Example:
Thing.find().where('age').gt(21);
// or
Thing.find().gt('age', 21);
Query.prototype.gte()
Parameters
- [path] «String»
- val «Number»
Specifies a $gte
query condition.
When called with one argument, the most recent path passed to where()
is used.
Query.prototype.hint()
Parameters
- val «Object» a hint object
Returns:
- «Query» this
Sets query hints.
Example:
query.hint({ indexA: 1, indexB: -1 });
Note:
Cannot be used with distinct()
Query.prototype.in()
Parameters
- [path] «String»
- val «Array»
Specifies an $in
query condition.
When called with one argument, the most recent path passed to where()
is used.
Query.prototype.intersects()
Parameters
- [arg] «Object»
Returns:
- «Query» this
Declares an intersects query for geometry()
.
Example:
query.where('path').intersects().geometry({
type: 'LineString',
coordinates: [[180.0, 11.0], [180, 9.0]]
});
query.where('path').intersects({
type: 'LineString',
coordinates: [[180.0, 11.0], [180, 9.0]]
});
Note:
MUST be used after where()
.
Note:
In Mongoose 3.7, intersects
changed from a getter to a function. If you need the old syntax, use this.
Query.prototype.j()
Parameters
- val «boolean»
Returns:
- «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:
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:
new Query().lean() // true
new Query().lean(true)
new Query().lean(false)
const docs = await Model.find().lean();
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:
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.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»
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:
const query = new Query();
// Throws an error 'operation exceeded time limit' as long as there's
// >= 1 doc in the queried collection
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 isremainder
.
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:
// All find products whose inventory is odd
Product.find().mod('inventory', [2, 1]);
Product.find().where('inventory').mod([2, 1]);
// This syntax is a little strange, but supported.
Product.find().where('inventory').mod(2, 1);
Query.prototype.model
Type:
- «property»
The model this query is associated with.
Example:
const q = MyModel.find();
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 toQuery.prototype.populate()
lean
: if truthy, Mongoose will not hydrate any documents that are returned from this query. SeeQuery.prototype.lean()
for more information.strict
: controls how Mongoose handles keys that aren't in the schema for updates. This option istrue
by default, which means Mongoose will silently strip any paths in the update that aren't in the schema. See thestrict
mode docs for more information.strictQuery
: controls how Mongoose handles keys that aren't in the schema for the queryfilter
. This option isfalse
by default for backwards compatibility, which means Mongoose will allowModel.find({ foo: 'bar' })
even iffoo
is not in the schema. See thestrictQuery
docs for more information.nearSphere
: use$nearSphere
instead ofnear()
. See theQuery.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:
query.where('loc').near({ center: [10, 10] });
query.where('loc').near({ center: [10, 10], maxDistance: 5 });
query.where('loc').near({ center: [10, 10], maxDistance: 5, spherical: true });
query.near('loc', { center: [10, 10], maxDistance: 5 });
Query.prototype.nearSphere()
DEPRECATED Specifies a $nearSphere
condition
Example:
query.where('loc').nearSphere({ center: [10, 10], maxDistance: 5 });
Deprecated. Use query.near()
instead with the spherical
option set to true
.
Example:
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:
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:
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 aDocumentNotFoundError
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:
// Throws if no doc returned
await Model.findOne({ foo: 'bar' }).orFail();
// Throws if no document was updated. Note that `orFail()` will still
// throw if the only document that matches is `{ foo: 'bar', name: 'test' }`,
// because `orFail()` will throw if no document was _updated_, not
// if no document was _found_.
await Model.updateOne({ foo: 'bar' }, { name: 'test' }).orFail();
// Throws "No docs found!" error if no docs match `{ foo: 'bar' }`
await Model.find({ foo: 'bar' }).orFail(new Error('No docs found!'));
// Throws "Not found" error if no document was found
await Model.findOneAndUpdate({ foo: 'bar' }, { name: 'test' }).
orFail(() => Error('Not found'));
Query.prototype.polygon()
Parameters
- [path] «String|Array»
- [coordinatePairs...] «Array|Object»
Returns:
- «Query» this
Specifies a $polygon
condition
Example:
query.where('loc').within().polygon([10, 20], [13, 25], [7, 15]);
query.polygon('loc', [10, 20], [13, 25], [7, 15]);
Query.prototype.populate()
Parameters
- path «Object|String|Array[String]» either the path(s) 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()
retainnull
andundefined
array entries. - [options.getters=false]
«boolean» if true, Mongoose will call any getters defined on the
localField
. By default, Mongoose gets the raw value oflocalField
. For example, you would need to set this option totrue
if you wanted to add alowercase
getter to yourlocalField
. - [options.clone=false]
«boolean» When you do
BlogPost.find().populate('author')
, blog posts with the same author will share 1 copy of anauthor
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
andlean
.
Returns:
- «Query» this
Specifies paths which should be populated with other documents.
Example:
let book = await Book.findOne().populate('authors');
book.title; // 'Node.js in Action'
book.authors[0].name; // 'TJ Holowaychuk'
book.authors[1].name; // 'Nathan Rajlich'
let books = await Book.find().populate({
path: 'authors',
// `match` and `sort` apply to the Author model,
// not the Book model. These options do not affect
// which documents are in `books`, just the order and
// contents of each book document's `authors`.
match: { name: new RegExp('.*h.*', 'i') },
sort: { name: -1 }
});
books[0].title; // 'Node.js in Action'
// Each book's `authors` are sorted by name, descending.
books[0].authors[0].name; // 'TJ Holowaychuk'
books[0].authors[1].name; // 'Marc Harter'
books[1].title; // 'Professional AngularJS'
// Empty array, no authors' name has the letter 'h'
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:
const q1 = Question.find({ answer: 42 });
q1.post(function middleware() {
console.log(this.getFilter());
});
await q1.exec(); // Prints "{ answer: 42 }"
// Doesn't print anything, because `middleware()` is only
// registered on `q1`.
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:
const q1 = Question.find({ answer: 42 });
q1.pre(function middleware() {
console.log(this.getFilter());
});
await q1.exec(); // Prints "{ answer: 42 }"
// Doesn't print anything, because `middleware()` is only
// registered on `q1`.
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:
const q = Model.find();
q.projection(); // null
q.select('a b');
q.projection(); // { a: 1, b: 1 }
q.projection({ c: 1 });
q.projection(); // { c: 1 }
q.projection(null);
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:
primary - (default) Read from primary only. Operations will produce an error if primary is unavailable. Cannot be combined with tags.
secondary Read from secondary if available, otherwise error.
primaryPreferred Read from primary if available, otherwise a secondary.
secondaryPreferred Read from a secondary if available, otherwise read from the primary.
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
p primary
pp primaryPreferred
s secondary
sp secondaryPreferred
n nearest
Example:
new Query().read('primary')
new Query().read('p') // same as primary
new Query().read('primaryPreferred')
new Query().read('pp') // same as primaryPreferred
new Query().read('secondary')
new Query().read('s') // same as secondary
new Query().read('secondaryPreferred')
new Query().read('sp') // same as secondaryPreferred
new Query().read('nearest')
new Query().read('n') // same as nearest
// read from secondaries with matching tags
new Query().read('s', [{ dc:'sf', s: 1 },{ dc:'ma', s: 2 }])
Read more about how to use read preferences 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:
new Query().readConcern('local')
new Query().readConcern('l') // same as local
new Query().readConcern('available')
new Query().readConcern('a') // same as available
new Query().readConcern('majority')
new Query().readConcern('m') // same as majority
new Query().readConcern('linearizable')
new Query().readConcern('lz') // same as linearizable
new Query().readConcern('snapshot')
new Query().readConcern('s') // same as snapshot
Read Concern Level:
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).
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).
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.
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.
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
l local
a available
m majority
lz linearizable
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:
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 occurreddeletedCount
: the number of documents deletedn
: the number of documents deleted. Equal todeletedCount
.
Example:
const res = await Character.remove({ name: /Stark/ });
// Number of docs deleted
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()
.
// not executed
const query = Character.remove({ name: /Stark/ });
// executed
Character.remove({ name: /Stark/ }, callback);
Character.remove({ name: /Stark/ }).remove(callback);
// executed without a callback
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:
const res = await Person.replaceOne({ _id: 24601 }, { name: 'Jean Valjean' });
res.acknowledged; // Indicates if this write result was acknowledged. If not, then all other members of this result will be undefined.
res.matchedCount; // Number of documents that matched the filter
res.modifiedCount; // Number of documents that were modified
res.upsertedCount; // Number of documents that were upserted
res.upsertedId; // Identifier of the inserted document (if an upsert took place)
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:
// include a and b, exclude other fields
query.select('a b');
// Equivalent syntaxes:
query.select(['a', 'b']);
query.select({ a: 1, b: 1 });
// exclude c and d, include other fields
query.select('-c -d');
// Use `+` to override schema-level `select: false` without making the
// projection inclusive.
const schema = new Schema({
foo: { type: String, select: false },
bar: String
});
// ...
query.select('+foo'); // Override foo's `select: false` without excluding `bar`
// or you may use object notation, useful when
// you have keys already prefixed with a "-"
query.select({ a: 1, b: 1 });
query.select({ c: 0, d: 0 });
Additional calls to select can override the previous selection:
query.select({ a: 1, b: 1 }).select({ b: 0 }); // selection is now { a: 1 }
query.select({ a: 0, b: 0 }).select({ b: 1 }); // selection is now { a: 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.
query.selectedExclusively(); // false
query.select('-name');
query.selectedExclusively(); // true
query.selectedInclusively(); // false
Query.prototype.selectedInclusively()
Returns:
- «Boolean»
Determines if inclusive field selection has been made.
query.selectedInclusively(); // false
query.select('name');
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:
const s = await mongoose.startSession();
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:
// Updates `{ $set: { updatedAt: new Date() } }`
new Query().updateOne({}, {}).set('updatedAt', new Date());
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 tofalse
to skip timestamps for that particular update. Has no effect iftimestamps
is not enabled in the schema options. - 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()
:
- lean
- populate
- projection
- sanitizeProjection
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,void»
Sets the query conditions to the provided JSON object.
Example:
const query = new Query();
query.find({ a: 1 })
query.setQuery({ a: 2 });
query.getQuery(); // { a: 2 }
Query.prototype.setUpdate()
Parameters
- new «Object» update operation
Returns:
- «undefined,void»
Sets the current update operation to new value.
Example:
const query = new Query();
query.update({}, { $set: { a: 5 } });
query.setUpdate({ $set: { b: 6 } });
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:
const docs = await MyModel.where('tags').size(0).exec();
assert(Array.isArray(docs));
console.log('documents with 0 tags', docs);
Query.prototype.skip()
Parameters
- val «Number»
Specifies the number of documents to skip.
Example:
query.skip(100).limit(20);
Note:
Cannot be used with distinct()
Query.prototype.slice()
Parameters
- [path] «String»
- val «Number|Array» number of elements to slice or array with number of elements to skip and number of elements to slice
Returns:
- «Query» this
Specifies a $slice
projection for an array.
Example:
query.slice('comments', 5); // Returns the first 5 comments
query.slice('comments', -5); // Returns the last 5 comments
query.slice('comments', [10, 5]); // Returns the first 5 comments after the 10-th
query.where('comments').slice(5); // Returns the first 5 comments
query.where('comments').slice([-10, 5]); // Returns the first 5 comments after the 10-th to last
Note: If the absolute value of the number of elements to be sliced is greater than the number of elements in the array, all array elements will be returned.
// Given `arr`: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
query.slice('arr', 20); // Returns [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
query.slice('arr', -20); // Returns [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Note: If the number of elements to skip is positive and greater than the number of elements in the array, an empty array will be returned.
// Given `arr`: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
query.slice('arr', [20, 5]); // Returns []
Note: If the number of elements to skip is negative and its absolute value is greater than the number of elements in the array, the starting position is the start of the array.
// Given `arr`: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
query.slice('arr', [-20, 5]); // Returns [1, 2, 3, 4, 5]
Query.prototype.snapshot()
Returns:
- «Query» this
Specifies this query as a snapshot
query.
Example:
query.snapshot(); // true
query.snapshot(true);
query.snapshot(false);
Note:
Cannot be used with distinct()
Query.prototype.sort()
Parameters
- arg «Object|String|Array<Array<string|number>>»
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:
// sort by "field" ascending and "test" descending
query.sort({ field: 'asc', test: -1 });
// equivalent
query.sort('field -test');
// also possible is to use a array with array key-value pairs
query.sort([['field', 'asc']]);
Note:
Cannot be used with distinct()
Query.prototype.tailable()
Parameters
- bool «Boolean» defaults to true
- [opts] «Object» options to set
- [opts.awaitData] «Boolean» false by default. Set to true to keep the cursor open even if there's no data.
- [opts.maxAwaitTimeMS]
«Number» the maximum amount of time for the server to wait on new documents to satisfy a tailable cursor query. Requires
tailable
andawaitData
to be true
Sets the tailable option (for use with capped collections).
Example:
query.tailable(); // true
query.tailable(true);
query.tailable(false);
// Set both `tailable` and `awaitData` options
query.tailable({ awaitData: true });
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:
// Create a query for adventure movies and read from the primary
// node in the replica-set unless it is down, in which case we'll
// read from a secondary node.
const query = Movie.find({ tags: 'adventure' }).read('primaryPreferred');
// create a custom Query constructor based off these settings
const Adventure = query.toConstructor();
// Adventure is now a subclass of mongoose.Query and works the same way but with the
// default query parameters and options set.
Adventure().exec(callback)
// further narrow down our query results while still using the previous settings
Adventure().where({ name: /^Life/ }).exec(callback);
// since Adventure is a stand-alone constructor we can also add our own
// helper methods and getters without impacting global queries
Adventure.prototype.startsWith = function (prefix) {
this.where({ name: new RegExp('^' + prefix) })
return this;
}
Object.defineProperty(Adventure.prototype, 'highlyRated', {
get: function () {
this.where({ rating: { $gt: 4.5 }});
return this;
}
})
Adventure().highlyRated.startsWith('Life').exec(callback)
Query.prototype.transform()
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 transform()
will run after any post hooks.
Example:
const res = await MyModel.findOne().transform(res => {
// Sets a `loadedAt` property on the doc that tells you the time the
// document was loaded.
return res == null ?
res :
Object.assign(res, { loadedAt: new Date() });
});
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:
Model.where({ _id: id }).update({ title: 'words' });
// becomes
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. IfsetDefaultsOnInsert
andupsert
are true, mongoose will apply the defaults specified in the model's schema if a new document is created.strict
(boolean) overrides thestrict
option for this updateread
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.
const q = Model.where({ _id: id });
q.update({ $set: { name: 'bob' }}).update(); // not executed
q.update({ $set: { name: 'bob' }}).exec(); // executed
// keys that are not [atomic](https://www.mongodb.com/docs/manual/tutorial/model-data-for-atomic-operations/#pattern) ops become `$set`.
// this executes the same command as the previous example.
q.update({ name: 'bob' }).exec();
// multi updates
Model.where()
.update({ name: /^match/ }, { $set: { arr: [] }}, { multi: true }, callback)
// more multi updates
Model.where()
.setOptions({ multi: true })
.update({ $set: { arr: [] }}, callback)
// single update by default
Model.where({ email: 'address@example.com' })
.update({ $inc: { counter: 1 }}, callback)
API summary
update(filter, doc, options, cb); // executes
update(filter, doc, options);
update(filter, doc, cb); // executes
update(filter, doc);
update(doc, cb); // executes
update(doc);
update(cb); // executes
update(true); // executes
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:
const res = await Person.updateMany({ name: /Stark$/ }, { isDeleted: true });
res.n; // Number of documents matched
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 themulti
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:
const res = await Person.updateOne({ name: 'Jean-Luc Picard' }, { ship: 'USS Enterprise' });
res.acknowledged; // Indicates if this write result was acknowledged. If not, then all other members of this result will be undefined.
res.matchedCount; // Number of documents that matched the filter
res.modifiedCount; // Number of documents that were modified
res.upsertedCount; // Number of documents that were upserted
res.upsertedId; // Identifier of the inserted document (if an upsert took place)
This function triggers the following middleware.
updateOne()
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:
// The 'majority' option means the `deleteOne()` promise won't resolve
// until the `deleteOne()` has propagated to the majority of the replica set
await mongoose.model('Person').
deleteOne({ name: 'Ned Stark' }).
w('majority');
Query.prototype.where()
Parameters
- [path] «String|Object»
- [val] «any»
Returns:
- «Query» this
Specifies a path
for use with chaining.
Example:
// instead of writing:
User.find({age: {$gte: 21, $lte: 65}}, callback);
// we can instead write:
User.where('age').gte(21).lte(65);
// passing query conditions is permitted
User.find().where({ name: 'vonderful' })
// chaining
User
.where('age').gte(21).lte(65)
.where('name', /^vonderful/i)
.where('friends').slice(10)
.exec(callback)
Query.prototype.within()
Returns:
- «Query» this
Defines a $within
or $geoWithin
argument for geo-spatial queries.
Example:
query.where(path).within().box()
query.where(path).within().circle()
query.where(path).within().geometry()
query.where('loc').within({ center: [50,50], radius: 10, unique: true, spherical: true });
query.where('loc').within({ box: [[40.73, -73.9], [40.7, -73.988]] });
query.where('loc').within({ polygon: [[],[],[],[]] });
query.where('loc').within([], [], []) // polygon
query.where('loc').within([], []) // box
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 ofmongod
servers, or tag set ofmongod
servers, that must acknowledge this write before this write is considered successful.j
: Boolean, set totrue
to request acknowledgement that this operation has been persisted to MongoDB's on-disk journal.wtimeout
: Ifw > 1
, the maximum amount of time to wait for this write to propagate through the replica set before this operation fails. The default is0
, 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:
// The 'majority' option means the `deleteOne()` promise won't resolve
// until the `deleteOne()` has propagated to the majority of the replica set
await mongoose.model('Person').
deleteOne({ name: 'Ned Stark' }).
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:
// The `deleteOne()` promise won't resolve until this `deleteOne()` has
// propagated to at least `w = 2` members of the replica set. If it takes
// longer than 1 second, this `deleteOne()` will fail.
await mongoose.model('Person').
deleteOne({ name: 'Ned Stark' }).
w(2).
wtimeout(1000);
Query.prototype[Symbol.asyncIterator]()
Returns an asyncIterator for use with for/await/of
loops
This function only works for find()
queries.
You do not need to call this function explicitly, the JavaScript runtime
will call it for you.
Example:
for await (const doc of Model.aggregate([{ $sort: { name: 1 } }])) {
console.log(doc.name);
}
Node.js 10.x supports async iterators natively without any flags. You can
enable async iterators in Node.js 8.x using the --harmony_async_iteration
flag.
Note: This function is not if Symbol.asyncIterator
is undefined. If
Symbol.asyncIterator
is undefined, that means your Node.js version does not
support async iterators.
Query.use$geoWithin
Type:
- «property»
Flag to opt out of using $geoWithin
.
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.
- QueryCursor()
- QueryCursor.prototype.addCursorFlag()
- QueryCursor.prototype.close()
- QueryCursor.prototype.eachAsync()
- QueryCursor.prototype.map()
- QueryCursor.prototype.next()
- QueryCursor.prototype.options
- QueryCursor.prototype.rewind()
- QueryCursor.prototype[Symbol.asyncIterator]()
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.
- [options.batchSize]
«Number» if set, will call
fn()
with arrays of documents with length at mostbatchSize
- [options.continueOnError=false]
«Boolean» if true,
eachAsync()
iterates through all docs even iffn
throws an error. If false,eachAsync()
throws an error immediately if the given functionfn()
throws an error. - [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:
// Iterate over documents asynchronously
Thing.
find({ name: /^hello/ }).
cursor().
eachAsync(async function (doc, i) {
doc.foo = doc.bar + i;
await doc.save();
})
QueryCursor.prototype.map()
Parameters
- fn «Function»
Returns:
- «QueryCursor»
Registers a transform function which subsequently maps documents retrieved
via the streams interface or .next()
Example:
// Map documents returned by `data` events
Thing.
find({ name: /^hello/ }).
cursor().
map(function (doc) {
doc.foo = "bar";
return doc;
})
on('data', function(doc) { console.log(doc.foo); });
// Or map documents returned by `.next()`
const cursor = Thing.find({ name: /^hello/ }).
cursor().
map(function (doc) {
doc.foo = "bar";
return doc;
});
cursor.next(function(error, doc) {
console.log(doc.foo);
});
QueryCursor.prototype.next()
Parameters
- callback «Function»
Returns:
- «Promise»
Get the next document from this cursor. Will return null
when there are
no documents left.
QueryCursor.prototype.options
Type:
- «property»
The options
passed in to the QueryCursor
constructor.
QueryCursor.prototype.rewind()
Returns:
- «AggregationCursor» this
Rewind this cursor to its uninitialized state. Any options that are present on the cursor will remain in effect. Iterating this cursor will cause new queries to be sent to the server, even if the resultant data has already been retrieved by this cursor.
QueryCursor.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:
// Works without using `cursor()`
for await (const doc of Model.find([{ $sort: { name: 1 } }])) {
console.log(doc.name);
}
// Can also use `cursor()`
for await (const doc of Model.find([{ $sort: { name: 1 } }]).cursor()) {
console.log(doc.name);
}
Node.js 10.x supports async iterators natively without any flags. You can
enable async iterators in Node.js 8.x using the --harmony_async_iteration
flag.
Note: This function is not if Symbol.asyncIterator
is undefined. If
Symbol.asyncIterator
is undefined, that means your Node.js version does not
support async iterators.
- Aggregate()
- Aggregate.prototype.addFields()
- Aggregate.prototype.allowDiskUse()
- Aggregate.prototype.append()
- Aggregate.prototype.catch()
- Aggregate.prototype.collation()
- Aggregate.prototype.count()
- Aggregate.prototype.cursor()
- Aggregate.prototype.densify()
- Aggregate.prototype.exec()
- Aggregate.prototype.explain()
- Aggregate.prototype.facet()
- Aggregate.prototype.fill()
- Aggregate.prototype.graphLookup()
- Aggregate.prototype.group()
- Aggregate.prototype.hint()
- Aggregate.prototype.limit()
- Aggregate.prototype.lookup()
- Aggregate.prototype.match()
- Aggregate.prototype.model()
- Aggregate.prototype.near()
- Aggregate.prototype.option()
- Aggregate.prototype.options
- Aggregate.prototype.pipeline()
- Aggregate.prototype.project()
- Aggregate.prototype.read()
- Aggregate.prototype.readConcern()
- Aggregate.prototype.redact()
- Aggregate.prototype.replaceRoot()
- Aggregate.prototype.sample()
- Aggregate.prototype.search()
- Aggregate.prototype.session()
- Aggregate.prototype.skip()
- Aggregate.prototype.sort()
- Aggregate.prototype.sortByCount()
- Aggregate.prototype.then()
- Aggregate.prototype.unionWith()
- Aggregate.prototype.unwind()
- Aggregate.prototype[Symbol.asyncIterator]()
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:
const aggregate = Model.aggregate([
{ $project: { a: 1, b: 1 } },
{ $skip: 5 }
]);
Model.
aggregate([{ $match: { age: { $gte: 21 }}}]).
unwind('tags').
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 databasenew Aggregate([{ $match: { _id: '00000000000000000000000a' } }]); // Do this instead to cast to an ObjectId new Aggregate([{ $match: { _id: new mongoose.Types.ObjectId('00000000000000000000000a') } }]);
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
Example:
// adding new fields based on existing fields
aggregate.addFields({
newField: '$b.nested'
, plusTen: { $add: ['$val', 10]}
, sub: {
name: '$a'
}
})
// etc
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.
Returns:
- «Aggregate» this
Sets the allowDiskUse option for the aggregation query
Example:
await Model.aggregate([{ $match: { foo: 'bar' } }]).allowDiskUse(true);
Aggregate.prototype.append()
Parameters
- ...ops «Object|Array[Object]» operator(s) to append. Can either be a spread of objects or a single parameter of a object array.
Returns:
- «Aggregate»
Appends new operators to this aggregate pipeline
Example:
aggregate.append({ $project: { field: 1 }}, { $limit: 2 });
// or pass an array
const pipeline = [{ $match: { daw: 'Logic Audio X' }} ];
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.
Compatible with await
.
Aggregate.prototype.collation()
Parameters
- collation «Object» options
Returns:
- «Aggregate» this
Adds a collation
Example:
const res = await Model.aggregate(pipeline).collation({ locale: 'en_US', strength: 1 });
Aggregate.prototype.count()
Parameters
- fieldName «String» The name of the output field which has the count as its value. It must be a non-empty string, must not start with $ and must not contain the . character.
Returns:
- «Aggregate»
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:
- «AggregationCursor» cursor representing this aggregation
Sets the cursor
option and executes this aggregation, returning an aggregation cursor.
Cursors are useful if you want to process the results of the aggregation one-at-a-time
because the aggregation result is too big to fit into memory.
Example:
const cursor = Model.aggregate(..).cursor({ batchSize: 1000 });
cursor.eachAsync(function(doc, i) {
// use doc
});
Aggregate.prototype.densify()
Parameters
- arg «Object» $densify operator contents
Returns:
- «Aggregate»
Appends a new $densify operator to this aggregate pipeline.
Example:
aggregate.densify({
field: 'timestamp',
range: {
step: 1,
unit: 'hour',
bounds: [new Date('2021-05-18T00:00:00.000Z'), new Date('2021-05-18T08:00:00.000Z')]
}
});
Aggregate.prototype.exec()
Parameters
- [callback] «Function»
Returns:
- «Promise» Returns a Promise if no "callback" is given.
Executes the aggregate pipeline on the currently bound Model.
Example:
aggregate.exec(callback);
// Because a promise is returned, the `callback` is optional.
const result = await aggregate.exec();
Aggregate.prototype.explain()
Parameters
- [verbosity] «String»
- [callback] «Function» The callback function to call, if not specified, will return a Promise instead.
Returns:
- «Promise» Returns a promise if no "callback" is given
Aggregate.prototype.facet()
Parameters
- facet «Object» options
Returns:
- «Aggregate» this
Combines multiple aggregation pipelines.
Example:
const res = await Model.aggregate().facet({
books: [{ groupBy: '$author' }],
price: [{ $bucketAuto: { groupBy: '$price', buckets: 2 } }]
});
// Output: { books: [...], price: [{...}, {...}] }
Aggregate.prototype.fill()
Parameters
- arg «Object» $fill operator contents
Returns:
- «Aggregate»
Appends a new $fill operator to this aggregate pipeline.
Example:
aggregate.fill({
output: {
bootsSold: { value: 0 },
sandalsSold: { value: 0 },
sneakersSold: { value: 0 }
}
});
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.
Example:
// 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' }`
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.
Example:
aggregate.group({ _id: "$department" });
Aggregate.prototype.hint()
Parameters
- value «Object|String» a hint object or the index name
Returns:
- «Aggregate» this
Sets the hint option for the aggregation query
Example:
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»
Aggregate.prototype.lookup()
Parameters
- options «Object» to $lookup as described in the above link
Returns:
- «Aggregate»
Appends new custom $lookup operator to this aggregate pipeline.
Example:
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.
Example:
aggregate.match({ department: { $in: [ "sales", "engineering" ] } });
Aggregate.prototype.model()
Parameters
- [model] «Model» Set the model associated with this aggregate. If not provided, returns the already stored model.
Returns:
- «Model»
Get/set the model that this aggregation will execute on.
Example:
const aggregate = MyModel.aggregate([{ $match: { answer: 42 } }]);
aggregate.model() === MyModel; // true
// Change the model. There's rarely any reason to do this.
aggregate.model(SomeOtherModel);
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.
Example:
aggregate.near({
near: { type: 'Point', coordinates: [40.724, -73.997] },
distanceField: "dist.calculated", // required
maxDistance: 0.008,
query: { type: "public" },
includeLocs: "dist.location",
spherical: true,
});
Aggregate.prototype.option()
Parameters
- options «Object» keys to merge into current options
- [options.maxTimeMS]
«Number» number limits the time this aggregation will run, see MongoDB docs on
maxTimeMS
- [options.allowDiskUse] «Boolean» boolean if true, the MongoDB server will use the hard drive to store data during this aggregation
- [options.collation]
«Object» object see
Aggregate.prototype.collation()
- [options.session]
«ClientSession» ClientSession see
Aggregate.prototype.session()
Returns:
- «Aggregate» this
Lets you set arbitrary options, for middleware or plugins.
Example:
const agg = Model.aggregate(..).option({ allowDiskUse: true }); // Set the `allowDiskUse` option
agg.options; // `{ allowDiskUse: true }`
Aggregate.prototype.options
Type:
- «property»
Contains options passed down to the aggregate command. Supported options are:
allowDiskUse
bypassDocumentValidation
collation
comment
cursor
explain
fieldsAsRaw
hint
let
maxTimeMS
raw
readConcern
readPreference
session
writeConcern
Aggregate.prototype.pipeline()
Returns:
- «Array» The current pipeline similar to the operation that will be executed
Returns the current pipeline
Example:
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.
Example:
// include a, include b, exclude _id
aggregate.project("a b -_id");
// or you may use object notation, useful when
// you have keys already prefixed with a "-"
aggregate.project({a: 1, b: 1, _id: 0});
// reshaping documents
aggregate.project({
newField: '$b.nested'
, plusTen: { $add: ['$val', 10]}
, sub: {
name: '$a'
}
})
// etc
aggregate.project({ salary_k: { $divide: [ "$salary", 1000 ] } });
Aggregate.prototype.read()
Parameters
- pref «String|ReadPreference» one of the listed preference options or their aliases
- [tags] «Array» optional tags for this query. DEPRECATED
Returns:
- «Aggregate» this
Sets the readPreference option for the aggregation query.
Example:
await Model.aggregate(pipeline).read('primaryPreferred');
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:
await Model.aggregate(pipeline).readConcern('majority');
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:
await Model.aggregate(pipeline).redact({
$cond: {
if: { $eq: [ '$level', 5 ] },
then: '$$PRUNE',
else: '$$DESCEND'
}
});
// $redact often comes with $cond operator, you can also use the following syntax provided by mongoose
await Model.aggregate(pipeline).redact({ $eq: [ '$level', 5 ] }, '$$PRUNE', '$$DESCEND');
Aggregate.prototype.replaceRoot()
Parameters
- newRoot «String|Object» the 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.
Example:
aggregate.replaceRoot("user");
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.
Example:
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:
const res = await Model.aggregate().
search({
text: {
query: 'baseball',
path: 'plot'
}
});
// Output: [{ plot: '...', title: '...' }]
Aggregate.prototype.session()
Parameters
- session «ClientSession»
Returns:
- «Aggregate» this
Sets the session for this aggregation. Useful for transactions.
Example:
const session = await Model.startSession();
await Model.aggregate(..).session(session);
Aggregate.prototype.skip()
Parameters
- num «Number» number of records to skip before next stage
Returns:
- «Aggregate»
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.
Example:
// these are equivalent
aggregate.sort({ field: 'asc', test: -1 });
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 '$'.
Example:
aggregate.sortByCount('users');
aggregate.sortByCount({ $mergeObjects: [ "$employee", "$business" ] })
Aggregate.prototype.then()
Parameters
- [resolve] «Function» successCallback
- [reject] «Function» errorCallback
Returns:
- «Promise»
Provides a Promise-like then
function, which will call .exec
without a callback
Compatible with await
.
Example:
Model.aggregate(..).then(successCallback, errorCallback);
Aggregate.prototype.unionWith()
Parameters
- options «Object» to $unionWith query as described in the above link
Returns:
- «Aggregate»
Appends new $unionWith operator to this aggregate pipeline.
Example:
aggregate.unionWith({ coll: 'users', pipeline: [ { $match: { _id: 1 } } ] });
Aggregate.prototype.unwind()
Parameters
- fields
«String|Object|Array[String]|Array[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 '$'.
Example:
aggregate.unwind("tags");
aggregate.unwind("a", "b", "c");
aggregate.unwind({ path: '$tags', preserveNullAndEmptyArrays: true });
Aggregate.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:
const agg = Model.aggregate([{ $match: { age: { $gte: 25 } } }]);
for await (const doc of agg) {
console.log(doc.name);
}
Node.js 10.x supports async iterators natively without any flags. You can
enable async iterators in Node.js 8.x using the --harmony_async_iteration
flag.
Note: This function is not set if Symbol.asyncIterator
is undefined. If
Symbol.asyncIterator
is undefined, that means your Node.js version does not
support async iterators.
- AggregationCursor()
- AggregationCursor.prototype.addCursorFlag()
- AggregationCursor.prototype.close()
- AggregationCursor.prototype.eachAsync()
- AggregationCursor.prototype.map()
- AggregationCursor.prototype.next()
- AggregationCursor.prototype[Symbol.asyncIterator]()
AggregationCursor()
Parameters
- agg «Aggregate»
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.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:
// Map documents returned by `data` events
Thing.
find({ name: /^hello/ }).
cursor().
map(function (doc) {
doc.foo = "bar";
return doc;
})
on('data', function(doc) { console.log(doc.foo); });
// Or map documents returned by `.next()`
const cursor = Thing.find({ name: /^hello/ }).
cursor().
map(function (doc) {
doc.foo = "bar";
return doc;
});
cursor.next(function(error, doc) {
console.log(doc.foo);
});
AggregationCursor.prototype.next()
Parameters
- callback «Function»
Returns:
- «Promise»
Get the next document from this cursor. Will return null
when there are
no documents left.
AggregationCursor.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:
// Async iterator without explicitly calling `cursor()`. Mongoose still
// creates an AggregationCursor instance internally.
const agg = Model.aggregate([{ $match: { age: { $gte: 25 } } }]);
for await (const doc of agg) {
console.log(doc.name);
}
// You can also use an AggregationCursor instance for async iteration
const cursor = Model.aggregate([{ $match: { age: { $gte: 25 } } }]).cursor();
for await (const doc of cursor) {
console.log(doc.name);
}
Node.js 10.x supports async iterators natively without any flags. You can
enable async iterators in Node.js 8.x using the --harmony_async_iteration
flag.
Note: This function is not set if Symbol.asyncIterator
is undefined. If
Symbol.asyncIterator
is undefined, that means your Node.js version does not
support async iterators.
- SchemaType()
- SchemaType.cast()
- SchemaType.checkRequired()
- SchemaType.get()
- SchemaType.prototype.cast()
- SchemaType.prototype.castFunction()
- SchemaType.prototype.default()
- SchemaType.prototype.doValidate()
- SchemaType.prototype.get()
- SchemaType.prototype.immutable()
- SchemaType.prototype.index()
- SchemaType.prototype.isRequired
- SchemaType.prototype.path
- SchemaType.prototype.ref()
- SchemaType.prototype.required()
- SchemaType.prototype.select()
- SchemaType.prototype.set()
- SchemaType.prototype.sparse()
- SchemaType.prototype.text()
- SchemaType.prototype.transform()
- SchemaType.prototype.unique()
- SchemaType.prototype.validate()
- SchemaType.prototype.validators
- SchemaType.set()
SchemaType()
Parameters
- path «String»
- [options] «SchemaTypeOptions» See SchemaTypeOptions docs
- [instance] «String»
SchemaType constructor. Do not instantiate SchemaType
directly.
Mongoose converts your schema paths into SchemaTypes automatically.
Example:
const schema = new Schema({ name: String });
schema.path('name') instanceof SchemaType; // true
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:
// Disallow `null` for numbers, and don't try to cast any values to
// numbers, so even strings like '123' will cause a CastError.
mongoose.Number.cast(function(v) {
assert.ok(v === undefined || typeof v === 'number');
return v;
});
SchemaType.checkRequired()
Parameters
- [fn] «Function» If set, will overwrite the current set function
Returns:
- «Function» The input
fn
or the already set function
Set & Get the checkRequired
function
Override the function the required validator uses to check whether a value
passes the required
check. Override this on the individual SchemaType.
Example:
// Use this to allow empty strings to pass the `required` validator
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:
// Make all numbers round down
mongoose.Number.get(function(v) { return Math.floor(v); });
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.castFunction()
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:
// Disallow `null` for numbers, and don't try to cast any values to
// numbers, so even strings like '123' will cause a CastError.
const number = new mongoose.Number('mypath', {});
number.cast(function(v) {
assert.ok(v === undefined || typeof v === 'number');
return v;
});
SchemaType.prototype.default()
Parameters
- val «Function|any» The default value to set
Returns:
- «Any,undefined,void» Returns the set default value.
Sets a default value for this SchemaType.
Example:
const schema = new Schema({ n: { type: Number, default: 10 })
const M = db.model('M', schema)
const m = new M;
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:
// values are cast:
const schema = new Schema({ aNumber: { type: Number, default: 4.815162342 }})
const M = db.model('M', schema)
const m = new M;
console.log(m.aNumber) // 4.815162342
// default unique objects for Mixed types:
const schema = new Schema({ mixed: Schema.Types.Mixed });
schema.path('mixed').default(function () {
return {};
});
// if we don't use a function to return object literals for Mixed defaults,
// each document will receive a reference to the same object literal creating
// a "shared" object instance:
const schema = new Schema({ mixed: Schema.Types.Mixed });
schema.path('mixed').default({});
const M = db.model('M', schema);
const m1 = new M;
m1.mixed.added = 1;
console.log(m1.mixed); // { added: 1 }
const m2 = new M;
console.log(m2.mixed); // { added: 1 }
SchemaType.prototype.doValidate()
Parameters
- value «Any»
- callback «Function»
- scope «Object»
- [options] «Object»
- [options.path] «String»
Returns:
- «Any» If no validators, returns the output from calling
fn
, otherwise no return
Performs a validation of value
using the validators declared for this SchemaType.
SchemaType.prototype.get()
Parameters
- fn «Function»
Returns:
- «SchemaType» this
Adds a getter to this schematype.
Example:
function dob (val) {
if (!val) return val;
return (val.getMonth() + 1) + "/" + val.getDate() + "/" + val.getFullYear();
}
// defining within the schema
const s = new Schema({ born: { type: Date, get: dob })
// or by retreiving its SchemaType
const s = new Schema({ born: Date })
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:
function obfuscate (cc) {
return '****-****-****-' + cc.slice(cc.length-4, cc.length);
}
const AccountSchema = new Schema({
creditCardNumber: { type: String, get: obfuscate }
});
const Account = db.model('Account', AccountSchema);
Account.findById(id, function (err, found) {
console.log(found.creditCardNumber); // '****-****-****-1234'
});
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.
function inspector (val, priorValue, schematype) {
if (schematype.options.required) {
return schematype.path + ' is required';
} else {
return schematype.path + ' is not';
}
}
const VirusSchema = new Schema({
name: { type: String, required: true, get: inspector },
taxonomy: { type: String, get: inspector }
})
const Virus = db.model('Virus', VirusSchema);
Virus.findById(id, function (err, virus) {
console.log(virus.name); // name is required
console.log(virus.taxonomy); // taxonomy is not
})
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:
const schema = new Schema({
name: { type: String, immutable: true },
age: Number
});
const Model = mongoose.model('Test', schema);
await Model.create({ name: 'test' });
const doc = await Model.findOne();
doc.isNew; // false
doc.name = 'new name';
doc.name; // 'test', because `name` is immutable
Mongoose also prevents changing immutable properties using updateOne()
and updateMany()
based on strict mode.
Example:
// Mongoose will strip out the `name` update, because `name` is immutable
Model.updateOne({}, { $set: { name: 'test2' }, $inc: { age: 1 } });
// If `strict` is set to 'throw', Mongoose will throw an error if you
// update `name`
const err = await Model.updateOne({}, { name: 'test2' }, { strict: 'throw' }).
then(() => null, err => err);
err.name; // StrictModeError
// If `strict` is `false`, Mongoose allows updating `name` even though
// the property is immutable.
Model.updateOne({}, { name: 'test2' }, { strict: false });
SchemaType.prototype.index()
Parameters
- options «Object|Boolean|String|Number»
Returns:
- «SchemaType» this
Declares the index options for this schematype.
Example:
const s = new Schema({ name: { type: String, index: true })
const s = new Schema({ name: { type: String, index: -1 })
const s = new Schema({ loc: { type: [Number], index: 'hashed' })
const s = new Schema({ loc: { type: [Number], index: '2d', sparse: true })
const s = new Schema({ loc: { type: [Number], index: { type: '2dsphere', sparse: true }})
const s = new Schema({ date: { type: Date, index: { unique: true, expires: '1d' }})
s.path('my.path').index(true);
s.path('my.date').index({ expires: 60 });
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.isRequired
Type:
- «property»
True if this SchemaType has a required validator. False otherwise.
Example:
const schema = new Schema({ name: { type: String, required: true } });
schema.path('name').isRequired; // true
schema.path('name').required(false);
schema.path('name').isRequired; // false
SchemaType.prototype.path
Type:
- «property»
The path to this SchemaType in a Schema.
Example:
const schema = new Schema({ name: String });
schema.path('name').path; // 'name'
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:
const userSchema = new Schema({ name: String });
const User = mongoose.model('User', userSchema);
const postSchema = new Schema({ user: mongoose.ObjectId });
postSchema.path('user').ref('User'); // Can set ref to a model name
postSchema.path('user').ref(User); // Or a model class
postSchema.path('user').ref(() => 'User'); // Or a function that returns the model name
postSchema.path('user').ref(() => User); // Or a function that returns the model class
// Or you can just declare the `ref` inline in your schema
const postSchema2 = new Schema({
user: { type: mongoose.ObjectId, ref: User }
});
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:
const s = new Schema({ born: { type: Date, required: true })
// or with custom error message
const s = new Schema({ born: { type: Date, required: '{PATH} is required!' })
// or with a function
const s = new Schema({
userId: ObjectId,
username: {
type: String,
required: function() { return this.userId != null; }
}
})
// or with a function and a custom message
const s = new Schema({
userId: ObjectId,
username: {
type: String,
required: [
function() { return this.userId != null; },
'username is required if id is specified'
]
}
})
// or through the path API
s.path('name').required(true);
// with custom error messaging
s.path('name').required(true, 'grrr :( ');
// or make a path conditionally required based on a function
const isOver18 = function() { return this.age >= 18; };
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:
T = db.model('T', new Schema({ x: { type: String, select: true }}));
T.find(..); // field x will always be selected ..
// .. unless overridden;
T.find().select('-x').exec(callback);
SchemaType.prototype.set()
Parameters
- fn «Function»
Returns:
- «SchemaType» this
Adds a setter to this schematype.
Example:
function capitalize (val) {
if (typeof val !== 'string') val = '';
return val.charAt(0).toUpperCase() + val.substring(1);
}
// defining within the schema
const s = new Schema({ name: { type: String, set: capitalize }});
// or with the SchemaType
const s = new Schema({ name: String })
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.
function toLower(v) {
return v.toLowerCase();
}
const UserSchema = new Schema({
email: { type: String, set: toLower }
});
const User = db.model('User', UserSchema);
const user = new User({email: 'AVENUE@Q.COM'});
console.log(user.email); // 'avenue@q.com'
// or
const user = new User();
user.email = 'Avenue@Q.com';
console.log(user.email); // 'avenue@q.com'
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.
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.
function inspector (val, priorValue, schematype) {
if (schematype.options.required) {
return schematype.path + ' is required';
} else {
return val;
}
}
const VirusSchema = new Schema({
name: { type: String, required: true, set: inspector },
taxonomy: { type: String, set: inspector }
})
const Virus = db.model('Virus', VirusSchema);
const v = new Virus({ name: 'Parvoviridae', taxonomy: 'Parvovirinae' });
console.log(v.name); // name is required
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.
const nameSchema = new Schema({ name: String, keywords: [String] });
nameSchema.path('name').set(function(v) {
// Need to check if `this` is a document, because in mongoose 5
// setters will also run on queries, in which case `this` will be a
// mongoose query object.
if (this instanceof Document && v != null) {
this.keywords = v.split(' ');
}
return v;
});
SchemaType.prototype.sparse()
Parameters
- bool «Boolean»
Returns:
- «SchemaType» this
Declares a sparse index.
Example:
const s = new Schema({ name: { type: String, sparse: true } });
s.path('name').index({ sparse: true });
SchemaType.prototype.text()
Parameters
- bool «Boolean»
Returns:
- «SchemaType» this
Declares a full text index.
Example:
const s = new Schema({ name : { type: String, text : true } })
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:
const schema = new Schema({
date: { type: Date, transform: v => v.getFullYear() }
});
const Model = mongoose.model('Test', schema);
await Model.create({ date: new Date('2016-06-01') });
const doc = await Model.findOne();
doc.date instanceof Date; // true
doc.toJSON().date; // 2016 as a number
JSON.stringify(doc); // '{"_id":...,"date":2016}'
SchemaType.prototype.unique()
Parameters
- bool «Boolean»
Returns:
- «SchemaType» this
Declares an unique index.
Example:
const s = new Schema({ name: { type: String, unique: true } });
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 (exceptundefined
) 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.
Example:
// make sure every value is equal to "something"
function validator (val) {
return val === 'something';
}
new Schema({ name: { type: String, validate: validator }});
// with a custom error message
const custom = [validator, 'Uh oh, {PATH} does not equal "something".']
new Schema({ name: { type: String, validate: custom }});
// adding many validators at a time
const many = [
{ validator: validator, msg: 'uh oh' }
, { validator: anotherValidator, msg: 'failed' }
]
new Schema({ name: { type: String, validate: many }});
// or utilizing SchemaType methods directly:
const schema = new Schema({ name: 'string' });
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.
schema.path('name').validate({
validator: function(v) { return v.length > 5; },
// `errors['name']` will be "name must have length 5, got 'foo'"
message: function(props) {
return `${props.path} must have length 5, got '${props.value}'`;
}
});
To bypass Mongoose's error messages and just copy the error message that the validator throws, do this:
schema.path('name').validate({
validator: function() { throw new Error('Oops!'); },
// `errors['name']` will be "Oops!"
message: function(props) { return props.reason.message; }
});
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.
schema.path('name').validate({
validator: function (value) {
return new Promise(function (resolve, reject) {
resolve(false); // validation failed
});
}
});
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.
const conn = mongoose.createConnection(..);
conn.on('error', handleError);
const Product = conn.model('Product', yourSchema);
const dvd = new Product(..);
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.
// registering an error listener on the Model lets us handle errors more locally
Product.on('error', handleError);
SchemaType.prototype.validators
Type:
- «property»
The validators that Mongoose should run to validate properties at this SchemaType's path.
Example:
const schema = new Schema({ name: { type: String, required: true } });
schema.path('name').validators.length; // 1, the `required` validator
SchemaType.set()
Parameters
- option «String» The name of the option you'd like to set (e.g. trim, lowercase, etc...)
- value «Any» The value of the option you'd like to set.
Returns:
- «void,void»
Sets a default option for this schema type.
Example:
// Make all strings be trimmed by default
mongoose.SchemaTypes.String.set('trim', true);
- VirtualType()
- VirtualType.prototype.applyGetters()
- VirtualType.prototype.applySetters()
- VirtualType.prototype.get()
- VirtualType.prototype.set()
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 ornull
. - [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, usingQuery#countDocuments()
- [options.match=null]
«Object|Function» add an extra match condition to
populate()
- [options.limit=null]
«Number» add a default
limit
to thepopulate()
query - [options.skip=null]
«Number» add a default
skip
to thepopulate()
query - [options.perDocumentLimit=null]
«Number» For legacy reasons,
limit
withpopulate()
may give incorrect results because it only executes a single query for every document being populated. If you setperDocumentLimit
, Mongoose will ensure correctlimit
per document by executing a separate query for each document topopulate()
. 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
andlean
. - name «String»
VirtualType constructor
This is what mongoose uses to define virtual attributes via Schema.prototype.virtual
.
Example:
const fullname = schema.virtual('fullname');
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
- fn «Function»
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 beundefined
.virtual
: the virtual object you called.get()
on.doc
: the document this virtual is attached to. Equivalent tothis
.
Example:
const virtual = schema.virtual('fullname');
virtual.get(function(value, virtual, doc) {
return this.name.first + ' ' + this.name.last;
});
VirtualType.prototype.set()
Parameters
- fn «Function»
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 tothis
.
Example:
const virtual = schema.virtual('fullname');
virtual.set(function(value, virtual, doc) {
const parts = value.split(' ');
this.name.first = parts[0];
this.name.last = parts[1];
});
const Model = mongoose.model('Test', schema);
const doc = new Model();
// Calls the setter with `value = 'Jean-Luc Picard'`
doc.fullname = 'Jean-Luc Picard';
doc.name.first; // 'Jean-Luc'
doc.name.last; // 'Picard'
- Error()
- Error.CastError
- Error.DivergentArrayError
- Error.DocumentNotFoundError
- Error.MissingSchemaError
- Error.MongooseServerSelectionError
- Error.OverwriteModelError
- Error.ParallelSaveError
- Error.StrictModeError
- Error.StrictPopulateError
- Error.ValidationError
- Error.ValidatorError
- Error.VersionError
- Error.messages
- Error.prototype.name
Error()
Parameters
- msg «String» Error message
Type:
- «constructor»
MongooseError constructor. MongooseError is the base class for all Mongoose-specific errors.
Example:
const Model = mongoose.model('Test', new mongoose.Schema({ answer: Number }));
const doc = new Model({ answer: 'not a number' });
const err = doc.validateSync();
err instanceof mongoose.Error.ValidationError; // 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.MongooseServerSelectionError
Type:
- «property»
Thrown when the MongoDB Node driver can't connect to a valid server to send an operation to.
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 constructor that
were not specified in schema or change immutable properties when
strict
mode is "throw"
Error.StrictPopulateError
Type:
- «property»
An instance of this error class will be returned when mongoose failed to populate with a path that is not existing.
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:
const schema = Schema({ name: { type: String, required: true } });
const Model = mongoose.model('Test', schema);
const doc = new Model({});
// Top-level error is a ValidationError, **not** a ValidatorError
const err = doc.validateSync();
err instanceof mongoose.Error.ValidationError; // true
// A ValidationError `err` has 0 or more ValidatorErrors keyed by the
// path in the `err.errors` property.
err.errors['name'] instanceof mongoose.Error.ValidatorError;
err.errors['name'].kind; // 'required'
err.errors['name'].path; // 'name'
err.errors['name'].value; // undefined
Instances of ValidatorError
have the following properties:
kind
: The validator'stype
, like'required'
or'regexp'
path
: The path that failed validationvalue
: 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 errorCastError
: Mongoose could not convert a value to the type defined in the schema path. May be in aValidationError
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 tosave()
an array that was modified after you loaded it with a$elemMatch
or similar projectionMissingSchemaError
: You tried to access a model withmongoose.model()
that was not definedDocumentNotFoundError
: The document you tried tosave()
was not foundValidatorError
: error from an individual schema path's validatorValidationError
: error returned fromvalidate()
orvalidateSync()
. Contains zero or moreValidatorError
instances in.errors
property.MissingSchemaError
: You calledmongoose.Document()
without a schemaObjectExpectedError
: 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 paramterOverwriteModelError
: Thrown when you callmongoose.model()
to re-define a model that was already defined.ParallelSaveError
: Thrown when you callsave()
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 tothrow
.VersionError
: Thrown when the document is out of sync
- SchemaArray()
- SchemaArray.checkRequired()
- SchemaArray.options
- SchemaArray.prototype.checkRequired()
- SchemaArray.prototype.enum()
- SchemaArray.schemaName
- SchemaArray.set()
SchemaArray()
Parameters
- key «String»
- cast «SchemaType»
- options «Object»
- schemaOptions «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:
// Require non-empty array to pass `required` check
mongoose.Schema.Types.Array.checkRequired(v => Array.isArray(v) && v.length);
const M = mongoose.model({ arr: { type: Array, required: true } });
new M({ arr: [] }).validateSync(); // `null`, validation fails!
SchemaArray.options
Type:
- «property»
Options for all arrays.
castNonArrays
:true
by default. Iffalse
, Mongoose will throw a CastError when a value isn't an array. Iftrue
, 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 «Any» value for option
Returns:
- «undefined,void»
Sets a default option for all Array instances.
Example:
// Make all Array instances have `required` of true by default.
mongoose.Schema.Array.set('required', true);
const User = mongoose.model('User', new Schema({ test: Array }));
new User({ }).validateSync().errors.test.message; // Path `test` is required.
- DocumentArrayPath()
- DocumentArrayPath.options
- DocumentArrayPath.prototype.discriminator()
- DocumentArrayPath.schemaName
- DocumentArrayPath.set()
DocumentArrayPath()
Parameters
- key «String»
- schema «Schema»
- options «Object»
- schemaOptions «Object»
SubdocsArray SchemaType constructor
DocumentArrayPath.options
Type:
- «property»
Options for all document arrays.
castNonArrays
:true
by default. Iffalse
, Mongoose will throw a CastError when a value isn't an array. Iftrue
, 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 thename
parameter. - [options.clone=true]
«Boolean» By default,
discriminator()
clones the givenschema
. Set tofalse
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:
const shapeSchema = Schema({ name: String }, { discriminatorKey: 'kind' });
const schema = Schema({ shapes: [shapeSchema] });
const docArrayPath = parentSchema.path('shapes');
docArrayPath.discriminator('Circle', Schema({ radius: Number }));
DocumentArrayPath.schemaName
Type:
- «property»
This schema type's name, to defend against minifiers that mangle function names.
DocumentArrayPath.set()
Parameters
- option «String» The name of the option you'd like to set (e.g. trim, lowercase, etc...)
- value «Any» The value of the option you'd like to set.
Returns:
- «void,void»
Type:
- «property»
Sets a default option for all DocumentArray instances.
Example:
// Make all numbers have option `min` equal to 0.
mongoose.Schema.DocumentArray.set('_id', false);
SubdocumentPath()
Parameters
- schema «Schema»
- path «String»
- options «Object»
Single nested subdocument SchemaType constructor.
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 thename
parameter. - [options.clone=true]
«Boolean» By default,
discriminator()
clones the givenschema
. Set tofalse
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:
const shapeSchema = Schema({ name: String }, { discriminatorKey: 'kind' });
const schema = Schema({ shape: shapeSchema });
const singleNestedPath = parentSchema.path('shape');
singleNestedPath.discriminator('Circle', Schema({ radius: Number }));
SubdocumentPath.set()
Parameters
- option «String» The option you'd like to set the value for
- value «Any» value for option
Returns:
- «void,void»
Type:
- «property»
Sets a default option for all SubdocumentPath instances.
Example:
// Make all numbers have option `min` equal to 0.
mongoose.Schema.SubdocumentPath.set('required', true);
- SchemaTypeOptions()
- SchemaTypeOptions.prototype.cast
- SchemaTypeOptions.prototype.default
- SchemaTypeOptions.prototype.immutable
- SchemaTypeOptions.prototype.index
- SchemaTypeOptions.prototype.ref
- SchemaTypeOptions.prototype.ref
- SchemaTypeOptions.prototype.required
- SchemaTypeOptions.prototype.select
- SchemaTypeOptions.prototype.sparse
- SchemaTypeOptions.prototype.text
- SchemaTypeOptions.prototype.transform
- SchemaTypeOptions.prototype.type
- SchemaTypeOptions.prototype.unique
- SchemaTypeOptions.prototype.validate
SchemaTypeOptions()
Type:
- «constructor»
The options defined on a schematype.
Example:
const schema = new Schema({ name: String });
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:
const schema = new Schema({
num: {
type: Number,
cast: '{VALUE} is not a valid number'
}
});
// Throws 'CastError: "bad" is not a valid number'
schema.path('num').cast('bad');
const Model = mongoose.model('Test', schema);
const doc = new Model({ num: 'fail' });
const err = doc.validateSync();
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.ref
Type:
- «Function|String»
The path in the document that populate()
should use to find the model
to use.
SchemaTypeOptions.prototype.required
Type:
- «Function|Boolean»
If true, attach a required validator to this path, which ensures this 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:
const schema = Schema({
myDate: {
type: Date,
transform: v => v.getFullYear()
}
});
const Model = mongoose.model('Test', schema);
const doc = new Model({ myDate: new Date('2019/06/01') });
doc.myDate instanceof Date; // true
const res = doc.toObject({ transform: true });
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.prototype.castNonArrays
- SchemaArrayOptions.prototype.enum
- SchemaArrayOptions.prototype.of
SchemaArrayOptions()
Type:
- «constructor»
The options defined on an Array schematype.
Example:
const schema = new Schema({ tags: [String] });
schema.path('tags').options; // SchemaArrayOptions instance
SchemaArrayOptions.prototype.castNonArrays
Type:
- «Boolean»
If set to false
, will always deactivate casting non-array values to arrays.
If set to true
, will cast non-array values to arrays if init
and SchemaArray.options.castNonArrays
are also true
Example:
const Model = db.model('Test', new Schema({ x1: { castNonArrays: false, type: [String] } }));
const doc = new Model({ x1: "some non-array value" });
await doc.validate(); // Errors with "CastError"
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:
// `arr` is an array of numbers.
new Schema({ arr: [Number] });
// Equivalent way to define `arr` as an array of numbers
new Schema({ arr: { type: Array, of: Number } });
SchemaBufferOptions()
Type:
- «constructor»
The options defined on a Buffer schematype.
Example:
const schema = new Schema({ bitmap: Buffer });
schema.path('bitmap').options; // SchemaBufferOptions instance
SchemaBufferOptions.prototype.subtype
Type:
- «Number»
Set the default subtype for this buffer.
- SchemaDateOptions()
- SchemaDateOptions.prototype.expires
- SchemaDateOptions.prototype.max
- SchemaDateOptions.prototype.min
SchemaDateOptions()
Type:
- «constructor»
The options defined on a Date schematype.
Example:
const schema = new Schema({ startedAt: Date });
schema.path('startedAt').options; // SchemaDateOptions instance
SchemaDateOptions.prototype.expires
Type:
- «Date»
If set, Mongoose creates a TTL index on this path.
mongo TTL index expireAfterSeconds
value will take 'expires' value expressed in seconds.
Example:
const schema = new Schema({ "expireAt": { type: Date, expires: 11 } });
// if 'expireAt' is set, then document expires at expireAt + 11 seconds
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.prototype.enum
- SchemaNumberOptions.prototype.max
- SchemaNumberOptions.prototype.min
- SchemaNumberOptions.prototype.populate
SchemaNumberOptions()
Type:
- «constructor»
The options defined on a Number schematype.
Example:
const schema = new Schema({ count: Number });
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:
const schema = new Schema({
favoritePrime: {
type: Number,
enum: [3, 5, 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:
const schema = new Schema({
child: {
type: Number,
ref: 'Child',
populate: { select: 'name' }
}
});
const Parent = mongoose.model('Parent', schema);
// Automatically adds `.select('name')`
Parent.findOne().populate('child');
SchemaObjectIdOptions()
Type:
- «constructor»
The options defined on an ObjectId schematype.
Example:
const schema = new Schema({ testId: mongoose.ObjectId });
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:
const schema = new Schema({
child: {
type: 'ObjectId',
ref: 'Child',
populate: { select: 'name' }
}
});
const Parent = mongoose.model('Parent', schema);
// Automatically adds `.select('name')`
Parent.findOne().populate('child');
- SchemaStringOptions()
- SchemaStringOptions.prototype.enum
- SchemaStringOptions.prototype.lowercase
- SchemaStringOptions.prototype.match
- SchemaStringOptions.prototype.maxLength
- SchemaStringOptions.prototype.minLength
- SchemaStringOptions.prototype.populate
- SchemaStringOptions.prototype.trim
- SchemaStringOptions.prototype.uppercase
SchemaStringOptions()
Type:
- «constructor»
The options defined on a string schematype.
Example:
const schema = new Schema({ name: String });
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()
.
- MongooseDocumentArray.prototype.create()
- MongooseDocumentArray.prototype.id()
- MongooseDocumentArray.prototype.inspect()
- MongooseDocumentArray.prototype.pull()
- MongooseDocumentArray.prototype.push()
- MongooseDocumentArray.prototype.toObject()
MongooseDocumentArray.prototype.create()
Parameters
- obj «Object» the value to cast to this arrays SubDocument schema
Creates a subdocument casted to this schema.
This is the same subdocument constructor used for casting.
MongooseDocumentArray.prototype.id()
Parameters
- id «ObjectId|String|Number|Buffer»
Returns:
- «EmbeddedDocument,null» the subdocument or null if not found.
Searches array items for the first document with a matching _id.
Example:
const embeddedDoc = m.array.id(some_id);
MongooseDocumentArray.prototype.inspect()
Helper for console.log
MongooseDocumentArray.prototype.pull()
Parameters
- [...args] «Object»
Pulls items from the array atomically.
MongooseDocumentArray.prototype.push()
Parameters
- [...args] «Object»
Wraps Array#push
with proper change tracking.
MongooseDocumentArray.prototype.toObject()
Parameters
- [options]
«Object» optional options to pass to each documents
toObject
method call during conversion
Returns:
- «Array»
Returns a native js Array of plain js objects
Note:
Each sub-document is converted to a plain object by calling its #toObject
method.
- Subdocument.prototype.$parent()
- Subdocument.prototype.inspect()
- Subdocument.prototype.ownerDocument()
- Subdocument.prototype.parent()
- Subdocument.prototype.remove()
Subdocument.prototype.$parent()
Returns this sub-documents parent document.
Subdocument.prototype.inspect()
Helper for console.log
Subdocument.prototype.ownerDocument()
Returns:
- «Document»
Returns the top level document of this sub-document.
Subdocument.prototype.parent()
Returns this sub-documents parent document.
Subdocument.prototype.remove()
Parameters
- [options] «Object»
- [callback] «Function» optional callback for compatibility with Document.prototype.remove
Null-out this subdoc
ArraySubdocument.prototype.$parent()
Returns this sub-documents parent document.
ArraySubdocument.prototype.parentArray()
Returns this subdocument's parent array.
Example:
const Test = mongoose.model('Test', new Schema({
docArr: [{ name: String }]
}));
const doc = new Test({ docArr: [{ name: 'test subdoc' }] });
doc.docArr[0].parentArray() === doc.docArr; // true
- MongooseBuffer.mixin.copy()
- MongooseBuffer.mixin.equals()
- MongooseBuffer.mixin.subtype()
- MongooseBuffer.mixin.toBSON()
- MongooseBuffer.mixin.toObject()
- MongooseBuffer.mixin.write()
MongooseBuffer.mixin.copy()
Parameters
- target «Buffer»
Returns:
- «Number» The number of bytes copied.
Type:
- «property»
Copies the buffer.
Note:
Buffer#copy
does not mark target
as modified so you must copy from a MongooseBuffer
for it to work as expected. This is a work around since copy
modifies the target, not this.
MongooseBuffer.mixin.equals()
Parameters
- other «Buffer»
Returns:
- «Boolean»
Determines if this buffer is equals to other
buffer
MongooseBuffer.mixin.subtype()
Parameters
- subtype «Hex»
Sets the subtype option and marks the buffer modified.
SubTypes:
const bson = require('bson')
bson.BSON_BINARY_SUBTYPE_DEFAULT
bson.BSON_BINARY_SUBTYPE_FUNCTION
bson.BSON_BINARY_SUBTYPE_BYTE_ARRAY
bson.BSON_BINARY_SUBTYPE_UUID
bson.BSON_BINARY_SUBTYPE_MD5
bson.BSON_BINARY_SUBTYPE_USER_DEFINED
doc.buffer.subtype(bson.BSON_BINARY_SUBTYPE_UUID);
MongooseBuffer.mixin.toBSON()
Returns:
- «Binary»
Converts this buffer for storage in MongoDB, including subtype
MongooseBuffer.mixin.toObject()
Parameters
- [subtype] «Hex»
Returns:
- «Binary»
Converts this buffer to its Binary type representation.
SubTypes:
const bson = require('bson')
bson.BSON_BINARY_SUBTYPE_DEFAULT
bson.BSON_BINARY_SUBTYPE_FUNCTION
bson.BSON_BINARY_SUBTYPE_BYTE_ARRAY
bson.BSON_BINARY_SUBTYPE_UUID
bson.BSON_BINARY_SUBTYPE_MD5
bson.BSON_BINARY_SUBTYPE_USER_DEFINED
doc.buffer.toObject(bson.BSON_BINARY_SUBTYPE_USER_DEFINED);
MongooseBuffer.mixin.write()
Type:
- «property»
Writes the buffer.
Decimal128()
- MongooseMap.prototype.$isMongooseMap
- MongooseMap.prototype.clear()
- MongooseMap.prototype.delete()
- MongooseMap.prototype.get()
- MongooseMap.prototype.set()
- MongooseMap.prototype.toBSON()
- MongooseMap.prototype.toJSON()
MongooseMap.prototype.$isMongooseMap
Type:
- «property»
Set to true
for all Mongoose map instances
MongooseMap.prototype.clear()
Overwrites native Map's clear()
function to support change tracking.
MongooseMap.prototype.delete()
Overwrites native Map's delete()
function to support change tracking.
MongooseMap.prototype.get()
Overwrites native Map's get()
function to support Mongoose getters.
MongooseMap.prototype.set()
Overwrites native Map's set()
function to support setters, populate()
,
and change tracking. Note that Mongoose maps only support strings and
ObjectIds as keys.
Example:
doc.myMap.set('test', 42); // works
doc.myMap.set({ obj: 42 }, 42); // Throws "Mongoose maps only support string keys"
MongooseMap.prototype.toBSON()
Converts this map to a native JavaScript Map so the MongoDB driver can serialize it.
MongooseMap.prototype.toJSON()
Parameters
- [options] «Object»
- [options.flattenMaps=false]
«Boolean» set to
true
to convert the map to a POJO rather than a native JavaScript map
Converts this map to a native JavaScript Map for JSON.stringify()
. Set
the flattenMaps
option to convert this map to a POJO instead.
Example:
doc.myMap.toJSON() instanceof Map; // true
doc.myMap.toJSON({ flattenMaps: true }) instanceof Map; // false