- Mongoose.prototype.Connection()
- Mongoose.prototype.Decimal128
- Example:
- Mongoose.prototype.DocumentProvider()
- Mongoose.prototype.Mixed
- Example:
- Mongoose.prototype.Mongoose()
- Mongoose.prototype.Number
- Example:
- Mongoose.prototype.Promise
- Mongoose.prototype.PromiseProvider()
- Mongoose.prototype.STATES
- Mongoose.prototype.Schema()
- Mongoose.prototype.SchemaType()
- Mongoose.prototype.SchemaTypes
- Note:
- Types:
- Mongoose.prototype.connect()
- Mongoose.prototype.connection
- Example:
- Mongoose.prototype.createConnection()
- Mongoose.prototype.deleteModel()
- Mongoose.prototype.disconnect()
- Mongoose.prototype.isValidObjectId()
- Mongoose.prototype.model()
- Example:
- Mongoose.prototype.mongo
- Mongoose.prototype.mquery
- Mongoose.prototype.now()
- Mongoose.prototype.pluralize()
- Currently supported options are
- Mongoose.prototype.trusted()
- Mongoose.prototype.version
- Example
- Schema.Types
- Example:
- Schema.indexTypes
- Schema.prototype.add()
- Schema.prototype.childSchemas
- Schema.prototype.clone()
- Example:
- Example:
- Example:
- Schema.prototype.indexes()
- Example:
- Schema.prototype.method()
- Example
- Schema.prototype.path()
- Example
- Example:
- Schema.prototype.pick()
- Schema.prototype.plugin()
- Example:
- Schema.prototype.queue()
- Example:
- Example:
- Example:
- Schema.prototype.static()
- Example
- Schema.prototype.virtualpath()
- Schema.reserved
- Connection
- Connection.prototype.client
- Connection.prototype.close()
- Connection.prototype.collections
- Connection.prototype.config
- Connection.prototype.createCollection()
- Example:
- Connection.prototype.dropDatabase()
- Connection.prototype.get()
- Example:
- Connection.prototype.host
- Example
- Connection.prototype.model()
- Connection.prototype.modelNames()
- Connection.prototype.models
- Example
- Connection.prototype.openUri()
- Connection.prototype.pass
- Example
- Example:
- Connection.prototype.port
- Example
- Connection.prototype.set()
- Supported options include
- Connection.prototype.setClient()
- Example:
- Example:
- Example:
- Connection.prototype.user
- Example
- The ChangeStream object is an event emitter that emits the following events
- Document
- Document.prototype.$ignore()
- Example:
- Example
- Example:
- Document.prototype.$isNew
- Document.prototype.$locals
- Example:
- Document.prototype.$parent()
- Example:
- Document.prototype.depopulate()
- Document.prototype.directModifiedPaths()
- Example
- Document.prototype.errors
- Document.prototype.get()
- Example
- Document.prototype.id
- Note:
- Document.prototype.invalidate()
- Example
- Example
- Document.prototype.isModified()
- Document.prototype.isNew
- Document.prototype.isSelected()
- Document.prototype.markModified()
- Example:
- Document.prototype.overwrite()
- Document.prototype.parent()
- Example:
- Example:
- Valid options:
- Example:
- Document.prototype.schema
- Document.prototype.set()
- Example:
- Document.prototype.toObject()
- Getters/Virtuals
- Example
- Document.prototype.update()
- Valid options:
- Example:
- Document.prototype.validate()
- Example:
- Note:
- Model
- Model.aggregate()
- NOTE:
- Model.buildBulkWriteOperations()
- Model.bulkSave()
- Model.bulkWrite()
- Model.cleanIndexes()
- Example:
- Example:
- Example:
- Model.createIndexes()
- Example:
- Model.deleteOne()
- Note:
- Example:
- Example
- Example:
- Model.estimatedDocumentCount()
- Model.events
- Example:
- Example:
- Examples:
- Example:
- Model.findByIdAndRemove()
- Examples:
- Options:
- Note:
- Note:
- Example:
- Options:
- Model.findOneAndRemove()
- Examples:
- Options:
- Model.findOneAndUpdate()
- Examples:
- Example:
- Model.hydrate()
- Model.init()
- Example:
- Example:
- Model.mapReduce()
- Other options:
- Example:
- Available top-level options:
- Model.prototype.$where
- Model.prototype.$where()
- Example:
- Model.prototype.modelName
- Model.prototype.remove()
- Example:
- Example:
- Model.prototype.schema
- Model.remove()
- Note:
- Example:
- Example:
- Example:
- Example:
- Model.update()
- Valid options:
- Example:
- Model.updateMany()
- Model.updateOne()
- Model.validate()
- Model.watch()
- increment()
- Query
- Query.prototype.$where()
- NOTE:
- Query.prototype.allowDiskUse()
- Query.prototype.and()
- Query.prototype.batchSize()
- Example
- Query.prototype.box()
- Query.prototype.cast()
- Query.prototype.catch()
- Query.prototype.centerSphere()
- Query.prototype.circle()
- Query.prototype.clone()
- Example:
- Query.prototype.comment()
- Example
- Query.prototype.count()
- Query.prototype.countDocuments()
- Query.prototype.cursor()
- Valid options
- Example
- Query.prototype.deleteOne()
- Example
- Example
- Example
- Example
- Example:
- Query.prototype.estimatedDocumentCount()
- Query.prototype.exec()
- Query.prototype.exists()
- Query.prototype.explain()
- Query.prototype.find()
- Query.prototype.findOne()
- Query.prototype.findOneAndDelete()
- Callback Signature
- Query.prototype.findOneAndRemove()
- Callback Signature
- Query.prototype.findOneAndReplace()
- Callback Signature
- Query.prototype.findOneAndUpdate()
- Callback Signature
- Query.prototype.geometry()
- NOTE:
- Example:
- Query.prototype.getOptions()
- Example:
- Example:
- Query.prototype.getUpdate()
- Example:
- Query.prototype.gte()
- Query.prototype.hint()
- Note
- Example
- NOTE:
- This option is only valid for operations that write to the database
- Query.prototype.lean()
- Query.prototype.limit()
- Example
- Query.prototype.lt()
- Query.prototype.lte()
- Query.prototype.map()
- Query.prototype.maxDistance()
- Query.prototype.maxScan()
- Example
- Query.prototype.maxTimeMS()
- Query.prototype.maxscan()
- Query.prototype.mod()
- Query.prototype.model
- Example:
- Query.prototype.ne()
- Query.prototype.near()
- Query.prototype.nearSphere()
- Example
- Example
- Example:
- Example
- Example:
- Example:
- Example:
- Example:
- Preferences:
- Query.prototype.readConcern()
- Read Concern Level:
- Example
- Note
- Example:
- Example
- Example:
- Example:
- Options:
- Query.prototype.setUpdate()
- Query.prototype.size()
- Example
- Note
- Example:
- Example
- Note
- Example
- Query.prototype.tailable()
- Example
- Query.prototype.then()
- Query.prototype.update()
- Valid options:
- Note
- Example:
- Example:
- This option is only valid for operations that write to the database
- Query.prototype.where()
- Query.prototype.within()
- Example
- NOTE:
- Sets the 3 write concern parameters for this query
- This option is only valid for operations that write to the database
- QueryCursor
- QueryCursor.prototype.close()
- Example
- Example
- function Object() { [native code] }.prototype.options
- Aggregate
- Examples:
- Aggregate.prototype.append()
- Aggregate.prototype.catch()
- Example:
- Examples:
- Example:
- Example:
- Example:
- Example:
- Examples:
- Examples:
- Aggregate.prototype.limit()
- Aggregate.prototype.lookup()
- Aggregate.prototype.match()
- Aggregate.prototype.model()
- Aggregate.prototype.near()
- Examples:
- Example:
- Examples:
- Example:
- Example:
- Example:
- Examples:
- Examples:
- Example:
- Aggregate.prototype.skip()
- Aggregate.prototype.sort()
- Aggregate.prototype.sortByCount()
- Aggregate.prototype.then()
- Aggregate.prototype.unwind()
- AggregationCursor
- AggregationCursor.prototype.close()
- AggregationCursor.prototype.map()
- AggregationCursor.prototype.next()
- Example:
- SchemaType.prototype.get()
- SchemaType.prototype.immutable()
- Example:
- Example:
- 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()
- Error message templates:
- Schematype.cast()
- Schematype.cast()
- Schematype.checkRequired()
- Schematype.get()
- Schematype.set()
- Virtualtype
- VirtualType.prototype.applyGetters()
- VirtualType.prototype.get()
- VirtualType.prototype.set()
- Error
- Error.CastError
- Error.DivergentArrayError
- Error.DocumentNotFoundError
- Error.MissingSchemaError
- Error.OverwriteModelError
- Error.ParallelSaveError
- Error.StrictModeError
- Error.ValidationError
- Error.ValidatorError
- Example:
- SchemaArray.checkRequired()
- SchemaArray.options
- SchemaArray.prototype.checkRequired()
- SchemaArray.schemaName
- SchemaArray.set()
- DocumentArrayPath
- DocumentArrayPath.options
- DocumentArrayPath.prototype.discriminator()
- DocumentArrayPath.schemaName
- SubdocumentPath
- SubdocumentPath.prototype.discriminator()
- SchemaTypeOptions
- SchemaTypeOptions.prototype.default
- SchemaTypeOptions.prototype.immutable
- SchemaTypeOptions.prototype.index
- SchemaTypeOptions.prototype.ref
- SchemaTypeOptions.prototype.required
- SchemaTypeOptions.prototype.select
- SchemaTypeOptions.prototype.sparse
- SchemaTypeOptions.prototype.text
- SchemaTypeOptions.prototype.transform
- Example:
- SchemaArrayOptions.prototype.of
- Example:
- SchemaDateOptions
- SchemaObjectIdOptions
- SchemaStringOptions
API Docs
- Mongoose()
- Mongoose.prototype.CastError()
- Mongoose.prototype.Connection()
- Mongoose.prototype.Decimal128
- Mongoose.prototype.DocumentProvider()
- Mongoose.prototype.Mixed
- Mongoose.prototype.Mongoose()
- Mongoose.prototype.ObjectId
- Mongoose.prototype.PromiseProvider()
- Mongoose.prototype.STATES
- Mongoose.prototype.SchemaType()
- Mongoose.prototype.SchemaTypes
- Mongoose.prototype.VirtualType()
- Mongoose.prototype.connection
- Mongoose.prototype.createConnection()
- Mongoose.prototype.disconnect()
- Mongoose.prototype.get()
- Mongoose.prototype.model()
- Mongoose.prototype.mongo
- Mongoose.prototype.now()
- Mongoose.prototype.pluralize()
- Mongoose.prototype.set()
- Mongoose.prototype.trusted()
- Schema.Types
- Schema.prototype.add()
- Schema.prototype.clone()
- Schema.prototype.get()
- Schema.prototype.indexes()
- Schema.prototype.method()
- Schema.prototype.path()
- Schema.prototype.paths
- Schema.prototype.plugin()
- Schema.prototype.pre()
- Schema.prototype.remove()
- Schema.prototype.set()
- Schema.prototype.virtual()
- Schema.prototype.virtuals
- Connection.prototype.asPromise()
- Connection.prototype.close()
- Connection.prototype.collections
- Connection.prototype.createCollection()
- Connection.prototype.deleteModel()
- Connection.prototype.dropDatabase()
- Connection.prototype.getClient()
- Connection.prototype.id
- Connection.prototype.modelNames()
- Connection.prototype.name
- Connection.prototype.pass
- Connection.prototype.plugins
- Connection.prototype.readyState
- Connection.prototype.setClient()
- Connection.prototype.transaction()
- Connection.prototype.user
- Document.prototype.$getAllSubdocs()
- Document.prototype.$isDefault()
- Document.prototype.$isEmpty()
- Document.prototype.$locals
- Document.prototype.$op
- Document.prototype.$session()
- Document.prototype.$where
- Document.prototype.directModifiedPaths()
- Document.prototype.errors
- Document.prototype.getChanges()
- Document.prototype.init()
- Document.prototype.invalidate()
- Document.prototype.isDirectSelected()
- Document.prototype.isModified()
- Document.prototype.isSelected()
- Document.prototype.modifiedPaths()
- Document.prototype.parent()
- Document.prototype.populated()
- Document.prototype.save()
- Document.prototype.set()
- Document.prototype.toObject()
- Document.prototype.undefined
- Document.prototype.update()
- Document.prototype.validate()
- Model.aggregate()
- Model.bulkSave()
- Model.cleanIndexes()
- Model.countDocuments()
- Model.createCollection()
- Model.deleteMany()
- Model.diffIndexes()
- Model.distinct()
- Model.estimatedDocumentCount()
- Model.exists()
- Model.findById()
- Model.findByIdAndRemove()
- Model.findOne()
- Model.findOneAndRemove()
- Model.findOneAndUpdate()
- Model.init()
- Model.inspect()
- Model.mapReduce()
- Model.prototype.$where
- Model.prototype.base
- Model.prototype.collection
- Model.prototype.deleteOne()
- Model.prototype.model()
- Model.prototype.remove()
- Model.prototype.schema
- Model.replaceOne()
- Model.syncIndexes()
- Model.update()
- Model.updateOne()
- Model.watch()
- increment()
- Query()
- Query.prototype.Symbol.asyncIterator()
- Query.prototype.allowDiskUse()
- Query.prototype.batchSize()
- Query.prototype.cast()
- Query.prototype.center()
- Query.prototype.circle()
- Query.prototype.collation()
- Query.prototype.count()
- Query.prototype.cursor()
- Query.prototype.deleteOne()
- Query.prototype.elemMatch()
- Query.prototype.error()
- Query.prototype.exec()
- Query.prototype.explain()
- Query.prototype.findOne()
- Query.prototype.findOneAndRemove()
- Query.prototype.findOneAndUpdate()
- Query.prototype.get()
- Query.prototype.getOptions()
- Query.prototype.getQuery()
- Query.prototype.gt()
- Query.prototype.hint()
- Query.prototype.intersects()
- Query.prototype.lean()
- Query.prototype.lt()
- Query.prototype.map()
- Query.prototype.maxScan()
- Query.prototype.maxscan()
- Query.prototype.mod()
- Query.prototype.mongooseOptions()
- Query.prototype.near()
- Query.prototype.nin()
- Query.prototype.or()
- Query.prototype.polygon()
- Query.prototype.post()
- Query.prototype.projection()
- Query.prototype.readConcern()
- Query.prototype.remove()
- Query.prototype.select()
- Query.prototype.selectedExclusively()
- Query.prototype.session()
- Query.prototype.setOptions()
- Query.prototype.setUpdate()
- Query.prototype.skip()
- Query.prototype.slice()
- Query.prototype.sort()
- Query.prototype.then()
- Query.prototype.update()
- Query.prototype.updateOne()
- Query.prototype.w()
- Query.prototype.within()
- Query.prototype.wtimeout()
- Query.prototype.Symbol.asyncIterator()
- QueryCursor.prototype.addCursorFlag()
- QueryCursor.prototype.eachAsync()
- QueryCursor.prototype.next()
- Aggregate.prototype.Symbol.asyncIterator()
- Aggregate.prototype.allowDiskUse()
- Aggregate.prototype.catch()
- Aggregate.prototype.count()
- Aggregate.prototype.exec()
- Aggregate.prototype.facet()
- Aggregate.prototype.group()
- Aggregate.prototype.limit()
- Aggregate.prototype.match()
- Aggregate.prototype.near()
- Aggregate.prototype.options
- Aggregate.prototype.project()
- Aggregate.prototype.readConcern()
- Aggregate.prototype.replaceRoot()
- Aggregate.prototype.search()
- Aggregate.prototype.skip()
- Aggregate.prototype.sortByCount()
- Aggregate.prototype.unwind()
- AggregationCursor()
- AggregationCursor.prototype.addCursorFlag()
- AggregationCursor.prototype.eachAsync()
- AggregationCursor.prototype.next()
- SchemaType()
- SchemaType.prototype.default()
- SchemaType.prototype.immutable()
- SchemaType.prototype.ref()
- SchemaType.prototype.select()
- SchemaType.prototype.sparse()
- SchemaType.prototype.transform()
- SchemaType.prototype.validate()
- Schematype.cast()
- Schematype.get()
- Error.CastError
- Error.DocumentNotFoundError
- Error.OverwriteModelError
- Error.StrictModeError
- Error.ValidatorError
- Error.messages
- Mongoose()
- Mongoose.prototype.CastError()
- Mongoose.prototype.Connection()
- Mongoose.prototype.Decimal128
- Mongoose.prototype.DocumentProvider()
- Mongoose.prototype.Mixed
- Mongoose.prototype.Mongoose()
- Mongoose.prototype.ObjectId
- Mongoose.prototype.PromiseProvider()
- Mongoose.prototype.STATES
- Mongoose.prototype.SchemaType()
- Mongoose.prototype.SchemaTypes
- Mongoose.prototype.VirtualType()
- Mongoose.prototype.connection
- Mongoose.prototype.createConnection()
- Mongoose.prototype.disconnect()
- Mongoose.prototype.get()
- Mongoose.prototype.model()
- Mongoose.prototype.mongo
- Mongoose.prototype.now()
- Mongoose.prototype.pluralize()
- Mongoose.prototype.set()
- Mongoose.prototype.trusted()
Parameters
- options «Object» see
Mongoose constructor.
The exports object of the mongoose
module is an instance of this class. Most apps will only use this one instance.
Example:
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
The Mongoose Collection constructor
The Mongoose Connection constructor
Mongoose.prototype.Date
Type:
- «property»
The Mongoose Date SchemaType.
Example:
const schema = new Schema({ test: Date });
schema.path('test') instanceof mongoose.Date; // true
Type:
- «property»
The Mongoose Decimal128 . 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 });
The Mongoose Document constructor.
Mongoose.prototype.DocumentProvider()
The Mongoose DocumentProvider constructor. Mongoose users should not have to use this directly
Mongoose.prototype.Error()
The constructor.
Type:
- «property»
The Mongoose Mixed . 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 constructor.
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' });
Type:
- «property»
The Mongoose ObjectId . 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 });
Type:
- «property»
The Mongoose constructor.
Storage layer for mongoose promises
The Mongoose Query constructor.
Mongoose.prototype.STATES
Type:
- «property»
Expose connection states for user-land
The Mongoose Schema constructor
Example:
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const CatSchema = new Schema(..);
The Mongoose SchemaType constructor
Mongoose.prototype.SchemaTypeOptions()
The constructor used for schematype options
Mongoose.prototype.SchemaTypes
Type:
- «property»
The various Mongoose SchemaTypes.
Note:
Alias of mongoose.Schema.Types for backwards compatibility.
Mongoose.prototype.Types
Type:
- «property»
The various Mongoose Types.
Example:
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;
The Mongoose VirtualType constructor
Mongoose.prototype.connect()
Parameters
- uri(s) «String»
[options] «Object» passed down to the MongoDB driver’s
connect()
function, except for 4 mongoose-specific options explained below.[options.bufferCommands=true] «Boolean» Mongoose specific option. Set to false to 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.reconnectTries=30] «Number» If you’re connected to a single server or mongos proxy (as opposed to a replica set), the MongoDB driver will try to reconnect every
reconnectInterval
milliseconds forreconnectTries
times, and give up afterward. When the driver gives up, the mongoose connection emits areconnectFailed
event. This option does nothing for replica set connections.[options.reconnectInterval=1000] «Number» See
reconnectTries
option above.[options.promiseLibrary] «Class» Sets the .
[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 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@localhost:port/database');
// replica sets
const uri = 'mongodb://user:pass@localhost: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.connection.on('error', cb);
This is the connection used by default for every model created using mongoose.model.
To create a new connection, use .
Type:
- «Array»
An array containing all 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://localhost:27017/test');
mongoose.connections.length; // 2
Parameters
[uri] «String» a mongodb:// URI
[options] «Object» passed down to the , except for 4 mongoose-specific options explained below.
[options.bufferCommands=true] «Boolean» Mongoose specific option. Set to false to disable buffering on all models associated with this connection.
[options.dbName] «String» The name of the database you want to use. If not provided, Mongoose uses the database name from connection string.
[options.user] «String» username for authentication, equivalent to
options.auth.user
. Maintained for backwards compatibility.[options.pass] «String» password for authentication, equivalent to
options.auth.password
. Maintained for backwards compatibility.[options.autoIndex=true] «Boolean» Mongoose-specific option. Set to false to disable automatic index creation for all models associated with this connection.
[options.reconnectTries=30] «Number» If you’re connected to a single server or mongos proxy (as opposed to a replica set), the MongoDB driver will try to reconnect every
reconnectInterval
milliseconds forreconnectTries
times, and give up afterward. When the driver gives up, the mongoose connection emits areconnectFailed
event. This option does nothing for replica set connections.[options.reconnectInterval=1000] «Number» See
reconnectTries
option above.[options.promiseLibrary] «Class» Sets the .
[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 .
[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 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 thenable, so you can do
await mongoose.createConnection()
Creates a Connection instance.
Each connection
instance maps to a single database. This method is helpful when managing multiple db connections.
Options passed take precedence over options included in connection strings.
Example:
// with mongodb:// URI
db = mongoose.createConnection('mongodb://user:pass@localhost:port/database');
// and options
const opts = { db: { native_parser: true }}
db = mongoose.createConnection('mongodb://user:pass@localhost:port/database', opts);
// replica sets
db = mongoose.createConnection('mongodb://user:pass@localhost:port,anotherhost:port,yetanother:port/database');
// and options
const opts = { replset: { strategy: 'ping', rs_name: 'testSet' }}
db = mongoose.createConnection('mongodb://user:pass@localhost:port,anotherhost:port,yetanother:port/database', opts);
// and options
const opts = { server: { auto_reconnect: false }, user: 'username', pass: 'mypassword' }
db = mongoose.createConnection('localhost', 'database', port, opts)
// initialize now, connect later
db = mongoose.createConnection();
db.openUri('localhost', 'database', port, [opts]);
Mongoose.prototype.deleteModel()
Parameters
- name «String|RegExp» if string, the name of the model to remove. If regexp, removes all models whose name matches the regexp.
Returns:
- «Mongoose» this
Removes the model named name
from the default connection, if it exists. You can use this function to clean up any models you created in your tests to prevent OverwriteModelErrors.
Equivalent to mongoose.connection.deleteModel(name)
.
Example:
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
});
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.
Type:
- «property»
Object with get()
and set()
containing the underlying driver this Mongoose instance uses to communicate with the database. A driver is a Mongoose-specific interface that defines functions like find()
.
Mongoose.prototype.get()
Parameters
- key «String»
Gets mongoose options
Example:
mongoose.get('test') // returns the 'test' value
Mongoose.prototype.isValidObjectId()
Returns true if Mongoose can cast the given value to an ObjectId, or false otherwise.
Example:
mongoose.isValidObjectId(new mongoose.Types.ObjectId()); // true
mongoose.isValidObjectId('0123456789ab'); // true
mongoose.isValidObjectId(6); // false
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)
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()
.
Type:
- «property»
The driver Mongoose uses.
Type:
- «property»
The query builder Mongoose uses.
Mongoose uses this function to get the current time when setting timestamps. You may stub out this function using a tool like for testing.
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.
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.
Parameters
- filter «Object»
Sanitizes query filters against 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 } } });
Parameters
- key «String»
- value «String|Function|Boolean»
Sets mongoose options
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
Currently supported options are
- ‘debug’: If
true
, prints the operations mongoose sends to MongoDB to the console. If a writable stream is passed, it will log to that stream, without colorization. If a callback function is passed, it will receive the collection name, the method name, then all arugments passed to the method. For example, if you wanted to replicate the default logging, you could output from the callbackMongoose: ${collectionName}.${methodName}(${methodArgs.join(', ')})
. - ‘returnOriginal’: If
false
, changes the defaultreturnOriginal
option tofindOneAndUpdate()
,findByIdAndUpdate
, andfindOneAndReplace()
to false. This is equivalent to setting thenew
option totrue
forfindOneAndX()
calls by default. Read our for more information. - ‘bufferCommands’: enable/disable mongoose’s buffering mechanism for all connections and models
- ‘cloneSchemas’: false by default. Set to
true
toclone()
all schemas before compiling into a model. - ‘applyPluginsToDiscriminators’: false by default. Set to true to apply global plugins to discriminator schemas. This typically isn’t necessary because plugins are applied to the base schema and discriminators copy all middleware, methods, statics, and properties from the base schema.
- ‘applyPluginsToChildSchemas’: true by default. Set to false to skip applying global plugins to child schemas
- ‘objectIdGetter’: true by default. Mongoose adds a getter to MongoDB ObjectId’s called
_id
that returnsthis
for convenience with populate. Set this to false to remove the getter. - ‘runValidators’: false by default. Set to true to enable update validators for all validators by default.
- ‘toObject’:
{ transform: true, flattenDecimals: true }
by default. Overwrites default objects to - ‘toJSON’:
{ transform: true, flattenDecimals: true }
by default. Overwrites default objects totoJSON()
, for determining how Mongoose documents get serialized byJSON.stringify()
- ‘strict’: true by default, may be
false
,true
, or'throw'
. Sets the default strict mode for schemas. - ‘strictQuery’: false by default, may be
false
,true
, or'throw'
. Sets the default mode for schemas. - ‘selectPopulatedPaths’: true by default. Set to false to opt out of Mongoose adding all fields that you
populate()
to yourselect()
. The schema-level optionselectPopulatedPaths
overwrites this one. - ‘maxTimeMS’: If set, attaches maxTimeMS to every query
- ‘autoIndex’: true by default. Set to false to disable automatic index creation for all models associated with this Mongoose instance.
- ‘autoCreate’: Set to
true
to make Mongoose call 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. - ‘overwriteModels’: Set to
true
to default to overwriting models with the same name when callingmongoose.model()
, as opposed to throwing anOverwriteModelError
.
Parameters
[options] «Object» see the
[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 for benefits like causal consistency, retryable writes, and .
Calling mongoose.startSession()
is equivalent to calling mongoose.connection.startSession()
. Sessions are scoped to a connection, so calling mongoose.startSession()
starts a session on the default mongoose connection.
Mongoose.prototype.trusted()
Parameters
- obj «Object»
Tells sanitizeFilter()
to skip the given object when filtering out potential query selector injection attacks. Use this method when you have a known query selector that you want to use.
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»
The Mongoose version
Example
console.log(mongoose.version); // '5.x.x'
Schema
- Schema.Types
- Schema.prototype.add()
- Schema.prototype.clone()
- Schema.prototype.get()
- Schema.prototype.indexes()
- Schema.prototype.method()
- Schema.prototype.path()
- Schema.prototype.paths
- Schema.prototype.plugin()
- Schema.prototype.pre()
- Schema.prototype.remove()
- Schema.prototype.set()
- Schema.prototype.virtual()
- Schema.prototype.virtuals
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:
- : 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)
- : 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. - : bool - defaults to false
- collection: string - no default
- : string - defaults to
__t
- id: bool - defaults to true
- : bool - defaults to true
- minimize: bool - controls behavior when called manually - defaults to true
- read: string
- : object - defaults to null, use to override the MongoDB server’s default write concern settings
- : object - defaults to
null
- strict: bool - defaults to true
- : bool - defaults to false
- toJSON - object - no default
- - object - no default
- typeKey - string - defaults to ‘type’
- - bool - defaults to
true
- versionKey: string or object - defaults to “__v”
- : bool - defaults to false. Set to true to enable optimistic concurrency.
- : object - defaults to null (which means use no collation)
- selectPopulatedPaths: boolean - defaults to
true
- : 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.
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 })
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 });
Type:
- «property»
Array of child schemas (from document arrays and single nested subdocs) and their corresponding compiled models. Each element of the array is an object with 2 properties: schema
and model
.
This property is typically only useful for plugin authors and advanced users. You do not need to interact with this property at all to use mongoose.
Schema.prototype.clone()
Returns:
- «Schema» the cloned schema
Returns a deep copy of the schema
Example:
const schema = new Schema({ name: String });
const clone = schema.clone();
clone === schema; // false
clone.path('name'); // SchemaString { ... }
Schema.prototype.eachPath()
Parameters
- fn «Function» callback function
Returns:
- «Schema» this
Iterates the schemas paths similar to Array#forEach.
The callback is passed the pathname and the schemaType instance.
Example:
const userSchema = new Schema({ name: String, registeredAt: Date });
userSchema.eachPath((pathname, schematype) => {
// Prints twice:
// name SchemaString { ... }
// registeredAt SchemaDate { ... }
console.log(pathname, schematype);
});
Parameters
- key «String» option name
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»
[options] «Object» Options to pass to MongoDB driver’s
createIndex()
function| «String» number} [options.expires=null] Mongoose-specific syntactic sugar, uses to convert
expires
option into seconds for theexpireAfterSeconds
in the above link.
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();
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;
}
}
}
Parameters
- model «Function»
- [virtualsOnly] «Boolean» if truthy, only pulls virtuals from the class, not methods or statics
Loads an ES6 class into a schema. Maps + getters, , and instance methods to schema , statics, and .
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
method «String|Object» name
[fn] «Function»
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
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
Type:
- «property»
The original object passed to the schema constructor
Example:
const schema = new Schema({ a: String }).add({ b: String });
schema.obj; // { a: String }
Parameters
- path «String»
- constructor «Object»
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
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» list of paths to pick
[options] «Object» options to pass to the schema constructor. Defaults to
this.options
if not set.
Returns:
- «Schema»
Returns a new schema that has the picked paths
from this schema.
This method is analagous to 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» callback
[opts] «Object»
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'
Schema.prototype.post()
Parameters
The «String|RegExp» method name or regular expression to match method name
[options] «Object»
[options.document] «Boolean» If
name
is a hook for both document and query middleware, set 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');
});
Parameters
The «String|RegExp» method name or regular expression to match method name
[options] «Object»
[options.document] «Boolean» If
name
is a hook for both document and query middleware, set 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()`
});
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" }'
Parameters
- path «String|Array»
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 { ... }
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' ]
Parameters
key «String» option name
[value] «Object» if not passed, the current option value is returned
Sets a schema option.
Example
schema.set('strict'); // 'true' by default
schema.set('strict', false); // Sets 'strict' to false
schema.set('strict'); // 'false'
Parameters
- name «String|Object»
- [fn] «Function»
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 statics.
Parameters
- name «String»
[options] «Object»
[options.ref] «String|Model» model name or model instance. Marks this as a .
[options.localField] «String|Function» Required for populate virtuals. See populate virtual docs for more information.
[options.foreignField] «String|Function» Required for populate virtuals. See 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 , 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.
Parameters
- name «String»
Returns:
- «VirtualType»
Returns the virtual type with the given name
.
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
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.close()
- Connection.prototype.collections
- Connection.prototype.createCollection()
- Connection.prototype.deleteModel()
- Connection.prototype.dropDatabase()
- Connection.prototype.getClient()
- Connection.prototype.id
- Connection.prototype.modelNames()
- Connection.prototype.name
- Connection.prototype.pass
- Connection.prototype.plugins
- Connection.prototype.readyState
- Connection.prototype.setClient()
- Connection.prototype.transaction()
- Connection.prototype.user
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://localhost: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.
Parameters
[force] «Boolean» optional
[callback] «Function» optional
Returns:
- «Promise»
Closes the connection
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.
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
Parameters
collection «string» The collection to create
[options] «Object» see
[callback] «Function»
Returns:
- «Promise»
Helper for createCollection()
. Will explicitly create the given collection with specified options. Used to create and views from mongoose.
Options are passed down without modification to the
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
});
Parameters
collection «string» The collection to delete
[callback] «Function»
Returns:
- «Promise»
Helper for dropCollection()
. Will delete the given collection, including all documents and indexes.
Parameters
- [callback] «Function»
Returns:
- «Promise»
Helper for dropDatabase()
. Deletes the given database, including all collections, documents, and indexes.
Example:
const conn = mongoose.createConnection('mongodb://localhost: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://localhost:27017/test');
conn.getClient(); // MongoClient { ... }
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://localhost:27017/mydb').host; // "localhost"
Type:
- «property»
A number identifier for this connection. Used for debugging when you have .
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 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»
Returns an array of model names created on this connection.
Type:
- «property»
A 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
Type:
- «property»
The name of the database this connection points to.
Example
mongoose.createConnection('mongodb://localhost:27017/mydb').name; // "mydb"
Parameters
uri «String» The URI to connect with.
[options] «Object» Passed on to
[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 .
[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 .
[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 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@localhost:27017/mydb').pass; // "psw"
Connection.prototype.plugin()
Parameters
fn «Function» plugin callback
[opts] «Object» optional options
Returns:
- «Connection» this
Declares a plugin executed on all schemas you pass to conn.model()
Equivalent to calling .plugin(fn)
on each schema you create.
Example:
const db = mongoose.createConnection('mongodb://localhost:27017/mydb');
db.plugin(() => console.log('Applied'));
db.plugins.length; // 1
db.model('Test', new Schema({})); // Prints "Applied"
Type:
- «property»
The plugins that will be applied to all models created on this connection.
Example:
const db = mongoose.createConnection('mongodb://localhost:27017/mydb');
db.plugin(() => console.log('Applied'));
db.plugins.length; // 1
db.model('Test', new Schema({})); // Prints "Applied"
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://localhost:27017/mydb').port; // 27017
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);
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.
Example:
conn.set('test', 'foo');
conn.get('test'); // 'foo'
conn.options.test; // 'foo'
Returns:
- «Connection» this
Set the 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://localhost: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, , 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' });
Parameters
fn «Function» Function to execute in a transaction
[options] «mongodb.TransactionOptions» Optional settings for the transaction
Returns:
- «Promise<Any>» promise that is fulfilled if Mongoose successfully committed the transaction, or rejects if the transaction was aborted or if Mongoose failed to commit the transaction. If fulfilled, the promise resolves to a MongoDB command result.
Requires MongoDB >= 3.6.0. Executes the wrapped async function in a transaction. Mongoose will commit the transaction if the async function executes successfully and attempt to retry if there was a retriable error.
Calls the MongoDB driver’s session.withTransaction()
, but also handles resetting Mongoose document state as shown below.
Example:
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;
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 .
Returns:
- «Connection» New Connection Object
Switches to a different database using the same connection pool.
Returns a new connection object, with the new db.
Connection.prototype.user
Type:
- «property»
The username specified in the URI
Example
mongoose.createConnection('mongodb://val:psw@localhost: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.$errors
- Document.prototype.$ignore()
- Document.prototype.$isDeleted()
- Document.prototype.$isNew
- Document.prototype.$markValid()
- Document.prototype.$parent()
- Document.prototype.$set()
- Document.prototype.depopulate()
- Document.prototype.equals()
- Document.prototype.get()
- Document.prototype.id
- Document.prototype.inspect()
- Document.prototype.isDirectModified()
- Document.prototype.isInit()
- Document.prototype.isNew
- Document.prototype.markModified()
- Document.prototype.overwrite()
- Document.prototype.populate()
- Document.prototype.replaceOne()
- Document.prototype.schema
- Document.prototype.toJSON()
- Document.prototype.toString()
- Document.prototype.unmarkModified()
- Document.prototype.updateOne()
- Document.prototype.validateSync()
Document.prototype.$errors
Type:
- «property»
Hash containing current validation $errors.
Get all subdocs (by bfs)
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
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» 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
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 .
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.$isNew
Type:
- «property»
Boolean flag specifying if the document is new.
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);
});
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()
Alias for parent()
. If this document is a subdocument or populated document, returns the document’s parent. Returns undefined
otherwise.
Document.prototype.$session()
Parameters
- [session] «ClientSession» overwrite the current session
Returns:
- «ClientSession»
Getter/setter around the session associated with this document. Used to automatically set session
if you save()
a doc that you got from a query with an associated session.
Example:
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.
Parameters
path «String|Object» path or object of key/vals to set
val «Any» the value to set
[type] «Schema|String|Number|Buffer|*» optionally specify a type for “on-the-fly” attributes
[options] «Object» optionally specify options that modify the behavior of the set
Alias for set()
, used internally to avoid conflicts
Document.prototype.$where
Type:
- «property»
Set this property to add additional query filters when Mongoose saves this document and isNew
is false.
Example:
// Make sure `save()` never updates a soft deleted document.
schema.pre('save', function() {
this.$where = { isDeleted: false };
});
Document.prototype.depopulate()
Parameters
- path «String»
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.
Returns:
- «Array»
Returns the list of paths that have been directly modified. A direct modified path is a path that you explicitly set, whether via doc.foo = 'bar'
, Object.assign(doc, { foo: 'bar' })
, or doc.set('foo', 'bar')
.
A path a
may be in modifiedPaths()
but not in directModifiedPaths()
because a child of a
was directly modified.
Example
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']
Parameters
- doc «Document» a document to compare
Returns:
- «Boolean»
Returns true if this document is equal to another document.
Documents are considered equal when they have matching _id
s, unless neither document has an _id
, in which case this function falls back to using deepEqual()
.
Type:
- «property»
Hash containing current validation errors.
Document.prototype.get()
Parameters
- path «String»
[type] «Schema|String|Number|Buffer|*» optionally specify a type for on-the-fly attributes
[options] «Object»
[options.virtuals=false] «Boolean» Apply virtuals before getting this path
[options.getters=true] «Boolean» If false, skip applying getters and just get the raw value
Returns the value of a path.
Example
// 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
of its Schema
to false at construction time.
new Schema({ name: String }, { id: false });
Parameters
- doc «Object» document returned by mongo
Initializes the document without setters or marking anything modified.
Called internally after a document is returned from mongodb. Normally, you do not need to call this function on your own.
This function triggers init
. Note that init
hooks are synchronous.
Document.prototype.inspect()
Helper for console.log
Document.prototype.invalidate()
Parameters
path «String» the field to invalidate. For array elements, use the
array.i.field
syntax, wherei
is the 0-based index in the array.errorMsg «String|Error» the error which states the reason
path
was invalidvalue «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
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
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
Type:
- «property»
Boolean flag specifying if the document is new.
Document.prototype.isSelected()
Parameters
- path «String|Array<String>»
Returns:
- «Boolean»
Checks if path
was selected in the source query which initialized this document.
Example
const doc = await Thing.findOne().select('name');
doc.isSelected('name') // true
doc.isSelected('age') // false
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 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»
Returns the list of paths that have been modified.
Document.prototype.overwrite()
Parameters
- obj «Object» the object to overwrite this document with
Overwrite all values in this document with the values of obj
, except for immutable properties. Behaves similarly to set()
, except for it unsets all properties that aren’t in obj
.
If this document is a subdocument or populated document, returns the document’s parent. Returns undefined
otherwise.
Parameters
path «String|Object|Array» either the path to populate or an object specifying all parameters, or either an array of those
[select] «Object|String» Field selection for the population query
[model] «Model» The model you wish to use for population. If not specified, populate will look up the model by the name in the Schema’s
ref
field.[match] «Object» Conditions for the population query
[options] «Object» Options for the population query (sort, etc)
[options.path=null] «String» The path to populate.
[options.retainNullValues=false] «boolean» by default, Mongoose removes null and undefined values from populated arrays. Use this option to make
populate()
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 .[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»
Populates paths on an existing document.
Example:
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
await doc.populate('fans', '-email');
doc.fans[0].email // not populated
await doc.populate('author fans', '-email');
doc.author.email // not populated
doc.fans[0].email // not populated
Document.prototype.populated()
Parameters
- path «String»
Returns:
- «Array,ObjectId,Number,Buffer,String,undefined»
Gets _id(s) used during population of the given path
.
Example:
Model.findOne().populate('author').exec(function (err, doc) {
console.log(doc.author.name) // Dr.Seuss
console.log(doc.populated('author')) // '5144cf8050f071d979c118a7'
})
If the path was not populated, returns undefined
.
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
Parameters
[options] «Object» options optional options
[options.session=null] «Session» the associated with this save operation. If not specified, defaults to the document’s associated session.
[options.safe] «Object» (DEPRECATED) overrides . 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
[options.j] «Boolean» set to true for MongoDB to wait until this
save()
has been journaled before resolving the returned promise. Overrides the[options.wtimeout] «Number» sets a timeout for the write concern. Overrides the .
[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 are enabled, skip timestamps for thissave()
.[fn] «Function» optional callback
Returns:
- «Promise,undefined» Returns undefined if used with callback or a Promise otherwise.
Saves this document by inserting a new document into the database if 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.
Parameters
path «String|Object» path or object of key/vals to set
val «Any» the value to set
[type] «Schema|String|Number|Buffer|*» optionally specify a type for “on-the-fly” attributes
[options] «Object» optionally specify options that modify the behavior of the set
Sets the value of a path, or many paths.
Example:
// 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 });
Parameters
- options «Object»
Returns:
- «Object»
The return value of this method is used in calls to JSON.stringify(doc).
This method accepts the same options as Document#toObject. To apply the options to every document of your schema by default, set your toJSON
option to the same argument.
schema.set('toJSON', { virtuals: true })
See schema options for details.
Document.prototype.toObject()
Parameters
[options] «Object»
[options.getters=false] «Boolean» if true, apply all getters, including virtuals
[options.virtuals=false] «Boolean» if true, apply virtuals, including aliases. Use
{ getters: true, virtuals: false }
to just apply getters, not virtuals[options.aliases=true] «Boolean» if
options.virtuals = true
, you can 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
Converts this document into a plain-old JavaScript object ().
Buffers are converted to instances of mongodb.Binary for proper storage.
Options:
getters
apply all getters (path and virtual getters), defaults to falsealiases
apply all aliases ifvirtuals=true
, defaults to truevirtuals
apply virtual getters (can overridegetters
option), defaults to falseminimize
remove empty objects, defaults to truetransform
a transform function to apply to the resulting document before returningdepopulate
depopulate any populated paths, replacing them with their original refs, defaults to falseversionKey
whether to include the version key, defaults to trueflattenMaps
convert Maps to POJOs. Useful if you want to JSON.stringify() the result of toObject(), defaults to falseuseProjection
set totrue
to omit fields that are excluded in this document’s projection. Unless you specified a projection, this will omit any field that hasselect: false
in the schema.
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 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 is behavior is different for transforms defined in the schema
if you define a transform in schema.options.toObject.transform
, that transform will not apply to subdocuments.
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 for some more details.
During save, no custom options are applied to the document before being sent to the database.
Helper for console.log
Returns:
- «Array<Document>» array of populated documents. Empty array if there are no populated documents associated with this document.
Gets all populated documents associated with this document.
Document.prototype.unmarkModified()
Parameters
- path «String» the path to unmark modified
Clears the modified state on the specified path.
Example:
doc.foo = 'bar';
doc.unmarkModified('foo');
doc.save(); // changes to foo will not be persisted
Document.prototype.update()
Parameters
- doc «Object»
- options «Object»
- callback «Function»
Returns:
- «Query»
Sends an update command with this document _id
as the query selector.
Example:
weirdCar.update({$inc: {wheels:1}}, { w: 1 }, callback);
Valid options:
- same as in
Parameters
- doc «Object»
[options] «Object» optional see
[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 .[options.strict] «Boolean|String» overwrites the schema’s strict mode option
[options.timestamps=null] «Boolean» If set to
false
and 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
Parameters
[pathsToValidate] «Array|String» list of paths to validate. If set, Mongoose will validate only the modified paths that are in the given list.
[options] «Object» internal options
[options.validateModifiedOnly=false] «Boolean» if
true
mongoose validates only modified paths.[options.pathsToSkip] «Array|string» list of paths to skip. If set, Mongoose will validate every modified path that is not in this list.
[callback] «Function» optional callback called after validation completes, passing an error if one occurred
Returns:
- «Promise» Promise
Executes registered validation rules for this document.
Note:
This method is called pre
save and if a validation rule is violated, is aborted and the error is returned to your callback
.
Example:
doc.validate(function (err) {
if (err) handleError(err);
else // validation passed
});
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» 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.aggregate()
- Model.bulkSave()
- Model.cleanIndexes()
- Model.countDocuments()
- Model.createCollection()
- Model.deleteMany()
- Model.diffIndexes()
- Model.distinct()
- Model.estimatedDocumentCount()
- Model.exists()
- Model.findById()
- Model.findByIdAndRemove()
- Model.findOne()
- Model.findOneAndRemove()
- Model.findOneAndUpdate()
- Model.init()
- Model.inspect()
- Model.mapReduce()
- Model.prototype.$where
- Model.prototype.base
- Model.prototype.collection
- Model.prototype.deleteOne()
- Model.prototype.model()
- Model.prototype.remove()
- Model.prototype.schema
- Model.replaceOne()
- Model.syncIndexes()
- Model.update()
- Model.updateOne()
- Model.watch()
- increment()
Model()
Parameters
doc «Object» values for initial set
optional «[fields]» object containing the fields that were selected in the query which returned this document. You do not need to set this parameter to ensure Mongoose handles your query projection.
[skipId=false] «Boolean» optional boolean. If true, mongoose doesn’t add an
_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 .
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 functions create subclasses of mongoose.Model
as shown below.
Example:
// `UserModel` is a "Model", a subclass of `mongoose.Model`.
const UserModel = mongoose.model('User', new Schema({ name: String }));
// You can use a Model to create new documents using `new`:
const userDoc = new UserModel({ name: 'Foo' });
await userDoc.save();
// You also use a model to create queries:
const userFromDb = await UserModel.findOne({ name: 'Foo' });
Model.aggregate()
Parameters
[pipeline] «Array» aggregation pipeline as an array of objects
[options] «Object» aggregation options
[callback] «Function»
Returns:
- «Aggregate»
Performs 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.buildBulkWriteOperations()
Parameters
- options «Object»
- options.skipValidation «Boolean» defaults to
false
, when set to true, building the write operations will bypass validating the documents.
@param {[Document]} documents The array of documents to build write operations of
Parameters
- documents «[Document]»
takes an array of documents, gets the changes and inserts/updates documents in the database according to whether or not the document is new, or whether it has changes or not.
bulkSave
uses bulkWrite
under the hood, so it’s mostly useful when dealing with many documents (10K+)
Model.bulkWrite()
Parameters
ops «Array»
[ops.insertOne.document] «Object» The document to insert
[opts.updateOne.filter] «Object» Update the first document that matches this filter
[opts.updateOne.update] «Object» An object containing update operators
[opts.updateOne.upsert=false] «Boolean» If true, insert a doc if none match
[opts.updateOne.timestamps=true] «Boolean» If false, do not apply to the operation
[opts.updateOne.arrayFilters] «Array» The array filters used in
update
[opts.updateMany.filter] «Object» Update all the documents that match this filter
[opts.updateMany.update] «Object» An object containing
[opts.updateMany.upsert=false] «Boolean» If true, insert a doc if no documents match
filter
[opts.updateMany.timestamps=true] «Boolean» If false, do not apply timestamps to the operation
[opts.updateMany.collation] «Object» The to use
[opts.updateMany.arrayFilters] «Array» The array filters used in
update
[opts.deleteOne.filter] «Object» Delete the first document that matches this filter
[opts.deleteMany.filter] «Object» Delete all documents that match this filter
[opts.replaceOne.filter] «Object» Replace the first document that matches this filter
[opts.replaceOne.replacement] «Object» The replacement document
[opts.replaceOne.upsert=false] «Boolean» If true, insert a doc if no documents match
filter
[options] «Object»
[options.ordered=true] «Boolean» If true, execute writes in order and stop at the first error. If false, execute writes in parallel and continue until all writes have either succeeded or errored.
[options.session=null] «ClientSession» The session associated with this bulk write. See .
[options.w=1] «String|number» The write concern. See for more information.
[options.wtimeout=null] «number» The write concern timeout.
[options.j=true] «Boolean» If false, disable
[options.bypassDocumentValidation=false] «Boolean» If true, disable MongoDB server-side schema validation for all writes in this bulk.
[options.strict=null] «Boolean» Overwrites the on schema. If false, allows filtering and writing fields not defined in the schema for all writes in this bulk.
[callback] «Function» callback
function(error, bulkWriteOpResult) {}
Returns:
- «Promise» resolves to a 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.cleanIndexes()
Parameters
- [callback] «Function» optional callback
Returns:
- «Promise,undefined» Returns
undefined
if callback is specified, returns a promise if no callback.
Deletes all indexes that aren’t defined in this model’s schema. Used by syncIndexes()
.
The returned promise resolves to a list of the dropped indexes’ names as an array
Model.count()
Parameters
- filter «Object»
- [callback] «Function»
Returns:
- «Query»
Counts number of documents that match filter
in a database collection.
This method is deprecated. If you want to count the number of documents in a collection, e.g. count({})
, use the instead. Otherwise, use the countDocuments()
function instead.
Example:
const count = await Adventure.count({ type: 'jungle' });
console.log('there are %d jungle adventures', count);
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 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
:$near
:$geoWithin
with$nearSphere
:$geoWithin
with
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.[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
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 function.
Parameters
- conditions «Object»
[options] «Object» optional see
[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 to learn more.
Parameters
- conditions «Object»
[options] «Object» optional see
[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 to learn more.
Parameters
options «Object» not used at all.
callback «Function» optional callback
Does a dry-run of Model.syncIndexes(), meaning that the result of this function would be the result of Model.syncIndexes().
Model.discriminator()
Parameters
name «String» discriminator model name
schema «Schema» discriminator model schema
[options] «Object|String» If string, same as
options.value
.[options.value] «String» the string stored in the
discriminatorKey
property. If not specified, Mongoose uses thename
parameter.[options.clone=true] «Boolean» By default,
discriminator()
clones the givenschema
. Set tofalse
to skip cloning.
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
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:
After completion, an index
event is emitted on this Model
passing an error if one occurred.
Example:
const eventSchema = new Schema({ thing: { type: 'string', unique: true }})
const Event = mongoose.model('Event', eventSchema);
Event.on('index', function (err) {
if (err) console.error(err); // error occurred during index creation
})
NOTE: It is not recommended that you run this in production. Index creation may impact database performance depending on your load. Use with caution.
Model.estimatedDocumentCount()
Parameters
- [options] «Object»
- [callback] «Function»
Returns:
- «Query»
Estimates the number of documents in the MongoDB collection. Faster than using countDocuments()
for large collections because estimatedDocumentCount()
uses collection metadata rather than scanning the entire collection.
Example:
const numAdventures = Adventure.estimatedDocumentCount();
Type:
- «property»
Event emitter that reports any errors that occurred. Useful for global error handling.
Example:
MyModel.events.on('error', err => console.log(err.message));
// Prints a 'CastError' because of the above handler
await MyModel.findOne({ _id: 'notanid' }).catch(noop);
Parameters
- filter «Object»
[options] «Object» optional see
[callback] «Function» callback
Returns:
- «Query»
Returns true if at least one document exists in the database that matches the given filter
, and false otherwise.
Under the hood, MyModel.exists({ answer: 42 })
is equivalent to MyModel.findOne({ answer: 42 }).select({ _id: 1 }).lean()
Example:
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()
Parameters
- filter «Object|ObjectId»
[projection] «Object|String|Array<String>» optional fields to return, see
[options] «Object» optional see
Query.prototype.setOptions()
[callback] «Function»
Returns:
- «Query»
Finds documents.
Mongoose casts the filter
to match the model’s schema before the command is sent. See our query casting tutorial for more information on how Mongoose casts filter
.
Examples:
// find all documents
await MyModel.find({});
// find all documents named john and at least 18
await MyModel.find({ name: 'john', age: { $gte: 18 } }).exec();
// executes, passing results to callback
MyModel.find({ name: 'john', age: { $gte: 18 }}, function (err, docs) {});
// executes, name LIKE john and only selecting the "name" and "friends" fields
await MyModel.find({ name: /john/i }, 'name friends').exec();
// passing options
await MyModel.find({ name: /john/i }, null, { skip: 10 }).exec();
Parameters
id «Any» value of
_id
to query by[projection] «Object|String|Array<String>» optional fields to return, see
[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 , 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
[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
[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
[callback] «Function»
Returns:
- «Query»
Issue a mongodb findAndModify remove command by a document’s _id field. findByIdAndRemove(id, ...)
is equivalent to findOneAndRemove({ _id: id }, ...)
.
Finds a matching document, removes it, passing the found document (if any) to the callback.
Executes the query if callback
is passed.
This function triggers the following middleware.
findOneAndRemove()
Options:
sort
: if multiple docs are found by the conditions, sets the sort order to choose which doc to updateselect
: sets the document fields to returnrawResult
: if true, returns the raw result from the MongoDB driverstrict
: overwrites the schema’s for this update
Examples:
A.findByIdAndRemove(id, options, callback) // executes
A.findByIdAndRemove(id, options) // return Query
A.findByIdAndRemove(id, callback) // executes
A.findByIdAndRemove(id) // returns Query
A.findByIdAndRemove() // returns Query
Model.findByIdAndUpdate()
Parameters
id «Object|Number|String» value of
_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 and the Mongoose lean tutorial.
[options.session=null] «ClientSession» The session associated with this query. See .
[options.strict] «Boolean|String» overwrites the schema’s strict mode option
[options.timestamps=null] «Boolean» If set to
false
and 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 .[callback] «Function»
Returns:
- «Query»
Issues a mongodb findAndModify update command by a document’s _id field. findByIdAndUpdate(id, ...)
is equivalent to findOneAndUpdate({ _id: id }, ...)
.
Finds a matching document, updates it according to the update
arg, passing any options
, and returns the found document (if any) to the callback. The query executes if callback
is passed.
This function triggers the following middleware.
findOneAndUpdate()
Options:
new
: bool - true to return the modified document rather than the original. defaults to falseupsert
: bool - creates the object if it doesn’t exist. defaults to false.runValidators
: if true, runs update validators on this command. Update validators validate the update operation against the model’s schema.setDefaultsOnInsert
:true
by default. IfsetDefaultsOnInsert
andupsert
are true, mongoose will apply the specified in the model’s schema if a new document is created.sort
: if multiple docs are found by the conditions, sets the sort order to choose which doc to updateselect
: sets the document fields to returnrawResult
: if true, returns the raw result from the MongoDB driverstrict
: overwrites the schema’s for this update
Examples:
A.findByIdAndUpdate(id, update, options, callback) // executes
A.findByIdAndUpdate(id, update, options) // returns Query
A.findByIdAndUpdate(id, update, callback) // executes
A.findByIdAndUpdate(id, update) // returns Query
A.findByIdAndUpdate() // returns Query
Note:
All top level update keys which are not atomic
operation names are treated as set operations:
Example:
Model.findByIdAndUpdate(id, { name: 'jason bourne' }, options, callback)
// is sent as
Model.findByIdAndUpdate(id, { $set: { name: 'jason bourne' }}, options, callback)
This helps prevent accidentally overwriting your document with { name: 'jason bourne' }
.
Note:
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.
Model.findById(id, function (err, doc) {
if (err) ..
doc.name = 'jason bourne';
doc.save(callback);
});
Parameters
- [conditions] «Object»
[projection] «Object|String|Array<String>» optional fields to return, see
[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
[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 .
[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 , as opposed to a findOneAndDelete()
command. For most mongoose use cases, this distinction is purely pedantic. You should use findOneAndDelete()
unless you have a good reason not to.
Options:
sort
: if multiple docs are found by the conditions, sets the sort order to choose which doc to updatemaxTimeMS
: puts a time limit on the query - requires mongodb >= 2.6.0select
: sets the document fields to return, ex.{ projection: { _id: 0 } }
projection
: equivalent toselect
rawResult
: if true, returns thestrict
: overwrites the schema’s strict mode option for this update
Examples:
A.findOneAndDelete(conditions, options, callback) // executes
A.findOneAndDelete(conditions, options) // return Query
A.findOneAndDelete(conditions, callback) // executes
A.findOneAndDelete(conditions) // returns Query
A.findOneAndDelete() // returns Query
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.
Model.findById(id, function (err, doc) {
if (err) ..
doc.name = 'jason bourne';
doc.save(callback);
});
Parameters
- conditions «Object»
[options] «Object» optional see
[options.session=null] «ClientSession» The session associated with this query. See transactions docs.
[options.strict] «Boolean|String» overwrites the schema’s
[options.projection=null] «Object|String|Array<String>» optional fields to return, see
Query.prototype.select()
[callback] «Function»
Returns:
- «Query»
Issue a mongodb findAndModify remove command.
Finds a matching document, removes it, passing the found document (if any) to the callback.
Executes the query if callback
is passed.
This function triggers the following middleware.
findOneAndRemove()
Options:
sort
: if multiple docs are found by the conditions, sets the sort order to choose which doc to updatemaxTimeMS
: puts a time limit on the query - requires mongodb >= 2.6.0select
: sets the document fields to returnprojection
: like select, it determines which fields to return, ex.{ projection: { _id: 0 } }
rawResult
: if true, returns thestrict
: overwrites the schema’s strict mode option for this update
Examples:
A.findOneAndRemove(conditions, options, callback) // executes
A.findOneAndRemove(conditions, options) // return Query
A.findOneAndRemove(conditions, callback) // executes
A.findOneAndRemove(conditions) // returns Query
A.findOneAndRemove() // returns Query
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.
Model.findById(id, function (err, doc) {
if (err) ..
doc.name = 'jason bourne';
doc.save(callback);
});
Parameters
filter «Object» Replace the first document that matches this filter
[replacement] «Object» Replace with this document
[options] «Object» optional see
[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 .[options.session=null] «ClientSession» The session associated with this query. See transactions docs.
[options.strict] «Boolean|String» overwrites the schema’s
[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
[callback] «Function»
Returns:
- «Query»
Issue a MongoDB findOneAndReplace()
command.
Finds a matching document, replaces it with the provided doc, and passes the returned doc to the callback.
Executes the query if callback
is passed.
This function triggers the following query middleware.
findOneAndReplace()
Options:
sort
: if multiple docs are found by the conditions, sets the sort order to choose which doc to updatemaxTimeMS
: puts a time limit on the query - requires mongodb >= 2.6.0select
: sets the document fields to returnprojection
: like select, it determines which fields to return, ex.{ projection: { _id: 0 } }
rawResult
: if true, returns the raw result from the MongoDB driverstrict
: overwrites the schema’s for this update
Examples:
A.findOneAndReplace(conditions, options, callback) // executes
A.findOneAndReplace(conditions, options) // return Query
A.findOneAndReplace(conditions, callback) // executes
A.findOneAndReplace(conditions) // returns Query
A.findOneAndReplace() // returns Query
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 and the Mongoose lean tutorial.
[options.session=null] «ClientSession» The session associated with this query. See .
[options.strict] «Boolean|String» overwrites the schema’s strict mode option
[options.timestamps=null] «Boolean» If set to
false
and 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 .[options.upsert=false] «Boolean» if true, and no documents found, insert a new document
[options.projection=null] «Object|String|Array<String>» optional fields to return, see
Query.prototype.select()
[callback] «Function»
Returns:
- «Query»
Issues a mongodb findAndModify update command.
Finds a matching document, updates it according to the update
arg, passing any options
, and returns the found document (if any) to the callback. The query executes if callback
is passed else a Query object is returned.
Options:
new
: bool - if true, return the modified document rather than the original. defaults to false (changed in 4.0)upsert
: bool - creates the object if it doesn’t exist. defaults to false.overwrite
: bool - if true, replace the entire document.fields
: {Object|String} - Field selection. Equivalent to.select(fields).findOneAndUpdate()
maxTimeMS
: puts a time limit on the query - requires mongodb >= 2.6.0sort
: if multiple docs are found by the conditions, sets the sort order to choose which doc to updaterunValidators
: if true, runs 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 thestrict
: overwrites the schema’s strict mode option for this update
Examples:
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' }
.
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
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' });
Parameters
- [callback] «Function»
This function is responsible for building , unless autoIndex
is turned off.
Mongoose calls this function automatically when a model is created using or connection.model()
, so you don’t need to call it. This function is also idempotent, so you may call it to get back a promise that will resolve when your indexes are finished building as an alternative to
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);
Event.init().then(function(Event) {
// You can also use `Event.on('index')` if you prefer event emitters
// over promises.
console.log('Indexes are done building!');
});
Model.insertMany()
Parameters
- doc(s) «Array|Object|*»
[options] «Object» see the mongodb driver options
[options.ordered «Boolean» = true] if true, will fail fast on the first error encountered. If false, will insert all the documents it can and report errors later. An
insertMany()
withordered = false
is called an “unordered”insertMany()
.[options.rawResult «Boolean» = false] if false, the returned promise resolves to the documents that passed mongoose document validation. If
true
, will return the with amongoose
property that containsvalidationErrors
if this is an unorderedinsertMany
.[options.lean «Boolean» = false] if
true
, skips hydrating and validating the documents. This option is useful if you need the extra performance, but Mongoose won’t validate the documents before inserting.[options.limit «Number» = null] this limits the number of documents being processed (validation/casting) by mongoose in parallel, this does NOT send the documents in batches to MongoDB. Use this option if you’re processing a large number of documents and your app is running out of memory.
[options.populate «String|Object|Array» = null] populates the result documents. This option is a no-op if
rawResult
is set.[callback] «Function» callback
Returns:
- «Promise» resolving to the raw result from the MongoDB driver if
options.rawResult
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 .
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 }'
Parameters
- [cb] «Function» optional callback
Returns:
- «Promise,undefined» Returns
undefined
if callback is specified, returns a promise if no callback.
Lists the indexes currently defined in MongoDB. This may or may not be the same as the indexes defined in your schema depending on whether you use the autoIndex
option and if you build indexes manually.
Model.mapReduce()
Parameters
o «Object» an object specifying map-reduce options
[callback] «Function» optional callback
Returns:
- «Promise»
Executes a mapReduce command.
o
is an object specifying all mapReduce options as well as the map and reduce functions. All options are delegated to the driver implementation. See for more detail about options.
This function does not trigger any middleware.
Example:
const o = {};
// `map()` and `reduce()` are run on the MongoDB server, not Node.js,
// these functions are converted to strings
o.map = function () { emit(this.name, 1) };
o.reduce = function (k, vals) { return vals.length };
User.mapReduce(o, function (err, results) {
console.log(results)
})
Other options:
query
{Object} query filter object.sort
{Object} sort input objects using this keylimit
{Number} max number of documentskeeptemp
{Boolean, default:false} keep temporary datafinalize
{Function} finalize functionscope
{Object} scope variables exposed to map/reduce/finalize during executionjsMode
{Boolean, default:false} it is possible to make the execution stay in JS. Provided in MongoDB > 2.0.Xverbose
{Boolean, default:false} provide statistics on job execution time.readPreference
{String}out*
{Object, default: {inline:1}} sets the output target for the map reduce job.
* out options:
{inline:1}
the results are returned in an array{replace: 'collectionName'}
add the results to collectionName: the results replace the collection{reduce: 'collectionName'}
add the results to collectionName: if dups are detected, uses the reducer / finalize functions{merge: 'collectionName'}
add the results to collectionName: if dups exist the new docs overwrite the old
If options.out
is set to replace
, merge
, or reduce
, a Model instance is returned that can be used for further querying. Queries run against this model are all executed with the ; meaning only the js object is returned and no Mongoose magic is applied (getters, setters, etc).
Example:
const o = {};
// You can also define `map()` and `reduce()` as strings if your
// linter complains about `emit()` not being defined
o.map = 'function () { emit(this.name, 1) }';
o.reduce = 'function (k, vals) { return vals.length }';
o.out = { replace: 'createdCollectionNameForResults' }
o.verbose = true;
User.mapReduce(o, 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,
o.resolveToObject = true;
const promise = User.mapReduce(o);
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.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 , 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 an array. Inferred from schema by default. - strictPopulate: optional boolean, set to
false
to allow populating paths that aren’t in the schema.
Examples:
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.$where
Type:
- «property»
Additional properties to attach to the query when calling save()
and isNew
is false.
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) {});
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.
Type:
- «property»
Collection the model uses.
This property is read-only. Modifying this property is a no-op.
Model.prototype.db
Type:
- «property»
Connection the model uses.
Parameters
- [fn] «function(err|product)» 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.
Parameters
- name «String» model name
Returns another Model instance.
Example:
const doc = new Tank;
doc.model('User').findById(id, callback);
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 .
[fn] «function(err|product)» optional callback
Returns:
- «Promise» Promise
Removes this document from the db.
Example:
product.remove(function (err, product) {
if (err) return handleError(err);
Product.findById(product._id, function (err, product) {
console.log(product) // null
})
})
As an extra measure of flow control, remove will return a Promise (bound to fn
if passed) so it could be chained, or hooked to recieve errors
Example:
product.remove().then(function (product) {
...
}).catch(function (err) {
assert.ok(err)
})
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 .
[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 . Overrides the schema-level
writeConcern
option[options.j] «Boolean» set to true for MongoDB to wait until this
save()
has been . Overrides the schema-levelwriteConcern
option[options.wtimeout] «Number» sets a . 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[options.timestamps=true] «Boolean» if
false
and timestamps are enabled, skip timestamps for thissave()
.[fn] «Function» optional callback
Returns:
- «Promise,undefined» Returns undefined if used with callback or a Promise otherwise.
Saves this document by inserting a new document into the database if document.isNew is true
, or sends an 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
Type:
- «property»
Schema the model uses.
Model.remove()
Parameters
- conditions «Object»
[options] «Object»
[options.session=null] «Session» the session associated with this operation.
[callback] «Function»
Returns:
- «Query»
Removes all documents that match conditions
from the collection. To remove just the first document that matches conditions
, set the single
option to true.
This method is deprecated. See Deprecation Warnings for details.
Example:
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 .
Parameters
- filter «Object»
- doc «Object»
[options] «Object» optional see
[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 for replica sets. Overrides the schema-level write concern
[options.timestamps=null] «Boolean» If set to
false
and 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()
Parameters
[options] «Object» see the
[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 for benefits like causal consistency, retryable writes, and .
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» Returns
undefined
if callback is specified, returns a promise if no callback.
Makes the indexes in MongoDB match the indexes defined in this model’s schema. This function will drop any indexes that are not defined in the model’s schema except the _id
index, and build any indexes that are in your schema but not in MongoDB.
See the 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
- raw «Object» fields/conditions that may contain aliased keys
Returns:
- «Object» the translated ‘pure’ fields/conditions
Translate any aliases fields/conditions so the final query or document object is pure
Example:
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
[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
[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 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 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)
[callback] «Function»
Returns:
- «Query»
Updates one document in the database without returning it.
This function triggers the following middleware.
update()
This method is deprecated. See Deprecation Warnings for details.
Examples:
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 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 themulti
(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 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 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
[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
[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
[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
[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»
- [context] «Object»
- [callback] «Function»
Returns:
- «Promise,undefined»
Casts and validates the given object against this model’s schema, passing the given context
to custom validators.
Example:
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']
}
Parameters
- [pipeline] «Array»
- [options] «Object» see the
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 .
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 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
increment()
Signal that we desire an increment of this documents version.
Example:
Model.findById(id, function (err, doc) {
doc.increment();
doc.save(function (err) { .. })
})
- Query()
- Query.prototype.Symbol.asyncIterator()
- Query.prototype.allowDiskUse()
- Query.prototype.batchSize()
- Query.prototype.cast()
- Query.prototype.center()
- Query.prototype.circle()
- Query.prototype.collation()
- Query.prototype.count()
- Query.prototype.cursor()
- Query.prototype.deleteOne()
- Query.prototype.elemMatch()
- Query.prototype.error()
- Query.prototype.exec()
- Query.prototype.explain()
- Query.prototype.findOne()
- Query.prototype.findOneAndRemove()
- Query.prototype.findOneAndUpdate()
- Query.prototype.get()
- Query.prototype.getOptions()
- Query.prototype.getQuery()
- Query.prototype.gt()
- Query.prototype.hint()
- Query.prototype.intersects()
- Query.prototype.lean()
- Query.prototype.lt()
- Query.prototype.map()
- Query.prototype.maxScan()
- Query.prototype.maxscan()
- Query.prototype.mod()
- Query.prototype.mongooseOptions()
- Query.prototype.near()
- Query.prototype.nin()
- Query.prototype.or()
- Query.prototype.polygon()
- Query.prototype.post()
- Query.prototype.projection()
- Query.prototype.readConcern()
- Query.prototype.remove()
- Query.prototype.select()
- Query.prototype.selectedExclusively()
- Query.prototype.session()
- Query.prototype.setOptions()
- Query.prototype.setUpdate()
- Query.prototype.skip()
- Query.prototype.slice()
- Query.prototype.sort()
- Query.prototype.then()
- Query.prototype.update()
- Query.prototype.updateOne()
- Query.prototype.w()
- Query.prototype.within()
- Query.prototype.wtimeout()
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();
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.Symbol.asyncIterator()
Returns an asyncIterator for use with 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 .
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.
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']);
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();
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»
Specifies the batchSize option.
Example
query.batchSize(100)
Note
Cannot be used with distinct()
Parameters
- val «Object»
- Upper «[Array]» Right Coords
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»
Casts this query to the schema of model
Note
If obj
is present, it is cast instead of this query.
Parameters
- [reject] «Function»
Returns:
- «Promise»
Executes the query returning a Promise
which will be resolved with either the doc(s) or rejected with the error. Like .then()
, but only takes a rejection handler.
More about Promise catch()
in JavaScript.
Query.prototype.center()
DEPRECATED Alias for
Deprecated. Use circle instead.
Query.prototype.centerSphere()
Parameters
- [path] «String»
- val «Object»
Returns:
- «Query» this
DEPRECATED Specifies a $centerSphere
condition
Deprecated. Use 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);
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
Parameters
- value «Object»
Returns:
- «Query» this
Adds a collation to this op (MongoDB 3.4 and up)
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 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);
})
Parameters
[filter] «Object» mongodb selector
[callback] «Function» optional params are (error, count)
Returns:
- «Query» this
Specifies this query as a countDocuments()
query. Behaves like count()
, except it always does a full collection scan when passed an empty filter {}
.
There are also minor differences in how countDocuments()
handles $where
and a couple geospatial operators. versus count()
.
Passing a callback
executes the query.
This function triggers the following middleware.
countDocuments()
Example:
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
:$near
:$geoWithin
with$nearSphere
:$geoWithin
with
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 . 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;
Parameters
[filter] «Object|Query» mongodb selector
[options] «Object» optional see
[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 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()
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);
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
});
Parameters
[options] «Object» passed transparently to the
[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();
Parameters
- [operation] «String|Function»
- [callback] «Function» optional params depend on the function being called
Returns:
- «Promise»
Executes the query
Examples:
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);
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);
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) {});
Parameters
[filter] «Object» mongodb selector
[projection] «Object» optional fields to return
[options] «Object» see
[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
}
});
Parameters
- [conditions] «Object»
[options] «Object»
[options.rawResult] «Boolean» if true, returns the
[options.session=null] «ClientSession» The session associated with this query. See transactions docs.
[options.strict] «Boolean|String» overwrites the schema’s
[callback] «Function» optional params are (error, document)
Returns:
- «Query» this
Issues a MongoDB 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`
}
Examples
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 .
[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`
}
Examples
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 .
[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 and the Mongoose lean tutorial.
[options.session=null] «ClientSession» The session associated with this query. See .
[options.strict] «Boolean|String» overwrites the schema’s strict mode option
[options.timestamps=null] «Boolean» If set to
false
and 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 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
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`
}
Examples
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
Parameters
- [filter] «Object|Query»
- [doc] «Object»
[options] «Object»
[options.rawResult] «Boolean» if true, returns the
[options.strict] «Boolean|String» overwrites the schema’s strict mode option
[options.session=null] «ClientSession» The session associated with this query. See .
[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 .[options.session=null] «ClientSession» The session associated with this query. See transactions docs.
[options.strict] «Boolean|String» overwrites the schema’s
[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 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`
}
Examples
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 })
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'
Returns:
- «Object» current query filter
Returns the current query filter (also known as conditions) as a .
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']
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 } }
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 } }
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)
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.
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 .
Parameters
- val «boolean»
Returns:
- «Query» this
Requests acknowledgement that this operation has been persisted to MongoDB’s on-disk journal.
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);
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 .
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()
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.
Parameters
- fn «Function» function to run to transform the query result
Returns:
- «Query» this
Runs a function fn
and treats the return value of fn
as the new value for the query to resolve to.
Any functions you pass to map()
will run after any post hooks.
Example:
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.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.
Parameters
- val «Number»
Specifies the maxScan option.
Example
query.maxScan(100)
Note
Cannot be used with distinct()
Query.prototype.maxTimeMS()
Parameters
- [ms] «Number» The number of milliseconds
Returns:
- «Query» this
Sets the 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);
Type:
- «property»
The model this query is associated with.
Example:
const q = MyModel.find();
q.model === MyModel; // true
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 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 the 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 the
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.
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 });
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 });
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' }])
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
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'));
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» either the path to populate or an object specifying all parameters
[select] «Object|String» Field selection for the population query
[model] «Model» The model you wish to use for population. If not specified, populate will look up the model by the name in the Schema’s
ref
field.[match] «Object» Conditions for the population query
[options] «Object» Options for the population query (sort, etc)
[options.path=null] «String» The path to populate.
[options.retainNullValues=false] «boolean» by default, Mongoose removes null and undefined values from populated arrays. Use this option to make
populate()
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 , 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.
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 });
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 });
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 and here.
Query.prototype.readConcern()
Parameters
- level «String» one of the listed read concern level or their aliases
Returns:
- «Query» this
Sets the readConcern option for the query.
Example:
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.
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 .
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 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 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
Note
Calling remove()
creates a Mongoose query, and a query does not execute until you either pass a callback, call , 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 for replica sets. Overrides the schema-level write concern
[options.timestamps=null] «Boolean» If set to
false
and 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 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.n; // Number of documents matched
res.nModified; // Number of documents modified
This function triggers the following middleware.
replaceOne()
Query.prototype.select()
Parameters
- arg «Object|String|Array<String>»
Returns:
- «Query» this
Specifies which document fields to include or exclude (also known as the query “projection”)
When using string syntax, prefixing a path with -
will flag that path as excluded. When a path does not have the -
prefix, it is included. Lastly, if a path is prefixed with +
, it forces inclusion of the path, which is useful for paths excluded at the .
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 });
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
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 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);
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()
:
- writeConcern
- : 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. - omitUndefined: delete any properties whose value is
undefined
when casting an update. In other words, if this is set, Mongoose will deletebaz
from the update inModel.updateOne({}, { foo: 'bar', baz: undefined })
before sending the update to the server. - overwriteDiscriminatorKey: allow setting the discriminator key in the update. Will use the correct discriminator schema if the update changes the discriminator key.
The following options are only for find()
, findOne()
, findById()
, findOneAndUpdate()
, and findByIdAndUpdate()
:
- lean
- 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»
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 }
Parameters
- new «Object» update operation
Returns:
- «undefined»
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()
Parameters
- v «Boolean» defaults to true
Returns:
- «Query» this
DEPRECATED Sets the slaveOk option.
Deprecated in MongoDB 2.2 in favor of read preferences.
Example:
query.slaveOk() // true
query.slaveOk(true)
query.slaveOk(false)
Parameters
- [path] «String»
- val «Number» number/range of elements to slice
Returns:
- «Query» this
Specifies a $slice
projection for an array.
Example
query.slice('comments', 5)
query.slice('comments', -5)
query.slice('comments', [10, 5])
query.where('comments').slice(5)
query.where('comments').slice([-10, 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()
Parameters
- arg «Object|String»
Returns:
- «Query» this
Sets the sort order
If an object is passed, values allowed are asc
, desc
, ascending
, descending
, 1
, and -1
.
If a string is passed, it must be a space delimited list of path names. The sort order of each path is ascending unless the path name is prefixed with -
which will be treated as descending.
Example
// sort by "field" ascending and "test" descending
query.sort({ field: 'asc', test: -1 });
// equivalent
query.sort('field -test');
Note
Cannot be used with distinct()
Parameters
bool «Boolean» defaults to true
[opts] «Object» options to set
[opts.numberOfRetries] «Number» if cursor is exhausted, retry this many times before giving up
[opts.tailableRetryInterval] «Number» if cursor is exhausted, wait this many milliseconds before retrying
Sets the tailable option (for use with capped collections).
Example
query.tailable() // true
query.tailable(true)
query.tailable(false)
Note
Cannot be used with distinct()
Query.prototype.then()
Parameters
- [resolve] «Function»
- [reject] «Function»
Returns:
- «Promise»
Executes the query returning a Promise
which will be resolved with either the doc(s) or rejected with the error.
More about .
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)
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
[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
[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 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://docs.mongodb.com/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 for replica sets. Overrides the schema-level write concern
[options.timestamps=null] «Boolean» If set to
false
and 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()
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
[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
[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.n; // Number of documents matched
res.nModified; // Number of documents modified
This function triggers the following middleware.
updateOne()
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.
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
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)
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 .
NOTE:
In Mongoose 3.7, within
changed from a getter to a function. If you need the old syntax, use .
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
: If , 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
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 , 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
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);
QueryCursor
- QueryCursor()
- QueryCursor.prototype.close()
- QueryCursor.prototype.map()
- function Object() { [native code] }.prototype.options
Query.prototype.Symbol.asyncIterator()
Returns an asyncIterator for use with . 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 .
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.
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 instead.
Parameters
- flag «String»
- value «Boolean»
Returns:
- «AggregationCursor» this
Adds a cursor flag. Useful for setting the noCursorTimeout
and tailable
flags.
QueryCursor.prototype.close()
Parameters
- callback «Function»
Returns:
- «Promise»
Marks this cursor as closed. Will stop streaming and subsequent calls to next()
will error.
QueryCursor.prototype.eachAsync()
Parameters
- fn «Function»
[options] «Object»
[options.parallel] «Number» the number of promises to execute in parallel. Defaults to 1.
[callback] «Function» executed when all docs have been processed
Returns:
- «Promise»
Execute fn
for every document in the cursor. If fn
returns a promise, will wait for the promise to resolve before iterating on to the next one. Returns a promise that resolves when done.
Example
// Iterate over documents asynchronously
Thing.
find({ name: /^hello/ }).
cursor().
eachAsync(async function (doc, i) {
doc.foo = doc.bar + i;
await doc.save();
})
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.
function Object() { [native code] }.prototype.options
Type:
- «property»
The options
passed in to the QueryCursor
constructor.
- Aggregate()
- Aggregate.prototype.addFields()
- Aggregate.prototype.append()
- Aggregate.prototype.collation()
- Aggregate.prototype.cursor()
- Aggregate.prototype.explain()
- Aggregate.prototype.graphLookup()
- Aggregate.prototype.hint()
- Aggregate.prototype.lookup()
- Aggregate.prototype.model()
- Aggregate.prototype.option()
- Aggregate.prototype.pipeline()
- Aggregate.prototype.read()
- Aggregate.prototype.redact()
- Aggregate.prototype.sample()
- Aggregate.prototype.session()
- Aggregate.prototype.sort()
- Aggregate.prototype.then()
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 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 database
new Aggregate([{ $match: { _id: '00000000000000000000000a' } }]);
// Do this instead to cast to an ObjectId
new Aggregate([{ $match: { _id: mongoose.Types.ObjectId('00000000000000000000000a') } }]);
Returns an asyncIterator for use with [for/await/of
loops](https://thecodebarbarian.com/getting-started-with-async-iterators-in-node-js You do not need to call this function explicitly, the JavaScript runtime will call it for you.
Example
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.
Aggregate.prototype.addFields()
Parameters
- arg «Object» field specification
Returns:
- «Aggregate»
Appends a new $addFields operator to this aggregate pipeline. Requires MongoDB v3.4+ to work
Examples:
// 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 ] } });
Parameters
value «Boolean» Should tell server it can use hard drive to store data during aggregation.
[tags] «Array» optional tags for this query
Sets the allowDiskUse option for the aggregation query (ignored for < 2.6.0)
Example:
await Model.aggregate([{ $match: { foo: 'bar' } }]).allowDiskUse(true);
Parameters
- ops «Object» operator(s) to append
Returns:
- «Aggregate»
Appends new operators to this aggregate pipeline
Examples:
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 , but only takes a rejection handler.
Parameters
- collation «Object» options
Returns:
- «Aggregate» this
Adds a collation
Example:
Model.aggregate(..).collation({ locale: 'en_US', strength: 1 }).exec();
Aggregate.prototype.count()
Parameters
- the «String» name of the count field
Returns:
- «Aggregate»
Appends a new $count operator to this aggregate pipeline.
Examples:
aggregate.count("userCount");
Parameters
- options «Object»
options.batchSize «Number» set the cursor batch size
[options.useMongooseAggCursor] «Boolean» use experimental mongoose-specific aggregation cursor (for
eachAsync()
and other query cursor semantics)
Returns:
- «Aggregate» this
Sets the cursor option option for the aggregation query (ignored for < 2.6.0). Note the different syntax below: .exec() returns a cursor object, and no callback is necessary.
Example:
const cursor = Model.aggregate(..).cursor({ batchSize: 1000 }).exec();
cursor.eachAsync(function(doc, i) {
// use doc
});
Aggregate.prototype.exec()
Parameters
- [callback] «Function»
Returns:
- «Promise»
Executes the aggregate pipeline on the currently bound Model.
Example:
aggregate.exec(callback);
// Because a promise is returned, the `callback` is optional.
const promise = aggregate.exec();
promise.then(..);
Parameters
- callback «Function»
Returns:
- «Promise»
Execute the aggregation with explain
Example:
Model.aggregate(..).explain(callback)
Aggregate.prototype.facet()
Parameters
- facet «Object» options
Returns:
- «Aggregate» this
Combines multiple aggregation pipelines.
Example:
Model.aggregate(...)
.facet({
books: [{ groupBy: '$author' }],
price: [{ $bucketAuto: { groupBy: '$price', buckets: 2 } }]
})
.exec();
// Output: { books: [...], price: [{...}, {...}] }
Parameters
- options «Object» to $graphLookup as described in the above link
Returns:
- «Aggregate»
Appends new custom $graphLookup operator(s) to this aggregate pipeline, performing a recursive search on a collection.
Note that graphLookup can only consume at most 100MB of memory, and does not allow disk use even if { allowDiskUse: true }
is specified.
Examples:
// 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.
Examples:
aggregate.group({ _id: "$department" });
Parameters
- value «Object|String» a hint object or the index name
Sets the hint option for the aggregation query (ignored for < 3.6.0)
Example:
Model.aggregate(..).hint({ qty: 1, category: 1 }).exec(callback)
Parameters
- num «Number» maximum number of records to pass to the next stage
Returns:
- «Aggregate»
Appends a new $limit operator to this aggregate pipeline.
Examples:
aggregate.limit(10);
Aggregate.prototype.lookup()
Parameters
- options «Object» to $lookup as described in the above link
Returns:
- «Aggregate*» @api public
Appends new custom $lookup operator to this aggregate pipeline.
Examples:
aggregate.lookup({ from: 'users', localField: 'userId', foreignField: '_id', as: 'users' });
Parameters
- arg «Object» $match operator contents
Returns:
- «Aggregate»
Appends a new custom $match operator to this aggregate pipeline.
Examples:
aggregate.match({ department: { $in: [ "sales", "engineering" ] } });
Aggregate.prototype.model()
Parameters
- [model] «Model» set the model associated with this aggregate.
Returns:
- «Model»
Get/set the model that this aggregation will execute on.
Example:
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
Parameters
- arg «Object»
Returns:
- «Aggregate»
Appends a new $geoNear operator to this aggregate pipeline.
NOTE:
MUST be used as the first operator in the pipeline.
Examples:
aggregate.near({
near: [40.724, -73.997],
distanceField: "dist.calculated", // required
maxDistance: 0.008,
query: { type: "public" },
includeLocs: "dist.location",
uniqueDocs: true,
num: 5
});
Parameters
options «Object» keys to merge into current options
number «[options.maxTimeMS]» limits the time this aggregation will run, see
boolean «[options.allowDiskUse]» if true, the MongoDB server will use the hard drive to store data during this aggregation
object «[options.collation]» see
Aggregate.prototype.collation()
ClientSession «[options.session]» see
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 }`
Type:
- «property»
Contains options passed down to the .
Supported options are
readPreference
explain
maxTimeMS
bypassDocumentValidation
raw
promoteLongs
promoteValues
promoteBuffers
collation
comment
Returns:
- «Array»
Returns the current pipeline
Example:
MyModel.aggregate().match({ test: 1 }).pipeline(); // [{ $match: { test: 1 } }]
Parameters
- arg «Object|String» field specification
Returns:
- «Aggregate»
Appends a new $project operator to this aggregate pipeline.
Mongoose query selection syntax is also supported.
Examples:
// 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 ] } });
Parameters
pref «String» one of the listed preference options or their aliases
[tags] «Array» optional tags for this query
Returns:
- «Aggregate» this
Sets the readPreference option for the aggregation query.
Example:
Model.aggregate(..).read('primaryPreferred').exec(callback)
Aggregate.prototype.readConcern()
Parameters
- level «String» one of the listed read concern level or their aliases
Returns:
- «Aggregate» this
Sets the readConcern level for the aggregation query.
Example:
Model.aggregate(..).readConcern('majority').exec(callback)
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:
Model.aggregate(...)
.redact({
$cond: {
if: { $eq: [ '$level', 5 ] },
then: '$$PRUNE',
else: '$$DESCEND'
}
})
.exec();
// $redact often comes with $cond operator, you can also use the following syntax provided by mongoose
Model.aggregate(...)
.redact({ $eq: [ '$level', 5 ] }, '$$PRUNE', '$$DESCEND')
.exec();
Aggregate.prototype.replaceRoot()
Parameters
- the «String|Object» field or document which will become the new root document
Returns:
- «Aggregate»
Appends a new $replaceRoot operator to this aggregate pipeline.
Note that the $replaceRoot
operator requires field strings to start with ‘$’. If you are passing in a string Mongoose will prepend ‘$’ if the specified field doesn’t start ‘$’. If you are passing in an object the strings in your expression will not be altered.
Examples:
aggregate.replaceRoot("user");
aggregate.replaceRoot({ x: { $concat: ['$this', '$that'] } });
Parameters
- size «Number» number of random documents to pick
Returns:
- «Aggregate»
Appends new custom $sample operator to this aggregate pipeline.
Examples:
aggregate.sample(3); // Add a pipeline that picks 3 random documents
Aggregate.prototype.search()
Parameters
- $search «Object» options
Returns:
- «Aggregate» this
Helper for ‘s $search
stage.
Example:
Model.aggregate().
search({
text: {
query: 'baseball',
path: 'plot'
}
});
// Output: [{ plot: '...', title: '...' }]
Aggregate.prototype.session()
Parameters
- session «ClientSession»
Sets the session for this aggregation. Useful for transactions.
Example:
const session = await Model.startSession();
await Model.aggregate(..).session(session);
Parameters
- num «Number» number of records to skip before next stage
Returns:
- «Aggregate»
Appends a new $skip operator to this aggregate pipeline.
Examples:
aggregate.skip(10);
Aggregate.prototype.sort()
Parameters
- arg «Object|String»
Returns:
- «Aggregate» this
Appends a new $sort operator to this aggregate pipeline.
If an object is passed, values allowed are asc
, desc
, ascending
, descending
, 1
, and -1
.
If a string is passed, it must be a space delimited list of path names. The sort order of each path is ascending unless the path name is prefixed with -
which will be treated as descending.
Examples:
// these are equivalent
aggregate.sort({ field: 'asc', test: -1 });
aggregate.sort('field -test');
Parameters
- arg «Object|String»
Returns:
- «Aggregate» this
Appends a new $sortByCount operator to this aggregate pipeline. Accepts either a string field name or a pipeline object.
Note that the $sortByCount
operator requires the new root to start with ‘$’. Mongoose will prepend ‘$’ if the specified field name doesn’t start with ‘$’.
Examples:
aggregate.sortByCount('users');
aggregate.sortByCount({ $mergeObjects: [ "$employee", "$business" ] })
Aggregate.prototype.then()
Parameters
[resolve] «Function» successCallback
[reject] «Function» errorCallback
Returns:
- «Promise»
Provides promise for aggregate.
Example:
Model.aggregate(..).then(successCallback, errorCallback);
Parameters
- fields «String|Object» the field(s) to unwind, either as field names or as . If passing a string, prefixing the field name with ‘$’ is optional. If passing an object,
path
must start with ‘$’.
Returns:
- «Aggregate»
Appends new custom $unwind operator(s) to this aggregate pipeline.
Note that the $unwind
operator requires the path name to start with ‘$’. Mongoose will prepend ‘$’ if the specified field doesn’t start ‘$’.
Examples:
aggregate.unwind("tags");
aggregate.unwind("a", "b", "c");
aggregate.unwind({ path: '$tags', preserveNullAndEmptyArrays: true });
- AggregationCursor()
- AggregationCursor.prototype.addCursorFlag()
- AggregationCursor.prototype.eachAsync()
- AggregationCursor.prototype.next()
AggregationCursor()
Parameters
- agg «Aggregate»
- options «Object»
An AggregationCursor is a concurrency primitive for processing aggregation results one document at a time. It is analogous to QueryCursor.
An AggregationCursor fulfills the Node.js streams3 API, in addition to several other mechanisms for loading documents from MongoDB one at a time.
Creating an AggregationCursor executes the model’s pre aggregate hooks, but not the model’s post aggregate hooks.
Unless you’re an advanced user, do not instantiate this class directly. Use Aggregate#cursor()
instead.
AggregationCursor.prototype.Symbol.asyncIterator()
Returns an asyncIterator for use with [for/await/of
loops]( 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 .
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.
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);
});
Parameters
- callback «Function»
Returns:
- «Promise»
Get the next document from this cursor. Will return null
when there are no documents left.
- SchemaType()
- SchemaType.prototype.default()
- SchemaType.prototype.immutable()
- SchemaType.prototype.ref()
- SchemaType.prototype.select()
- SchemaType.prototype.sparse()
- SchemaType.prototype.transform()
- SchemaType.prototype.validate()
- Schematype.cast()
- Schematype.get()
Parameters
- path «String»
[options] «SchemaTypeOptions» See
[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.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.
Parameters
- val «Function|any» the default value
Returns:
- «defaultValue»
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 }
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, 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 .
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 .
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»
Returns:
- «SchemaType» this
Declares the index options for this schematype.
Example:
const s = new Schema({ name: { type: String, index: true })
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 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.
Parameters
- ref «String|Model|Function» either a model name, a , 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 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:
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 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, 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 });
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}'
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 , 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 will be used.
Examples:
// 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() { 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 , 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);
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.cast()
Parameters
- caster «Function|false» Function that casts arbitrary values to this type, or throws an error if casting failed
Returns:
- «Function»
Get/set the function used to cast arbitrary values to this particular schematype instance. Overrides SchemaType.cast()
.
Example:
// 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;
});
Parameters
- fn «Function»
Returns:
- «Function»
Override the function the required validator uses to check whether a value passes the required
check. Override this on the individual SchemaType.
Example:
// 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); });
Parameters
option «String» The name of the option you’d like to set (e.g. trim, lowercase, etc…)
value «*» The value of the option you’d like to set.
Returns:
- «void»
Sets a default option for this schema type.
Example:
// Make all strings be trimmed by default
mongoose.SchemaTypes.String.set('trim', true);
Parameters
options «Object»
[options.ref] «string|function» if
ref
is not nullish, this becomes a[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
.
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
Parameters
- value «Object»
- doc «Document» The document this virtual is attached to
Returns:
- «any» the value after applying all getters
Applies getters to value
.
Parameters
- value «Object»
- doc «Document»
Returns:
- «any» the value after applying all setters
Applies setters to value
.
Parameters
- VirtualType, «Function(Any|» Document)} fn
Returns:
- «VirtualType» this
Adds a custom getter to this virtual.
Mongoose calls the getter function with the below 3 parameters.
value
: the value returned by the previous getter. If there is only one getter,value
will beundefined
.virtual
: the virtual object you called.get()
ondoc
: 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
- VirtualType, «Function(Any|» Document)} fn
Returns:
- «VirtualType» this
Adds a custom setter to this virtual.
Mongoose calls the setter function with the below 3 parameters.
value
: the value being setvirtual
: the virtual object you’re calling.set()
ondoc
: 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.DivergentArrayError
- Error.MissingSchemaError
- Error.ParallelSaveError
- Error.ValidationError
- Error.VersionError
- Error.prototype.name
Error()
Parameters
- msg «String» Error message
MongooseError constructor. MongooseError is the base class for all Mongoose-specific errors.
Example:
const Model = mongoose.model('Test', new Schema({ answer: Number }));
const doc = new Model({ answer: 'not a number' });
const err = doc.validateSync();
err instanceof mongoose.Error; // true
Error.CastError
Type:
- «property»
An instance of this error class will be returned when mongoose failed to cast a value.
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.
Type:
- «property»
Thrown when you try to access a model that has not been registered yet
Error.OverwriteModelError
Type:
- «property»
Thrown when a model with the given name was already registered on the connection. See the FAQ about OverwriteModelError
.
Error.ParallelSaveError
Type:
- «property»
An instance of this error class will be returned when you call save()
multiple times on the same document in parallel. See the FAQ for more information.
Error.StrictModeError
Type:
- «property»
Thrown when your try to pass values to model contrtuctor that were not specified in schema or change immutable properties when strict
mode is "throw"
Type:
- «property»
An instance of this error class will be returned when failed. The errors
property contains an object whose keys are the paths that failed and whose values are instances of CastError or ValidationError.
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
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 for more information.
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 with that was not definedDocumentNotFoundError
: The document you tried tosave()
was not foundValidatorError
: error from an individual schema path’s validatorValidationError
: error returned from 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 .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 call 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
SchemaArray()
Parameters
- key «String»
- cast «SchemaType»
- options «Object»
Array SchemaType constructor
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.
Parameters
- value «Any»
- doc «Document»
Returns:
- «Boolean»
Check if the given value satisfies the required
validator.
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()
Type:
- «property»
This schema type’s name, to defend against minifiers that mangle function names.
SchemaArray.set()
Parameters
- option «String»
- The option you’d like to set the value for
- value «*»
- value for option
Returns:
- «undefined»
Sets a default option for all Array instances.
Example:
// 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()
Parameters
- key «String»
- schema «Schema»
- options «Object»
SubdocsArray SchemaType constructor
Parameters
- option «String»
- The option you’d like to set the value for
- value «*»
- value for option
Returns:
- «undefined»
Type:
- «property»
Sets a default option for all DocumentArray instances.
Example:
// Make all numbers have option `min` equal to 0.
mongoose.Schema.DocumentArray.set('_id', false);
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 }));
Type:
- «property»
This schema type’s name, to defend against minifiers that mangle function names.
SubdocumentPath
Parameters
- schema «Schema»
- key «String»
- options «Object»
Single nested subdocument SchemaType constructor.
SubdocumentPath.
Parameters
- option «String»
- The option you’d like to set the value for
- value «*»
- value for option
Returns:
- «undefined»
Type:
- «property»
Sets a default option for all SubdocumentPath instances.
Example:
// Make all numbers have option `min` equal to 0.
mongoose.Schema.Embedded.set('required', true);
SubdocumentPath.prototype.discriminator()
Parameters
- name «String»
schema «Schema» fields to add to the schema for instances of this sub-class
[options] «Object|string» If string, same as
options.value
.[options.value] «String» the string stored in the
discriminatorKey
property. If not specified, Mongoose uses 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 }));
- SchemaTypeOptions()
- SchemaTypeOptions.prototype.default
- SchemaTypeOptions.prototype.index
- SchemaTypeOptions.prototype.required
- SchemaTypeOptions.prototype.sparse
- SchemaTypeOptions.prototype.transform
- SchemaTypeOptions.prototype.unique
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.
Type:
- «Function|Boolean»
If , 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.
Type:
- «Function|Boolean»
If true, attach a required validator to this path, which ensures this path path cannot be set to a nullish value. If a function, Mongoose calls the function and only checks for nullish values if the function returns a truthy value.
SchemaTypeOptions.prototype.select
Type:
- «Boolean|Number»
Whether to include or exclude this path by default when loading documents using find()
, findOne()
, etc.
Type:
- «Boolean|Number»
If , Mongoose will build a sparse index on this path.
Type:
- «Boolean|Number|Object»
If , Mongoose will build a text index on this path.
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
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. .
Type:
- «Function|Object»
Function or object describing how to validate this schematype.
SchemaArrayOptions
The options defined on an Array schematype.
Example:
const schema = new Schema({ tags: [String] });
schema.path('tags').options; // SchemaArrayOptions instance
SchemaArrayOptions.prototype.enum
Type:
- «Array»
If this is an array of strings, an array of allowed values for this path. Throws an error if this array isn’t an array of strings.
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 } });
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.
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.
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()
The options defined on a Number schematype.
Example:
const schema = new Schema({ count: Number });
schema.path('count').options; // SchemaNumberOptions instance
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]
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
.
Type:
- «Object»
Sets default .
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
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.
Type:
- «Object»
Sets default .
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.prototype.enum
- SchemaStringOptions.prototype.match
- SchemaStringOptions.prototype.minLength
- SchemaStringOptions.prototype.trim
The options defined on a string schematype.
Example:
SchemaStringOptions.prototype.enum
Type:
- «Array»
Array of allowed values for this path
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.
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”).
Type:
- «Object»
Sets default .
Type:
- «Boolean»
If truthy, Mongoose will add a custom setter that removes leading and trailing whitespace using .
Type:
- «Boolean»
If truthy, Mongoose will add a custom setter that uppercases this string using JavaScript’s built-in .