API Docs - 图1mongoose

API Docs - 图2mongoose

API Docs


Index


Mongoose()

Mongoose constructor.

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


Mongoose.prototypeSTATES

Expose connection states for user-land


Mongoose.prototype.set()

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

Sets mongoose options

Example:

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

Currently supported options are

  • 'debug': prints the operations mongoose sends to MongoDB to the console
  • 'bufferCommands': enable/disable mongoose's buffering mechanism for all connections and models
  • 'useFindAndModify': true by default. Set to false to make findOneAndUpdate() and findOneAndRemove() use native findOneAndUpdate() rather than findAndModify().

Mongoose.prototype.get ()

Parameters
  • key «String»

Gets mongoose options

Example:

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

Mongoose.prototype.createConnection()

Parameters
  • [uri] «String» a mongodb:// URI
  • [options] «Object» passed down to the MongoDB driver's connect() function, except for 4 mongoose-specific options explained below.
  • [options.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.bufferCommands=true] «Boolean» Mongoose specific option. Set to false to disable buffering on all models associated with this connection.
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 mangaging multiple db connections.

If arguments are passed, they are proxied to either Connection#open or Connection#openSet appropriately. This means we can pass db, server, and replset options to the driver. Note that the safe option specified in your schema will overwrite the safe db option specified here unless you set your schemas safe option to undefined. See this for more information.

Options passed take precedence over options included in connection strings.

Example:

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

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.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.bufferCommands=true] «Boolean» Mongoose specific option. Set to false to disable buffering on all models associated with this connection.
  • [callback] «Function»
Returns:
  • «Promise» resolves to this if connection succeeded

Opens the default mongoose connection.

Example:

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

Mongoose.prototype.disconnect()

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

Runs .close() on all connections in parallel.


Mongoose.prototype.pluralize()

Parameters
  • [fn] «Function|null» overwrites the function used to pluralize connection names
Returns:
  • «Function,null» the current function used to pluralize connection names, undefined by default.

Getter/setter around function for pluralizing collection names.


Mongoose.prototype.model()

Parameters
  • name «String|Function» model name or class extending Model
  • [schema] «Schema»
  • [collection] «String» name (optional, inferred from model name)
  • [skipInit] «Boolean» whether to skip initialization (defaults to false)
Returns:
  • «Model »

Defines a model or retrieves it.

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

Example:

  1. var mongoose = require('mongoose');
  2. // define an Actor model with this mongoose instance
  3. mongoose.model('Actor', new Schema({ name: String }));
  4. // create a new connection
  5. var conn = mongoose.createConnection(..);
  6. // retrieve the Actor model
  7. var Actor = conn.model('Actor');

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

Example:

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

Mongoose.prototype.modelNames()

Returns:
  • «Array»

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

Note:

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


Mongoose.prototype.plugin()

Parameters
  • fn «Function» plugin callback
  • [opts] «Object» optional options
Returns:
  • «Mongoose» this

Declares a global plugin executed on all Schemas.

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


Mongoose .prototype.connection

Returns:
  • «Connection »

The default connection of the mongoose module.

Example:

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

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


Mongoose.prototype.Aggregate ()

The Mongoose Aggregate constructor


Mongoose.prototype.Collection ()

The Mongoose Collection constructor


Mongoose .prototype.Connection ()

The Mongoose Connection constructor


Mongoose.prototype.version

The Mongoose version


Mongoose.prototype.Mongoose ()

The Mongoose constructor

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

Example:

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

Mongoose.prototype.Schema ()

The Mongoose Schema constructor

Example:

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

Mongoose.prototype.SchemaType ()

The Mongoose SchemaType constructor


Mongoose.prototype.SchemaTypes

The various Mongoose SchemaTypes.

Note:

Alias of mongoose.Schema.Types for backwards compatibility.


Mongoose.prototype.VirtualType ()

The Mongoose VirtualType constructor


Mongoose.prototype.Types

The various Mongoose Types.

Example:

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

Types:

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

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

Mongoose.prototype.Query ()

The Mongoose Query constructor.


Mongoose .prototype.Promise

The Mongoose Promise constructor.


Mongoose.prototype.PromiseProvider ()

Storage layer for mongoose promises


Mongoose.prototype.Model ()

The Mongoose Model constructor.


Mongoose.prototype.Document ()

The Mongoose Document constructor.


Mongoose.prototype.DocumentProvider ()

The Mongoose DocumentProvider constructor.


Mongoose.prototype.Error ()

The MongooseError constructor.


Mongoose.prototype.CastError ()

Parameters
  • type «String» The name of the type
  • value «Any» The value that failed to cast
  • path «String» The path a.b.c in the doc where this cast error occurred
  • [reason] «Error» The original error that was thrown

The Mongoose CastError constructor


Mongoose.prototype.mongo

The node-mongodb-native driver Mongoose uses.


Mongoose.prototype.mquery

The mquery query builder Mongoose uses.


Schema


Schema()

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

Schema 构造函数。

示例:

  1. var child = new Schema({ name: String });
  2. var schema = new Schema({ name: String, age: Number, children: [child] });
  3. var Tree = mongoose.model('Tree', schema);
  4. // 设置 schema 选项参数
  5. new Schema({ name: String }, { _id: false, autoIndex: false })

Options:

注意:

对 schema 进行嵌套时, (上例中的 children), 传给父 schema 引用之前一定要先声明子 schema。


Schema.prototype.childSchemas

一个数组,包含子 schema (document 数组中的,和单个的嵌套 subdoc) 和对应已编译的 model。每个元素都是个对象,包含2个属性:schemamodel

这个属性通常只有插件开发者和高级用户会使用。 你完全没必要操作它。


Schema.prototype.obj

传给 schema 构造函数的原始对象

示例:

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

Schema.prototype.paths

Schema 字段路径的扁平结构

示例:

  1. {
  2. '_id' : SchemaType,
  3. , 'nested.key' : SchemaType,
  4. }

Schema.prototype.tree

Schema 字段路径的树形结构

示例:

  1. {
  2. '_id' : ObjectId
  3. , 'nested' : {
  4. 'key' : String
  5. }
  6. }

Schema.prototype.clone()

Returns:
  • «Schema» 克隆的 schema

返回 schema 的一个深克隆(deep copy)


Schema.prototype.add()

Parameters
  • obj «Object»
  • prefix «String»

向 schema 中添加 路径/类型(key path / schema type) 键值对

示例:

  1. var ToySchema = new Schema;
  2. ToySchema.add({ name: 'string', color: 'string', price: 'number' });

Schema.reserved

document 中被保留的字段。

在 schema 的声明中禁止使用这个属性中的键作为字段名称,因为跟 mongoose 的功能存在冲突。使用这些名字会抛出错误。

  1. on, emit, _events, db, get, set, init, isNew, errors, schema, options, modelName, collection, _pres, _posts, toObject

注意: 允许使用这些名字作为方法名,但是自负风险, 因为它们可能是 mongoose document 中已经存在的方法名。

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

Schema.prototype.path()

Parameters
  • path «String»
  • constructor «Object»

读/写 schema 路径。

Sets a path (2个参数)

Gets a path (1个参数)

示例

  1. schema.path('name') // 返回该路径的数据类型
  2. schema.path('name', Number) // 把路径 `name` 的数据类型设置为 Number

Schema.prototype.eachPath()

Parameters
  • fn «Function» 回调函数
Returns:
  • «Schema» this

像 Array#forEach 一样遍历 schema 的所有路径。

每次遍历向回调函数传入路径和数据类型(schemaType)两个参数。


Schema.prototype.requiredPaths()

Parameters
  • invalidate «Boolean» 刷新缓存
Returns:
  • «Array»

返回一个数组,包含 schema 中必需的 (required) 路径字符串


Schema.prototype.indexedPaths()

Returns:
  • «Array»

返回字段上的索引和 schema-level 的索引(已被缓存的)


Schema.prototype.pathType()

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

返回 schema 中路径(path)的类型

给定一个路径,返回它是 real, virtual, nested 还是 ad-hoc/undefined


Schema.prototype.queue()

Parameters
  • name «String» 待调用方法的名称
  • args «Array» 传给方法的参数 (arguments)

向方法调用的队列中增加一条


Schema.prototype.pre()

Parameters
  • method «String»
  • callback «Function»

给 document 定义一个前置钩子 (pre hook)

示例

  1. var toySchema = new Schema(..);
  2. toySchema.pre('save', function (next) {
  3. if (!this.created) this.created = new Date;
  4. next();
  5. })
  6. toySchema.pre('validate', function (next) {
  7. if (this.name !== 'Woody') this.name = 'Woody';
  8. next();
  9. })

Schema.prototype.post()

Parameters
  • method «String» name of the method to hook
  • fn «Function» callback

给 document 定义一个后置钩子 (post hook)

示例

  1. var schema = new Schema(..);
  2. schema.post('save', function (doc) {
  3. console.log('this fired after a document was saved');
  4. });
  5. schema.post('find', function(docs) {
  6. console.log('this fired after you run a find query');
  7. });
  8. var Model = mongoose.model('Model', schema);
  9. var m = new Model(..);
  10. m.save(function(err) {
  11. console.log('this fires after the `post` hook');
  12. });
  13. m.find(function(err, docs) {
  14. console.log('this fires after the post find hook');
  15. });

Schema.prototype.plugin()

Parameters
  • plugin «Function» callback
  • [opts] «Object»

给 schema 注册一个插件


Schema.prototype.method()

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

向由该 schema 编译的 model 构造的 document 添加一个实例方法

示例

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

如果参数只有一个,是 名称/函数 哈希键值对,那么每一对 名称/函数 都被加为实例方法。

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

Schema.prototype.static()

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

向由该 schema 编译生成的 Model 添加静态类方法

示例

  1. var schema = new Schema(..);
  2. schema.static('findByName', function (name, callback) {
  3. return this.find({ name: name }, callback);
  4. });
  5. var Drink = mongoose.model('Drink', schema);
  6. Drink.findByName('sanpellegrino', function (err, drinks) {
  7. //
  8. });

如果参数只有一个,是 名称/函数 哈希键值对,那么每一对 名称/函数 都被加为静态方法。


Schema.prototype.index()

Parameters
  • fields «Object»
  • [options] «Object» 传给 MongoDB 驱动程序的 createIndex() 函数 的选项
  • [options.expires=null] «String» Mongoose 语法糖, 用 msexpires 选项转换成上面链接中 expireAfterSeconds 选项所需要的秒格式。

为该 schema 定义一个索引(大多是复合索引)

示例

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

Schema.prototype.set()

Parameters
  • key «String» 选项的名字
  • [value] «Object» 如果没有传值,选项的当前值被返回

读/写 schema 的一个选项。

示例

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

Schema.prototype.get()

Parameters
  • key «String» 选项的名字

读取 schema 的一个选项。


indexTypes

可用的索引类型


Schema.prototype.indexes()

返回 schema 的索引列表,定义自 schema.index() 或者字段选项 index: true


Schema.prototype.virtual()

Parameters
  • name «String»
  • [options] «Object»
Returns:
  • «VirtualType»

以给定名称创建一个虚拟类型 (virtual type)


Schema.prototype.virtualpath()

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

返回给定名称的虚拟类型。


Schema.prototype.remove()

Parameters
  • path «String|Array»

删除给定的路径 (path 或者 [paths])


Schema.prototype.loadClass()

Parameters
  • model «Function»
  • [virtualsOnly] «Boolean» 如果值为 true,从类中只加载 virtual 字段,忽略实例方法和静态方法。

向 schema 中加载一个 ES6 类。把类中的 setters + getters, static methods, 和 instance methods 映射成为 schema 中的 virtuals,statics, 和 methods

示例:

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

Schema.Types

内建的 Mongoose Schema Types.

示例:

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

Types:

通过这里的暴露入口,我们可以在 schema 中使用 Mixed SchemaType

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

Connection


Connection()

Parameters
  • base «Mongoose» a mongoose instance

Connection constructor

For practical reasons, a Connection equals a Db.


Connection .prototype.readyState

Connection ready state

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

Each state change emits its associated event name.

Example

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

Connection .prototype.collections

A hash of the collections associated with this connection


Connection .prototype.name

The name of the database this connection points to.

Example

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

Connection .prototype.host

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

Example

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

Connection .prototype.port

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

Example

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

Connection .prototype.user

The username specified in the URI

Example

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

Connection .prototype.pass

The password specified in the URI

Example

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

Connection .prototype.db

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


Connection .prototype.config

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


Connection.prototype.createCollection ()

Parameters
  • collection «string» The collection to delete
  • [options] «Object» see MongoDB driver docs
  • [callback] «Function»
Returns:
  • «Promise »

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

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


Connection.prototype.dropCollection ()

Parameters
  • collection «string» The collection to delete
  • [callback] «Function»
Returns:
  • «Promise »

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


Connection.prototype.dropDatabase ()

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

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


Connection.prototype.close()

Parameters
  • [force] «Boolean» optional
  • [callback] «Function» optional
Returns:
  • «Connection» self

Closes the connection


Connection.prototype.collection()

Parameters
  • name «String» of the collection
  • [options] «Object» optional collection options
Returns:
  • «Collection» collection instance

Retrieves a collection, creating it if not cached.

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


Connection.prototype.model()

Parameters
  • name «String» the model name
  • [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
Returns:
  • «Model» The compiled model

Defines or retrieves a model.

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

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

Example:

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

Connection.prototype.modelNames()

Returns:
  • «Array»

Returns an array of model names created on this connection.


Connection.prototype.shouldAuthenticate()

Returns:
  • «Boolean» true if the connection should be authenticated after it is opened, otherwise false.

@brief Returns if the connection requires authentication after it is opened. Generally if a username and password are both provided than authentication is needed, but in some cases a password is not required.


Connection.prototype.authMechanismDoesNotRequirePassword()

Returns:
  • «Boolean» true if the authentication mechanism specified in the options object requires

@brief Returns a boolean value that specifies if the current authentication mechanism needs a password to authenticate according to the auth objects passed into the open/openSet methods.


Connection.prototype.optionsProvideAuthenticationData()

Parameters
  • [options] «Object» the options object passed into the open/openSet methods.
Returns:
  • «Boolean» true if the provided options object provides enough data to authenticate with,

@brief Returns a boolean value that specifies if the provided objects object provides enough data to authenticate with. Generally this is true if the username and password are both specified but in some authentication methods, a password is not required for authentication so only a username is required.


Document


Document.prototype.schema

The documents schema.


Document.prototype.isNew

Boolean flag specifying if the document is new.


Document.prototype.id

The string version of this documents _id.

Note:

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

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

Document.prototype.errors

Hash containing current validation errors.


Document.prototype.$__buildDoc ()

Parameters
  • obj «Object»
  • [fields] «Object»
  • [skipId] «Boolean»

Builds the default doc structure


Document.prototype.init()

Parameters
  • doc «Object» document returned by mongo

Initializes the document without setters or marking anything modified.

Called internally after a document is returned from mongodb.


Document.prototype.update()

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

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

Example:

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

Valid options:


Document .prototype.$set ()

Parameters
  • path «String|Object» path or object of key/vals to set
  • val «Any» the value to set
  • [type] «Schema|String|Number|Buffer|*» optionally specify a type for "on-the-fly" attributes
  • [options] «Object» optionally specify options that modify the behavior of the set

Alias for set(), used internally to avoid conflicts


Document.prototype.set ()

Parameters
  • path «String|Object» path or object of key/vals to set
  • val «Any» the value to set
  • [type] «Schema|String|Number|Buffer|*» optionally specify a type for "on-the-fly" attributes
  • [options] «Object» optionally specify options that modify the behavior of the set

Sets the value of a path, or many paths.

Example:

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

Document.prototype.$__shouldModify ()

Returns:
  • «Boolean »

Determine if we should mark this change as modified.


Document.prototype.$__set ()

Handles the actual setting of the value and marking the path modified if appropriate.


Document.prototype.get()

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

Returns the value of a path.

Example

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

Document.prototype.$__path ()

Parameters
  • path «String»

Returns the schematype for the given path.


Document.prototype.markModified()

Parameters
  • path «String» the path to mark modified
  • [scope] «Document» the scope to run validators with

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

Very helpful when using Mixed types.

Example:

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

Document.prototype.unmarkModified()

Parameters
  • path «String» the path to unmark modified

Clears the modified state on the specified path.

Example:

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

Document .prototype.$ignore ()

Parameters
  • path «String» the path to ignore

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

Example:

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

Document.prototype.modifiedPaths()

Parameters
  • [options] «Object»
  • [options.includeChildren=false] «Boolean» if true, returns children of modified paths as well. For example, if false, the list of modified paths for doc.colors = { primary: 'blue' }; will not contain colors.primary
Returns:
  • «Array »

Returns the list of paths that have been modified.


Document.prototype.isModified()

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

Returns true if this document was modified, else false.

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

Example

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

Document .prototype.$isDefault ()

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

Checks if a path is set to its default.

Example

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

Document .prototype.$isDeleted ()

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

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

Example:

  1. product.remove(function (err, product) {
  2. product.isDeleted(); // true
  3. product.remove(); // no-op, doesn't send anything to the db
  4. product.isDeleted(false);
  5. product.isDeleted(); // false
  6. product.remove(); // will execute a remove against the db
  7. })

Document.prototype.isDirectModified()

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

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

Example

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

Document.prototype.isInit()

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

Checks if path was initialized.


Document.prototype.isSelected()

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

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

Example

  1. Thing.findOne().select('name').exec(function (err, doc) {
  2. doc.isSelected('name') // true
  3. doc.isSelected('age') // false
  4. })

Document.prototype.isDirectSelected()

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

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

Example

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

Document.prototype.validate()

Parameters
  • optional «Object» options internal options
  • callback «Function» optional callback called after validation completes, passing an error if one occurred
Returns:
  • «Promise» Promise

Executes registered validation rules for this document.

Note:

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

Example:

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

Document.prototype.validateSync()

Parameters
  • pathsToValidate «Array|string» only validate the given paths
Returns:
  • «MongooseError,undefined» MongooseError if there are errors during validation, or undefined if there is no error.

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

Note:

This method is useful if you need synchronous validation.

Example:

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

Document.prototype.invalidate()

Parameters
  • path «String» the field to invalidate
  • errorMsg «String|Error» the error which states the reason path was invalid
  • value «Object|String|Number|any» optional invalid value
  • [kind] «String» optional kind property for the error
Returns:
  • «ValidationError» the current ValidationError, with all currently invalidated paths

Marks a path as invalid, causing validation to fail.

The errorMsg argument will become the message of the ValidationError.

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

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

Document .prototype.$markValid()

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

Marks a path as valid, removing existing validation errors.


Document .prototype.save ()

Parameters
  • [options] «Object» options optional options
  • [options.safe] «Object» overrides schema's safe option
  • [options.validateBeforeSave] «Boolean» set to false to save without validating.
  • [fn] «Function» optional callback
Returns:
  • «Promise» Promise

Saves this document.

Example:

  1. product.sold = Date.now();
  2. product.save(function (err, product, numAffected) {
  3. if (err) ..
  4. })

The callback will receive three parameters

  • err if an error occurred
  • product which is the saved product
  • numAffected will be 1 when the document was successfully persisted to MongoDB, otherwise 0. Unless you tweak mongoose's internals, you don't need to worry about checking this parameter for errors - checking err is sufficient to make sure your document was properly saved.

As an extra measure of flow control, save will return a Promise.

Example:

  1. product.save().then(function(product) {
  2. ...
  3. });

Document.prototype.$__reset ()

Returns:
  • «Document »

Resets the internal modified state of this document.


Document.prototype.$__dirty ()

Returns this documents dirty paths / vals.


Document.prototype.$__setSchema ()

Parameters
  • schema «Schema»

Assigns/compiles schema into this documents prototype.


Document.prototype.$__getArrayPathsToValidate ()

Get active path that were changed and are arrays


Document.prototype.$__getAllSubdocs ()

Get all subdocs (by bfs)


Document.prototype.$toObject ()

Internal helper for toObject() and toJSON() that doesn't manipulate options


Document.prototype.toObject()

Parameters
  • [options] «Object»
Returns:
  • «Object» js object

Converts this document into a plain javascript object, ready for storage in MongoDB.

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

Options:

  • getters apply all getters (path and virtual getters)
  • virtuals apply virtual getters (can override getters option)
  • minimize remove empty objects (defaults to true)
  • transform a transform function to apply to the resulting document before returning
  • depopulate depopulate any populated paths, replacing them with their original refs (defaults to false)
  • versionKey whether to include the version key (defaults to true)

Getters/Virtuals

Example of only applying path getters

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

Example of only applying virtual getters

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

Example of applying both path and virtual getters

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

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

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

Transform

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

Transform functions receive three arguments

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

Example

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

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

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

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

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

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

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

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

Transforms are applied only to the document and are not applied to sub-documents.

Transforms, like all of these options, are also available for toJSON.

See schema options for some more details.

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


Document.prototype.toJSON()

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

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

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

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

See schema options for details.


Document.prototype.inspect ()

Helper for console.log


Document.prototype.toString ()

Helper for console.log


Document.prototype.equals()

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

Returns true if the Document stores the same data as doc.

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


Document.prototype.populate()

Parameters
  • [path] «String|Object» The path to populate or an options object
  • [callback] «Function» When passed, population is invoked
Returns:
  • «Document» this

Populates document references, executing the callback when complete. If you want to use promises instead, use this function with execPopulate()

Example:

  1. doc
  2. .populate('company')
  3. .populate({
  4. path: 'notes',
  5. match: /airline/,
  6. select: 'text',
  7. model: 'modelName'
  8. options: opts
  9. }, function (err, user) {
  10. assert(doc._id === user._id) // the document itself is passed
  11. })
  12. // summary
  13. doc.populate(path) // not executed
  14. doc.populate(options); // not executed
  15. doc.populate(path, callback) // executed
  16. doc.populate(options, callback); // executed
  17. doc.populate(callback); // executed
  18. doc.populate(options).execPopulate() // executed, returns promise

NOTE:

Population does not occur unless a callback is passed or you explicitly call execPopulate(). Passing the same path a second time will overwrite the previous path options. See Model.populate() for explaination of options.


Document.prototype.execPopulate()

Returns:
  • «Promise» promise that resolves to the document when population is done

Explicitly executes population and returns a promise. Useful for ES2015 integration.

Example:

  1. var promise = doc.
  2. populate('company').
  3. populate({
  4. path: 'notes',
  5. match: /airline/,
  6. select: 'text',
  7. model: 'modelName'
  8. options: opts
  9. }).
  10. execPopulate();
  11. // summary
  12. doc.execPopulate().then(resolve, reject);

Document .prototype.populated()

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

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

Example:

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

If the path was not populated, undefined is returned.


Document.prototype.depopulate()

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

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

Example:

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

If the path was not populated, this is a no-op.


Document.prototype.$__fullPath ()

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

Returns the full path to this document.


Model


Model()

Parameters
  • doc «Object» values with which to create the document

Model constructor

Provides the interface to MongoDB collections as well as creates document instances.


Model.prototype.db

Connection the model uses.


Model.prototype.collection

Collection the model uses.


Model.prototype.modelName

The name of the model


Model.prototype.$where

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


Model.prototype.baseModelName

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


Model.prototype.save()

Parameters
  • [options] «Object» options optional options
  • [options.safe] «Object» overrides schema's safe option
  • [options.validateBeforeSave] «Boolean» set to false to save without validating.
  • [fn] «Function» optional callback
Returns:
  • «Promise» Promise

Saves this document.

Example:

  1. product.sold = Date.now();
  2. product.save(function (err, product) {
  3. if (err) ..
  4. })

The callback will receive three parameters

  • err if an error occurred
  • product which is the saved product

As an extra measure of flow control, save will return a Promise.

Example:

  1. product.save().then(function(product) {
  2. ...
  3. });

Model.prototype.$__delta ()

Produces a special query document of the modified properties used in updates.


Model.prototype.$__version ()

Appends versioning to the where and update clauses.


Model.prototype.increment()

Signal that we desire an increment of this documents version.

Example:

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

Model.prototype.$__where ()

Returns a query object


Model.prototype.remove()

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

Removes this document from the db.

Example:

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

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

Example:

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

Model.prototype.model()

Parameters
  • name «String» model name

Returns another Model instance.

Example:

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

Model.discriminator()

Parameters
  • name «String» discriminator model name
  • schema «Schema» discriminator model schema
  • value «String» the string stored in the discriminatorKey property

Adds a discriminator type.

Example:

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

Model.init()

Parameters
  • [callback] «Function»

Performs any async initialization of this model against MongoDB. Currently, this function is only responsible for building indexes, unless autoIndex is turned off.

This function is called automatically, so you don't need to call it. This function is also idempotent, so you may call it to get back a promise that will resolve when your indexes are finished building as an alternative to MyModel.on('index')

Example:

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

Model.ensureIndexes()

Parameters
  • [options] «Object» internal options
  • [cb] «Function» optional callback
Returns:
  • «Promise »

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

Example:

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

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

Example:

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

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


Model.createIndexes()

Parameters
  • [options] «Object» internal options
  • [cb] «Function» optional callback
Returns:
  • «Promise »

Similar to ensureIndexes(), except for it uses the createIndex function. The ensureIndex() function checks to see if an index with that name already exists, and, if not, does not attempt to create the index. createIndex() bypasses this check.


Model.prototype.schema

Schema the model uses.


Model.prototype.base

Base Mongoose instance the model uses.


Model.prototype.discriminators

Registered discriminators for this model.


Model.translateAliases()

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

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

Example:

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

Note:

Only translate arguments of object type anything else is returned raw


Model.remove()

Parameters
  • conditions «Object»
  • [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.

Example:

  1. Character.remove({ name: 'Eddard Stark' }, function (err) {});

Note:

This method sends a remove command directly to MongoDB, no Mongoose documents are involved. Because no Mongoose documents are involved, no middleware (hooks) are executed.


Model.deleteOne()

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

Deletes the first document that matches conditions from the collection. Behaves like remove(), but deletes at most one document regardless of the single option.

Example:

  1. Character.deleteOne({ name: 'Eddard Stark' }, function (err) {});

Note:

Like Model.remove(), this function does not trigger pre('remove') or post('remove') hooks.


Model.deleteMany()

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

Deletes all of the documents that match conditions from the collection. Behaves like remove(), but deletes all documents that match conditions regardless of the single option.

Example:

  1. Character.deleteMany({ name: /Stark/, age: { $gte: 18 } }, function (err) {});

Note:

Like Model.remove(), this function does not trigger pre('remove') or post('remove') hooks.


Model.find()

Parameters
Returns:
  • «Query »

Finds documents

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

Examples:

  1. // named john and at least 18
  2. MyModel.find({ name: 'john', age: { $gte: 18 }});
  3. // executes immediately, passing results to callback
  4. MyModel.find({ name: 'john', age: { $gte: 18 }}, function (err, docs) {});
  5. // name LIKE john and only selecting the "name" and "friends" fields, executing immediately
  6. MyModel.find({ name: /john/i }, 'name friends', function (err, docs) { })
  7. // passing options
  8. MyModel.find({ name: /john/i }, null, { skip: 10 })
  9. // passing options and executing immediately
  10. MyModel.find({ name: /john/i }, null, { skip: 10 }, function (err, docs) {});
  11. // executing a query explicitly
  12. var query = MyModel.find({ name: /john/i }, null, { skip: 10 })
  13. query.exec(function (err, docs) {});
  14. // using the promise returned from executing a query
  15. var query = MyModel.find({ name: /john/i }, null, { skip: 10 });
  16. var promise = query.exec();
  17. promise.addBack(function (err, docs) {});

Model.findById()

Parameters
Returns:
  • «Query »

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

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

This function triggers the following middleware.

  • findOne()
  • Except for how it treats undefined. If you use findOne(), you'll see that findOne(undefined) and findOne({ _id: undefined }) are equivalent to findOne({}) and return arbitrary documents. However, mongoose translates findById(undefined) into findOne({ _id: null }).

Example:

  1. // find adventure by id and execute immediately
  2. Adventure.findById(id, function (err, adventure) {});
  3. // same as above
  4. Adventure.findById(id).exec(callback);
  5. // select only the adventures name and length
  6. Adventure.findById(id, 'name length', function (err, adventure) {});
  7. // same as above
  8. Adventure.findById(id, 'name length').exec(callback);
  9. // include all properties except for `length`
  10. Adventure.findById(id, '-length').exec(function (err, adventure) {});
  11. // passing options (in this case return the raw js objects, not mongoose documents by passing `lean`
  12. Adventure.findById(id, 'name', { lean: true }, function (err, doc) {});
  13. // same as above
  14. Adventure.findById(id, 'name').lean().exec(function (err, doc) {});

Model.findOne()

Parameters
Returns:
  • «Query »

Finds one document.

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

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

Example:

  1. // find one iphone adventures - iphone adventures??
  2. Adventure.findOne({ type: 'iphone' }, function (err, adventure) {});
  3. // same as above
  4. Adventure.findOne({ type: 'iphone' }).exec(function (err, adventure) {});
  5. // select only the adventures name
  6. Adventure.findOne({ type: 'iphone' }, 'name', function (err, adventure) {});
  7. // same as above
  8. Adventure.findOne({ type: 'iphone' }, 'name').exec(function (err, adventure) {});
  9. // specify options, in this case lean
  10. Adventure.findOne({ type: 'iphone' }, 'name', { lean: true }, callback);
  11. // same as above
  12. Adventure.findOne({ type: 'iphone' }, 'name', { lean: true }).exec(callback);
  13. // chaining findOne queries (same as above)
  14. Adventure.findOne({ type: 'iphone' }).select('name').lean().exec(callback);

Model.count()

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

Counts number of matching documents in a database collection.

Example:

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

Model.distinct()

Parameters
  • field «String»
  • [conditions] «Object» optional
  • [callback] «Function»
Returns:
  • «Query »

Creates a Query for a distinct operation.

Passing a callback immediately executes the query.

Example

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

Model.where()

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

Creates a Query, applies the passed conditions, and returns the Query.

For example, instead of writing:

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

we can instead write:

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

Since the Query class also supports where you can continue chaining

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

Model .prototype.$where ()

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

Creates a Query and specifies a $where condition.

Sometimes you need to query for things in mongodb using a JavaScript expression. You can do so via find({ $where: javascript }), or you can use the mongoose shortcut method $where via a Query chain or from your mongoose Model.

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

Model.findOneAndUpdate()

Parameters
  • [conditions] «Object»
  • [update] «Object»
  • [options] «Object» optional see Query.prototype.setOptions()
  • [options.lean] «Object» if truthy, mongoose will return the document as a plain JavaScript object rather than a mongoose document. See Query.lean().
  • [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 immediately 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.
  • fields: {Object|String} - Field selection. Equivalent to .select(fields).findOneAndUpdate()
  • maxTimeMS: puts a time limit on the query - requires mongodb >= 2.6.0
  • sort: if multiple docs are found by the conditions, sets the sort order to choose which doc to update
  • runValidators: if true, runs update validators on this command. Update validators validate the update operation against the model's schema.
  • setDefaultsOnInsert: if this and upsert are true, mongoose will apply the defaults specified in the model's schema if a new document is created. This option only works on MongoDB >= 2.4 because it relies on MongoDB's $setOnInsert operator.
  • rawResult: if true, returns the raw result from the MongoDB driver
  • strict: overwrites the schema's strict mode option for this update

Examples:

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

Note:

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

Example:

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

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

Note:

Values are cast to their appropriate types when using the findAndModify helpers. However, the below are not executed by default.

  • defaults. Use the setDefaultsOnInsert option to override.

findAndModify helpers support limited validation. You can enable these by setting the runValidators options, respectively.

If you need full-fledged validation, use the traditional approach of first retrieving the document.

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

Model.findByIdAndUpdate()

Parameters
  • id «Object|Number|String» value of _id to query by
  • [update] «Object»
  • [options] «Object» optional see Query.prototype.setOptions()
  • [options.lean] «Object» if truthy, mongoose will return the document as a plain JavaScript object rather than a mongoose document. See Query.lean().
  • [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 immediately if callback is passed else a Query object is returned.

This function triggers the following middleware.

  • findOneAndUpdate()

Options:

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

Examples:

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

Note:

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

Example:

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

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

Note:

Values are cast to their appropriate types when using the findAndModify helpers. However, the below are not executed by default.

  • defaults. Use the setDefaultsOnInsert option to override.

findAndModify helpers support limited validation. You can enable these by setting the runValidators options, respectively.

If you need full-fledged validation, use the traditional approach of first retrieving the document.

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

Model.findOneAndRemove()

Parameters
Returns:
  • «Query »

Issue a mongodb findAndModify remove command.

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

Executes immediately if callback is passed else a Query object is returned.

This function triggers the following middleware.

  • findOneAndRemove()

Options:

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

Examples:

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

Values are cast to their appropriate types when using the findAndModify helpers. However, the below are not executed by default.

  • defaults. Use the setDefaultsOnInsert option to override.

findAndModify helpers support limited validation. You can enable these by setting the runValidators options, respectively.

If you need full-fledged validation, use the traditional approach of first retrieving the document.

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

Model.findByIdAndRemove()

Parameters
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 immediately if callback is passed, else a Query object is returned.

This function triggers the following middleware.

  • findOneAndRemove()

Options:

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

Examples:

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

Model.create()

Parameters
  • docs «Array|Object» Documents to insert, as a spread or array
  • [callback] «Function» callback
Returns:
  • «Promise »

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

This function triggers the following middleware.

  • save()

Example:

  1. // pass a spread of docs and a callback
  2. Candy.create({ type: 'jelly bean' }, { type: 'snickers' }, function (err, jellybean, snickers) {
  3. if (err) // ...
  4. });
  5. // pass an array of docs
  6. var array = [{ type: 'jelly bean' }, { type: 'snickers' }];
  7. Candy.create(array, function (err, candies) {
  8. if (err) // ...
  9. var jellybean = candies[0];
  10. var snickers = candies[1];
  11. // ...
  12. });
  13. // callback is optional; use the returned promise if you like:
  14. var promise = Candy.create({ type: 'jawbreaker' });
  15. promise.then(function (jawbreaker) {
  16. // ...
  17. })

Model.watch()

Parameters
Returns:
  • «ChangeStream» mongoose-specific change stream wrapper

Requires a replica set running MongoDB >= 3.6.0. Watches the underlying collection for changes using MongoDB change streams.

This function does not trigger any middleware. In particular, it does not trigger aggregate middleware.

Example:

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

Model.insertMany()

Parameters
  • doc(s) «Array|Object|*»
  • [options] «Object» see the mongodb driver options
  • [options.ordered «Boolean» = true] if true, will fail fast on the first error encountered. If false, will insert all the documents it can and report errors later. An insertMany() with ordered = false is called an "unordered" insertMany().
  • [options.rawResult «Boolean» = false] if false, the returned promise resolves to the documents that passed mongoose document validation. If false, will return the raw result from the MongoDB driver with a mongoose property that contains validationErrors if this is an unordered insertMany.
  • [callback] «Function» callback
Returns:
  • «Promise »

Shortcut for validating an array of documents and inserting them into MongoDB if they're all valid. This function is faster than .create() because it only sends one operation to the server, rather than one for each document.

Mongoose always validates each document before sending insertMany to MongoDB. So if one document has a validation error, no documents will be saved, unless you set the ordered option to false.

This function does not trigger save middleware.

This function triggers the following middleware.

  • insertMany()

Example:

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

Model.bulkWrite()

Parameters
  • ops «Array»
  • [options] «Object»
  • [callback] «Function» callback function(error, bulkWriteOpResult) {}
Returns:
  • «Promise» resolves to a BulkWriteOpResult if the operation succeeds

Sends multiple insertOne, updateOne, updateMany, replaceOne, deleteOne, and/or deleteMany operations to the MongoDB server in one command. This is faster than sending multiple independent operations (like) 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, not save() nor update(). If you need to trigger save() middleware for every document use create() instead.

Example:

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

Model.hydrate()

Parameters
  • obj «Object»
Returns:
  • «Model» document instance

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

Example:

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

Model.update()

Parameters
Returns:
  • «Query »

Updates one document in the database without returning it.

This function triggers the following middleware.

  • update()

Examples:

  1. MyModel.update({ age: { $gt: 18 } }, { oldEnough: true }, fn);
  2. MyModel.update({ name: 'Tobi' }, { ferret: true }, { multi: true }, function (err, raw) {
  3. if (err) return handleError(err);
  4. console.log('The raw response from Mongo was ', raw);
  5. });

Valid options:

  • safe (boolean) safe mode (defaults to value set in schema (true))
  • upsert (boolean) whether to create the doc if it doesn't match (false)
  • multi (boolean) whether multiple documents should be updated (false)
  • runValidators: if true, runs update validators on this command. Update validators validate the update operation against the model's schema.
  • setDefaultsOnInsert: if this and upsert are true, mongoose will apply the defaults specified in the model's schema if a new document is created. This option only works on MongoDB >= 2.4 because it relies on MongoDB's $setOnInsert operator.
  • strict (boolean) overrides the strict option for this update
  • overwrite (boolean) disables update-only mode, allowing you to overwrite the doc (false)

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

The callback function receives (err, rawResponse).

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

Note:

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

Example:

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

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

Note:

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

Note:

To update documents without waiting for a response from MongoDB, do not pass a callback, then call exec on the returned Query:

  1. Comment.update({ _id: id }, { $set: { text: 'changed' }}).exec();

Note:

Although values are casted to their appropriate types when using update, the following are not applied:

  • defaults
  • setters
  • validators
  • middleware

If you need those features, use the traditional approach of first retrieving the document.

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

Model.updateMany()

Parameters
Returns:
  • «Query »

Same as update(), except MongoDB will update all documents that match criteria (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.

This function triggers the following middleware.

  • updateMany()

Model.updateOne()

Parameters
Returns:
  • «Query »

Same as update(), except MongoDB will update only the first document that matches criteria regardless of the value of the multi option.

This function triggers the following middleware.

  • updateOne()

Model.replaceOne()

Parameters
Returns:
  • «Query »

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

This function triggers the following middleware.

  • replaceOne()

Model.mapReduce()

Parameters
  • o «Object» an object specifying map-reduce options
  • [callback] «Function» optional callback
Returns:
  • «Promise »

Executes a mapReduce command.

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

This function does not trigger any middleware.

Example:

  1. var o = {};
  2. o.map = function () { emit(this.name, 1) }
  3. o.reduce = function (k, vals) { return vals.length }
  4. User.mapReduce(o, function (err, results) {
  5. console.log(results)
  6. })

Other options:

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

* out options:

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

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

Example:

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

Model.aggregate()

Parameters
  • [pipeline] «Array» aggregation pipeline as an array of objects
  • [callback] «Function»
Returns:
  • «Aggregate »

Performs aggregations on the models collection.

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

This function does not trigger any middleware.

Example:

  1. // Find the max balance of all accounts
  2. Users.aggregate([
  3. { $group: { _id: null, maxBalance: { $max: '$balance' }}},
  4. { $project: { _id: 0, maxBalance: 1 }}
  5. ]).
  6. then(function (res) {
  7. console.log(res); // [ { maxBalance: 98000 } ]
  8. });
  9. // Or use the aggregation pipeline builder.
  10. Users.aggregate()
  11. .group({ _id: null, maxBalance: { $max: '$balance' } })
  12. .select('-id maxBalance')
  13. .exec(function (err, res) {
  14. if (err) return handleError(err);
  15. console.log(res); // [ { maxBalance: 98 } ]
  16. });

NOTE:

  • Arguments are not cast to the model's schema because $project operators allow redefining the "shape" of the documents at any stage of the pipeline, which may leave documents in an incompatible format.
  • The documents returned are plain javascript objects, not mongoose documents (since any shape of document can be returned).
  • Requires MongoDB >= 2.1

Model.geoSearch()

Parameters
  • conditions «Object» an object that specifies the match condition (required)
  • options «Object» for the geoSearch, some (near, maxDistance) are required
  • [options.lean] «Object» if truthy, mongoose will return the document as a plain JavaScript object rather than a mongoose document. See Query.lean().
  • [callback] «Function» optional callback
Returns:
  • «Promise »

Implements $geoSearch functionality for Mongoose

This function does not trigger any middleware

Example:

  1. var options = { near: [10, 10], maxDistance: 5 };
  2. Locations.geoSearch({ type : "house" }, options, function(err, res) {
  3. console.log(res);
  4. });

Options:

  • near {Array} x,y point to search for
  • maxDistance {Number} the maximum distance from the point near that a result can be
  • limit {Number} The maximum number of results to return
  • lean {Boolean} return the raw object instead of the Mongoose Model

Model.populate()

Parameters
  • docs «Document|Array» Either a single document or array of documents to populate.
  • options «Object» A hash of key/val (path, options) used for population.
  • [callback(err,doc)] «Function» Optional callback, executed upon completion. Receives err and the doc(s).
Returns:
  • «Promise »

Populates document references.

Available 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

Examples:

  1. // populates a single object
  2. User.findById(id, function (err, user) {
  3. var opts = [
  4. { path: 'company', match: { x: 1 }, select: 'name' }
  5. , { path: 'notes', options: { limit: 10 }, model: 'override' }
  6. ]
  7. User.populate(user, opts, function (err, user) {
  8. console.log(user);
  9. });
  10. });
  11. // populates an array of objects
  12. User.find(match, function (err, users) {
  13. var opts = [{ path: 'company', match: { x: 1 }, select: 'name' }]
  14. var promise = User.populate(users, opts);
  15. promise.then(console.log).end();
  16. })
  17. // imagine a Weapon model exists with two saved documents:
  18. // { _id: 389, name: 'whip' }
  19. // { _id: 8921, name: 'boomerang' }
  20. // and this schema:
  21. // new Schema({
  22. // name: String,
  23. // weapon: { type: ObjectId, ref: 'Weapon' }
  24. // });
  25. var user = { name: 'Indiana Jones', weapon: 389 }
  26. Weapon.populate(user, { path: 'weapon', model: 'Weapon' }, function (err, user) {
  27. console.log(user.weapon.name) // whip
  28. })
  29. // populate many plain objects
  30. var users = [{ name: 'Indiana Jones', weapon: 389 }]
  31. users.push({ name: 'Batman', weapon: 8921 })
  32. Weapon.populate(users, { path: 'weapon' }, function (err, users) {
  33. users.forEach(function (user) {
  34. console.log('%s uses a %s', users.name, user.weapon.name)
  35. // Indiana Jones uses a whip
  36. // Batman uses a boomerang
  37. });
  38. });
  39. // Note that we didn't need to specify the Weapon model because
  40. // it is in the schema's ref

Query


Query()

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

Query 构造函数,用来构建查询器(query),不过并不需要直接实例化 Query 对象,而是用 Model 的 Model.find() 这些函数。

示例:

  1. const query = MyModel.find(); // `query` 是 `Query` 的一个实例
  2. query.setOptions({ lean : true });
  3. query.collection(MyModel.collection);
  4. query.where('age').gte(21).exec(callback);
  5. // 你也可以实例化一个 query,不过没有必要这么做,除非你是个高级用户又有充分的理由。
  6. const query = new mongoose.Query();

Query .prototype.use$geoWithin

选择是否启用 $geoWithin 的标识。

  1. mongoose.Query.use$geoWithin = false;

MongoDB 2.4 不再赞成使用 $within,而是用 $geoWithin 代替。Mongoose 默认使用 $geoWithin(对 $within 100%后向兼容)。 你如果运行较低版本的 MongoDB,把这个标识置为 false 就能使 within() 继续有效。


Query.prototype.toConstructor()

Returns:
  • «Query» subclass-of-Query

把当前 query 转换成自定义、可复用的而且保留当前所有参数(arguments)和选项(options)的构造函数。

示例

  1. // 为 adventure movies 生成一个 query,并从复本集(replica-set)中的主节点读取数据,
  2. // 如果主节点宕机,则从第二节点读取。
  3. var query = Movie.find({ tags: 'adventure' }).read('primaryPreferred');
  4. // 基于上面的设置创建一个自定义 Query 构造函数
  5. var Adventure = query.toConstructor();
  6. // Adventure 就成了 mongoose.Query 的子类,使用方式一致,并且已设置了默认的查询参数和选项。
  7. Adventure().exec(callback)
  8. // 在之前的设置基础上进一步缩小查询结果集
  9. Adventure().where({ name: /^Life/ }).exec(callback);
  10. // 由于 Adventure 是个独立的构造函数,我们也可以向其添加自定义的辅助方法( helper methods )
  11. // 和 getter 函数,并且不会影响到全局查询。
  12. Adventure.prototype.startsWith = function (prefix) {
  13. this.where({ name: new RegExp('^' + prefix) })
  14. return this;
  15. }
  16. Object.defineProperty(Adventure.prototype, 'highlyRated', {
  17. get: function () {
  18. this.where({ rating: { $gt: 4.5 }});
  19. return this;
  20. }
  21. })
  22. Adventure().highlyRated.startsWith('Life').exec(callback)

从版本3.7.3开始的新功能


Query .prototype.$where ()

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

指定一个传给 MongoDB query 的函数或表达式。

示例

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

注意:

只有当 MongoDB 其他操作符(如 $lt)不能表达你的查询条件时再使用 $where使用之前一定要阅读它的所有警告


Query .prototype.where ()

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

在链式用法中指定一个 path

示例

  1. // find 写法:
  2. User.find({age: {$gte: 21, $lte: 65}}, callback);
  3. // where 替换写法:
  4. User.where('age').gte(21).lte(65);
  5. // 也可以传入 query condition
  6. User.find().where({ name: 'vonderful' })
  7. // 链式写法
  8. User
  9. .where('age').gte(21).lte(65)
  10. .where('name', /^vonderful/i)
  11. .where('friends').slice(10)
  12. .exec(callback)

Query .prototype.equals ()

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

指定一个值,跟 where() 指定的路径做等值比较。

示例

  1. User.where('age').equals(49);
  2. // 等效于
  3. User.where('age', 49);

Query .prototype.or ()

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

$or 条件指定参数。

示例

  1. query.or([{ color: 'red' }, { status: 'emergency' }])

Query .prototype.nor ()

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

$nor 条件指定参数。

示例

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

Query .prototype.and ()

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

$and 条件指定参数。

示例

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

Query .prototype.gt ()

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

指定一个 $gt 查询条件。

如果只传入一个参数,则对最后的 where() 路径生效。

示例

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

Query .prototype.gte ()

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

指定一个 $gte 查询条件。

如果只传入一个参数,则对最后的 where() 路径生效。


Query .prototype.lt ()

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

指定一个 $lt 查询条件。

如果只传入一个参数,则对最后的 where() 路径生效。


Query .prototype.lte ()

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

指定一个 $lte 查询条件。

如果只传入一个参数,则对最后的 where() 路径生效。


Query .prototype.ne ()

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

指定一个 $ne 查询条件。

如果只传入一个参数,则对最后的 where() 路径生效。


Query .prototype.in ()

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

指定一个 $in 查询条件。

如果只传入一个参数,则对最后的 where() 路径生效。


Query .prototype.nin ()

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

指定一个 $nin 查询条件。

如果只传入一个参数,则对最后的 where() 路径生效。


Query .prototype.all ()

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

指定一个 $all 查询条件。

如果只传入一个参数,则对最后的 where() 路径生效。


Query .prototype.size ()

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

指定一个 $size 查询条件。

如果只传入一个参数,则对最后的 where() 路径生效。

示例

  1. MyModel.where('tags').size(0).exec(function (err, docs) {
  2. if (err) return handleError(err);
  3. assert(Array.isArray(docs));
  4. console.log('documents with 0 tags', docs);
  5. })

Query .prototype.regex ()

Parameters
  • [path] «String»
  • val «String|RegExp»

指定一个 $regex 查询条件。

如果只传入一个参数,则对最后的 where() 路径生效。


Query .prototype.maxDistance ()

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

指定一个 $maxDistance 查询条件。

如果只传入一个参数,则对最后的 where() 路径生效。


Query .prototype.mod ()

Parameters
  • [path] «String»
  • val «Array» 长度必须是2,第一个元素是 divisor,第二个是 remainder.
Returns:
  • «Query» this

指定一个 $mod 条件,对文档的过滤规则:属性 path 是个数值,且对 divisor 取模,余数等于 remainder

示例

  1. // products 中 inventory 是奇数的
  2. Product.find().mod('inventory', [2, 1]);
  3. Product.find().where('inventory').mod([2, 1]);
  4. // 这种语法有点儿奇怪,但也支持。
  5. Product.find().where('inventory').mod(2, 1);

Query .prototype.exists ()

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

指定一个 $exists 查询条件。

示例

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

Query .prototype.elemMatch ()

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

指定一个 $elemMatch 查询条件。

示例

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

Query .prototype.within ()

Returns:
  • «Query» this

给地理空间(geo-spatial)查询 $within$geoWithin 指定参数

示例

  1. query.where(path).within().box()
  2. query.where(path).within().circle()
  3. query.where(path).within().geometry()
  4. query.where('loc').within({ center: [50,50], radius: 10, unique: true, spherical: true });
  5. query.where('loc').within({ box: [[40.73, -73.9], [40.7, -73.988]] });
  6. query.where('loc').within({ polygon: [[],[],[],[]] });
  7. query.where('loc').within([], [], []) // polygon
  8. query.where('loc').within([], []) // box
  9. query.where('loc').within({ type: 'LineString', coordinates: [...] }); // geometry

必须where() 一起使用。

注意:

从 Mongoose 3.7 开始,查询中默认使用 $geoWithin。想改变这种做法,查看 Query.use$geoWithin

注意:

在 Mongoose 3.7 中,within 由 getter 改变成了 function。如果你需要旧语法,查看 这里


Query .prototype.slice ()

Parameters
  • [path] «String»
  • val «Number» number/range of elements to slice
Returns:
  • «Query» this

对数组字段做切片映射($slice projection)。

示例

  1. query.slice('comments', 5)
  2. query.slice('comments', -5)
  3. query.slice('comments', [10, 5])
  4. query.where('comments').slice(5)
  5. query.where('comments').slice([-10, 5])

Query .prototype.limit ()

Parameters
  • val «Number»

指定查询结果的最大条数。

示例

  1. query.limit(20)

注意

不能和 distinct() 一起使用


Query .prototype.skip ()

Parameters
  • val «Number»

指定跳过的文档条数。

示例

  1. query.skip(100).limit(20)

注意

不能和 distinct() 一起使用


Query .prototype.maxScan ()

Parameters
  • val «Number»

指定 maxScan 选项

示例

  1. query.maxScan(100)

注意

不能和 distinct() 一起使用


Query .prototype.batchSize ()

Parameters
  • val «Number»

指定 batchSize 选项

示例

  1. query.batchSize(100)

注意

不能和 distinct() 一起使用


Query .prototype.comment ()

Parameters
  • val «Number»

指定 comment 选项

示例

  1. query.comment('login query')

注意

不能和 distinct() 一起使用


Query .prototype.snapshot ()

Returns:
  • «Query» this

指定当前 query 是个 snapshot query

示例

  1. query.snapshot() // true
  2. query.snapshot(true)
  3. query.snapshot(false)

注意

不能和 distinct() 一起使用


Query .prototype.hint ()

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

设置查询会使用的索引

示例

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

注意

不能和 distinct() 一起使用


Query .prototype.select ()

Parameters
  • arg «Object|String»
Returns:
  • «Query» this

指定包含或排除哪些字段(也叫做查询映射 "projection" )

使用字符串语法时,有 - 前缀的路径会被排除,没有 - 前缀的路径会被选择。 最后,如果路径有前缀 +,将被强制选择,这对于在 schema level 被排除的路径会有用。

映射 必须 只能是 包含 或 排除 二者其一。换句话说,只能要么列举包含的字段(将排除其他所有字段),要么列举排除的字段(将选择其他所有字段)。 _id 字段总会被选择因为 MongoDB 默认会这么做.

示例

  1. // 选择 a 和 b 字段,排除其他的
  2. query.select('a b');
  3. // 排除 c 和 d 字段,选择其他的
  4. query.select('-c -d');
  5. // 如果存在已经有"-"前缀的字段,可以用对象标记法
  6. query.select({ a: 1, b: 1 });
  7. query.select({ c: 0, d: 0 });
  8. // 强制包含已经在 schema level 排除的字段
  9. query.select('+path')

Query .prototype.slaveOk ()

Parameters
  • v «Boolean» defaults to true
Returns:
  • «Query» this

已不赞成使用 设置 slaveOk 选项

Deprecated 从 MongoDB 2.2 版本之后使用 read preferences 代替

示例:

  1. query.slaveOk() // true
  2. query.slaveOk(true)
  3. query.slaveOk(false)

Query .prototype.read ()

Parameters
  • pref «String» one of the listed preference options or aliases
  • [tags] «Array» optional tags for this query
Returns:
  • «Query» this

指定读数据的 MongoDB 节点

首选项:

  1. primary - (默认值) 只从主节点读取。如果主节点不可用则报错。不能跟 tags 选项组合使用。
  2. secondary 只有当从节点可用时,从中读取,否则报错。
  3. primaryPreferred 优先读取主节点,不可用时读取从节点。
  4. secondaryPreferred 优先读取从节点,不可用时读取主节点。
  5. nearest 所有操作都读最近的候选节点,不同于其他模式,该选项会随机选取所有主、从节点。

选项别名:

  1. p primary
  2. pp primaryPreferred
  3. s secondary
  4. sp secondaryPreferred
  5. n nearest

示例:

  1. new Query().read('primary')
  2. new Query().read('p') // 等效于 primary
  3. new Query().read('primaryPreferred')
  4. new Query().read('pp') // 等效于 primaryPreferred
  5. new Query().read('secondary')
  6. new Query().read('s') // 等效于 secondary
  7. new Query().read('secondaryPreferred')
  8. new Query().read('sp') // 等效于 secondaryPreferred
  9. new Query().read('nearest')
  10. new Query().read('n') // 等效于 nearest
  11. // 读取匹配 tags 的从节点
  12. new Query().read('s', [{ dc:'sf', s: 1 },{ dc:'ma', s: 2 }])

这里这里 参阅更多 read 首选项的用法。


Query.prototype.setOptions()

Parameters
  • options «Object»

设置查询选项。某些选项只对特定操作生效。

选项:

以下选项只适用于 find(): - tailable - sort%7D%7D) - limit - skip - maxscan - batchSize - comment - snapshot - readPreference - hint

以下选项只适用于 update(), updateOne(), updateMany(), replaceOne(), findOneAndUpdate()findByIdAndUpdate(): - upsert - writeConcern

以下选项只适用于 find(), findOne(), findById(), findOneAndUpdate()findByIdAndUpdate(): - lean

以下选项适用于所有操作 (除这些以外 update(), updateOne(), updateMany(), remove(), deleteOne()deleteMany() ): - maxTimeMS

以下选项适用于所有操作: - collation


Query.prototype.getQuery()

Returns:
  • «Object» current query conditions

以 JSON 对象格式返回当前的 query conditions。

示例:

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

Query.prototype.getUpdate()

Returns:
  • «Object» current update operations

以 JSON 对象格式返回当前的 update operations。

示例:

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

function Object() { [native code] }.prototype._fieldsForExec ()

Returns:
  • «Object »

Returns fields selection for this query.


Query.prototype._updateForExec ()

Return an update document with corrected $set operations.


function Object() { [native code] }.prototype._ensurePath ()

Parameters
  • method «String»

Makes sure _path is set.


Query.prototype.lean()

Parameters
  • bool «Boolean|Object» 默认值 true
Returns:
  • «Query» this

设置 lean 选项

那些激活 lean 选项的查询,返回的文档是普通 javascript 对象,而不是 Mongoose Documents。 这些对象没有 save 方法、getters/setters,也没有被赋予其他 Mongoose magic。

示例:

  1. new Query().lean() // true
  2. new Query().lean(true)
  3. new Query().lean(false)
  4. Model.find().lean().exec(function (err, docs) {
  5. docs[0] instanceof mongoose.Document // false
  6. });

在高性能只读场景下这个选项就 厉害 了,特别是跟 stream 组合使用时。


Query.prototype.error()

Parameters
  • err «Error|null» 如果被赋值,exec() 会在查询被发送到 MongoDB 之前速效失败

读取/赋值 query 的 error 标识。如果标识不是 null 或 undefined,exec() promise 会直接执行 reject.

示例:

  1. Query().error(); // 读当前 error 值
  2. Query().error(null); // 空置当前 error
  3. Query().error(new Error('test')); // `exec()` will reject with test
  4. Schema.pre('find', function() {
  5. if (!this.getQuery().userId) {
  6. this.error(new Error('Not allowed to query without setting userId'));
  7. }
  8. });

注意:query casting 在 hooks 之后 执行,所以 cast errors 会覆盖自定义 errors。

示例:

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

Query.prototype.mongooseOptions()

Parameters
  • options «Object» if specified, overwrites the current options

Getter/setter around the current mongoose-specific options for this query (populate, lean, etc.)


Query.prototype.find()

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

查询文档

如果不传入 callback 查询不会被执行。实际执行时,查询结果是个文档数组。

示例

  1. query.find({ name: 'Los Pollos Hermanos' }).find(callback)

Query .prototype.merge ()

Parameters
  • source «Query|Object»
Returns:
  • «Query» this

把另一个 Query 或者 condition 对象合并到当前 query。

如果传入的是一个 Query,条件对象、字段选择和选项都会被合并。

3.7.0版本新功能


Query.prototype.collation()

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

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


Query.prototype.findOne()

Parameters
  • [conditions] «Object» mongodb selector
  • [projection] «Object» 可选 要选择的字段
  • [options] «Object» 见 setOptions()
  • [callback] «Function» 可选 参数表是 (error, document)
Returns:
  • «Query» this

声明一个 findOne 查询。传给回调函数的查询结果是第一个查到的文档。

传入 callback 时启动查询。结果是单个文档。

  • 注意: conditions 是可选的,如果 conditions 是 null 或 undefined, mongoose 会向 MongoDB 发送一个空的 findOne 指令,返回结果会是一个随机文档。 如果要按 _id 进行查询,可以用 Model.findById()

这个函数触发以下中间件

  • findOne()

示例

  1. var query = Kitten.where({ color: 'white' });
  2. query.findOne(function (err, kitten) {
  3. if (err) return handleError(err);
  4. if (kitten) {
  5. // 如果没有匹配的文档 kitten 是 null
  6. }
  7. });

Query.prototype.count()

Parameters
  • [conditions] «Object» mongodb selector
  • [callback] «Function» 可选 参数表是 (error, count)
Returns:
  • «Query» this

声明一个 count 查询

传入 callback 时启动查询

这个函数触发以下中间件

  • count()

示例:

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

Query.prototype.distinct()

Parameters
  • [field] «String»
  • [filter] «Object|Query»
  • [callback] «Function» 可选 参数表是 (error, arr)
Returns:
  • «Query» this

声明或执行 distict() 操作

传入 callback 启动查询

这个函数不触发中间件

示例

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

Query.prototype.sort()

Parameters
  • arg «Object|String»
Returns:
  • «Query» this

设置排序

如果传入的参数是个对象,字段值可以是 asc, desc, ascending, descending, 1-1

如果传入参数是字符串,它得是以空格间隔的字段路径名列表。每个字段的排列顺序默认是正序,如果字段名有 - 前缀, 那么这个字段是倒序。

示例

  1. // 按照 "field" 字段正序、"test" 字段倒序排列
  2. query.sort({ field: 'asc', test: -1 });
  3. // 等效于
  4. query.sort('field -test');

注意

不能和 distinct() 一起使用


Query.prototype.remove()

Parameters
  • [filter] «Object|Query» mongodb selector
  • [callback] «Function» 可选 参数表是 (error, writeOpResult)
Returns:
  • «Query» this

声明/执行删除操作

这个函数不触发中间件

示例

  1. Model.remove({ artist: 'Anne Murray' }, callback)

注意

只有当传入 callback 时操作才会被执行。如果要强制不带 callback 就执行,你得先调用 remove() 然后调用 exec() 来让它执行。

  1. // 不会执行
  2. var query = Model.find().remove({ name: 'Anne Murray' })
  3. // 会被执行
  4. query.remove({ name: 'Anne Murray' }, callback)
  5. query.remove({ name: 'Anne Murray' }).remove(callback)
  6. // 没有 callback 就执行
  7. query.exec()
  8. // 总结
  9. query.remove(conds, fn); // 执行
  10. query.remove(conds)
  11. query.remove(fn) // 执行
  12. query.remove()

Query.prototype.deleteOne()

Parameters
  • [filter] «Object|Query» mongodb selector
  • [callback] «Function» 可选 参数表是 (error, writeOpResult)
Returns:
  • «Query» this

声明/执行 deleteOne() 操作。 功能类似 remove,不过会忽略 single 选项最多删除一条文档。

这个函数不触发中间件.

示例

  1. Character.deleteOne({ name: 'Eddard Stark' }, callback)
  2. Character.deleteOne({ name: 'Eddard Stark' }).then(next)

Query.prototype.deleteMany()

Parameters
  • [filter] «Object|Query» mongodb selector
  • [callback] «Function» 可选 参数表是 (error, writeOpResult)
Returns:
  • «Query» this

声明 / 执行一次 deleteMany() 操作。功能类似于 remove,不过会忽略 single 选项,删除集合中 每一条 匹配条件的文档。

这个函数不触发中间件

示例

  1. Character.deleteMany({ name: /Stark/, age: { $gte: 18 } }, callback)
  2. Character.deleteMany({ name: /Stark/, age: { $gte: 18 } }).then(next)

Query .prototype.findOneAndUpdate ()

Parameters
  • [query] «Object|Query»
  • [doc] «Object»
  • [options] «Object»
  • [options.rawResult] «Boolean»
  • [options.strict] «Boolean|String» 覆盖 schema 的 严格模式 选项
  • [options.multipleCastError] «Boolean» 默认情况下 mongoose 只返回第一个 cast 错误。激活该选项来聚合所有的 cast 错误。
  • [options.lean] «Object» 如果值是 true, mongoose 以 plain JavaScript object 格式返回文档,不再实例化成一个 model 文档。参阅 Query.lean().
  • [callback] «Function» 可选 参数表是 (error, doc), 除非 设置了 rawResult 选项,那么参数将是 (error, writeOpResult)
Returns:
  • «Query» this

向 mongodb 发起一条 findAndModify 更新指令。

查到一条匹配的文档,依据 doc 参数和 options 选项更新文档,向回调函数返回查询到的文档(如果有的话)。如果传入了 callback 则查询会立即执行。

这个函数触发以下中间件

  • findOneAndUpdate()

支持的选项

  • new: bool - 如果设置为 true,不再返回旧文档而是更新后的文档。默认值 false(从 4.0 版本开始)
  • upsert: bool - 如果文档不存在则插入一条新数据。默认值 false
  • fields: {Object|String} - 选择字段。等效于 .select(fields).findOneAndUpdate()
  • sort: 如果查询条件匹配多条文档,可以设置排序条件以确定更新哪条文档(排序后的第一条)
  • maxTimeMS: 对查询设置时间限制 - 需要 mongodb 2.6.0 及以上版本
  • runValidators: 如果值为 true,更新操作执行时会做 update validators 。 Update validators 会依照 model 的 schema 对更新操作做校验。
  • setDefaultsOnInsert: 如果该选项和 upsert 都是 true, mongoose 会在插入新文档时应用 schema 中指定的 默认值。该选项只会在 MongoDB 2.4 版本及以上生效,因为它依赖 MongoDB 的 $setOnInsert 操作符。
  • rawResult: 如果值为 true,将返回 MongoDB 驱动的 原生结果(raw result)
  • context: string - if set to 'query' and runValidators is on, this will refer to the query in custom validator functions that update validation runs. Does nothing if runValidators is false.

回调函数签名

  1. function(error, doc) {
  2. // error: 发生错误时有值
  3. // doc: 如果 `new: false` 则为更新前的文档;如果 `new: true` 则为更新后的文档
  4. }

示例

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

Query .prototype.findOneAndRemove ()

Parameters
  • [conditions] «Object»
  • [options] «Object»
  • [options.rawResult] «Boolean» 如果值为 true,则返回 MongoDB 驱动的原生结果
  • [options.strict] «Boolean|String» 覆盖 schema 的 strict mode 选项
  • [callback] «Function» 可选 参数表是 (error, document)
Returns:
  • «Query» this

发起一条 mongodb findAndModify 删除指令。

查询一条匹配的文档,把它删掉,并回传给回调函数。如果有 callback 参数,删除指令会立即执行。

这个函数触发以下中间件

  • findOneAndRemove()

可选项

  • sort: 设置排序,如果多条文档匹配查询条件,将影响到实际更新哪条文档(只会更新第一条)
  • maxTimeMS: 对查询设置时间限制 - 需要 mongodb 2.6.0 及以上版本
  • rawResult: 如果设置为 true,返回结果将是 MongoDB 驱动的原生结果

回调函数签名

  1. function(error, doc) {
  2. // error: 可能爆出的错误
  3. // doc: 若 `new = false` 则是更新之前的文档,若 `new = true` 则是更新之后的文档
  4. }

示例

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

Query.prototype.update()

Parameters
  • [criteria] «Object»
  • [doc] «Object» the update command
  • [options] «Object»
  • [options.multipleCastError] «Boolean» 默认情况下,mongoose 只返回 query 转换中报的第一个错。激活该选项会聚合转换中所有的报错。
  • [callback] «Function» 可选,参数表是 (error, writeOpResult)
Returns:
  • «Query» this

声明且(/或)执行当前查询为 update() 操作。

被传入的路径中非原子($atomic)的操作,会以 $set 形式执行。

这个函数触发以下中间件

  • update()

示例

  1. Model.where({ _id: id }).update({ title: 'words' })
  2. // becomes
  3. Model.where({ _id: id }).update({ $set: { title: 'words' }})

可用选项:

  • safe (boolean) 安全模式(默认值同 schema 中的定义(true))
  • upsert (boolean) 没有匹配文档时是否创建新文档 (false)
  • multi (boolean) 是否更新多条文档 (false)
  • runValidators: 如果设为 true,这条命令将执行 update validators 。 Update validators 依据 schema 校验更新选项。
  • setDefaultsOnInsert: 如果该选项跟 upsert 都为 true,创建新文档时 mongoose 会应用 schema 中指定的 默认值 。 该选项只能用于 MongoDB >= 2.4 ,因为依赖于 MongoDB's $setOnInsert 操作符。
  • strict (boolean) 覆盖当前 update 的 strict 选项
  • overwrite (boolean) 禁用 update-only 模式,允许你替换整个文档 (false)
  • context (string) if set to 'query' and runValidators is on, this will refer to the query in custom validator functions that update validation runs. 如果 runValidators 是 false 则什么都不做。

注意

doc 参数被传入空对象 {} 会造成一次空操作,除非 overwrite 选项被激活。overwrite 选项没有激活的情况下,update 命令不会发送给 MongoDB 而被忽略,回调函数直接被调用,以防止数据集合的文档被意外覆盖。

注意

只有传入了回调函数,操作才会被执行。要想强制执行回调,你得先调用 update() 然后用 exec() 方法使其执行。

  1. var q = Model.where({ _id: id });
  2. q.update({ $set: { name: 'bob' }}).update(); // not executed
  3. q.update({ $set: { name: 'bob' }}).exec(); // executed
  4. // 非 $atomic ops 的键都会被转换成 $set。
  5. // 本句执行跟上例一样的命令。
  6. q.update({ name: 'bob' }).exec();
  7. // 用空文档替换更新
  8. var q = Model.where({ _id: id }).setOptions({ overwrite: true })
  9. q.update({ }, callback); // executes
  10. // 用空文档进行多条替换更新
  11. var q = Model.where({ _id: id });
  12. q.setOptions({ multi: true, overwrite: true })
  13. q.update({ });
  14. q.update(callback); // executed
  15. // 多条更新
  16. Model.where()
  17. .update({ name: /^match/ }, { $set: { arr: [] }}, { multi: true }, callback)
  18. // 再多一例多条更新
  19. Model.where()
  20. .setOptions({ multi: true })
  21. .update({ $set: { arr: [] }}, callback)
  22. // 默认是单条更新
  23. Model.where({ email: 'address@example.com' })
  24. .update({ $inc: { counter: 1 }}, callback)

API summary

  1. update(criteria, doc, options, cb) // executes
  2. update(criteria, doc, options)
  3. update(criteria, doc, cb) // executes
  4. update(criteria, doc)
  5. update(doc, cb) // executes
  6. update(doc)
  7. update(cb) // executes
  8. update(true) // executes
  9. update()

Query.prototype.updateMany()

Parameters
  • [criteria] «Object»
  • [doc] «Object» the update command
  • [options] «Object»
  • [options.multipleCastError] «Boolean» 默认情况下,mongoose 只返回 query 转换中报的第一个错。激活该选项会聚合转换中所有的报错。
  • [callback] «Function» 可选,参数表是 (error, writeOpResult)
Returns:
  • «Query» this

声明且(/或)执行当前查询为 updateMany() 操作。不同于 update() 的是, MongoDB 会忽略 multi 选项,更新 所有 匹配 criteria 的文档(而非只是第一条)。

注意 updateMany 不会 触发 update 中间件。可以用 pre('updateMany')post('updateMany') 代替。

这个函数触发以下中间件

  • updateMany()

Query.prototype.updateOne()

Parameters
  • [criteria] «Object»
  • [doc] «Object» the update command
  • [options] «Object»
  • [options.multipleCastError] «Boolean» 默认情况下,mongoose 只返回 query 转换中报的第一个错。激活该选项会聚合转换中所有的报错。
  • [callback] «Function» 参数表是(error, writeOpResult)
Returns:
  • «Query» this

声明且(/或)执行当前查询为 updateMany() 操作。不同于 update() 的是,MongoDB 会忽略 multi 选项, 更新第一条匹配 criteria 的文档。

注意 updateOne 不会 触发 update 中间件。可以用 pre('updateOne')post('updateOne') 代替。

这个函数触发以下中间件

  • updateOne()

Query.prototype.replaceOne()

Parameters
  • [criteria] «Object»
  • [doc] «Object» the update command
  • [options] «Object»
  • [callback] «Function» 可选 参数表是 (error, writeOpResult)
Returns:
  • «Query» this

声明且(/或)执行当前查询为 replaceOne() 操作。不同于 update() 的是,MongoDB 不接受原子操作符($set等)直接替换存在的文档。

注意 replaceOne 不会 触发 update 中间件。可以用 pre('replaceOne')post('replaceOne') 代替。

这个函数触发以下中间件

  • replaceOne()

Query.prototype.exec()

Parameters
  • [operation] «String|Function»
  • [callback] «Function» 可选 参数表取决于调用的函数
Returns:
  • «Promise »

执行查询

示例:

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

Query.prototype.then()

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

执行返回 Promise 的查询,成功返回 doc(s),失败返回 error


Query.prototype.catch()

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

执行返回 Promise 的查询,成功返回 doc(s),失败返回 error。 类似于 .then() 但是只接受失败句柄。


Query.prototype.populate()

Parameters
  • path «Object|String» 需要做表关联的字段路径,或者包含所有参数的对象
  • [select] «Object|String» 表关联查询要选择的字段
  • [model] «Model» 表关联的 model 。如果没有指定,将以 Schema 中 ref 字段为名称查找 model 进行关联。
  • [match] «Object» population 查询的条件
  • [options] «Object» population 查询的选项 (sort 等)
Returns:
  • «Query» this

指定哪些字段需要关联查询(populated)其他文档。

示例:

  1. Kitten.findOne().populate('owner').exec(function (err, kitten) {
  2. console.log(kitten.owner.name) // Max
  3. })
  4. Kitten.find().populate({
  5. path: 'owner'
  6. , select: 'name'
  7. , match: { color: 'black' }
  8. , options: { sort: { name: -1 }}
  9. }).exec(function (err, kittens) {
  10. console.log(kittens[0].owner.name) // Zoopa
  11. })
  12. // alternatively
  13. Kitten.find().populate('owner', 'name', null, {sort: { name: -1 }}).exec(function (err, kittens) {
  14. console.log(kittens[0].owner.name) // Zoopa
  15. })

字段的表关联在查询结束并收到响应之后执行。每个指定表关联的路径都由一个独立的查询执行。收到所有查询的响应之后,查询结果被传递给回调函数。


Query.prototype.cast()

Parameters
  • model «Model»
  • [obj] «Object»
Returns:
  • «Object »

Casts this query to the schema of model

注意

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


Query.prototype.cursor()

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

返回对 mongodb driver cursor 的封装。 QueryCursor 暴露了一个 Streams3 接口,和一个 .next() 函数。

.cursor() 函数触发 find 的前置钩子,但不会触发后置钩子。

示例

  1. // 有2种方式使用游标。第一种,流式:
  2. find({ name: /^hello/ }).
  3. cursor().
  4. on('data', function(doc) { console.log(doc); }).
  5. on('end', function() { console.log('Done!'); });
  6. // 或者使用 `.next()` 手动获取流中的下一个文档。
  7. // `.next()` 返回一个 promise,你可以用 promises 或者 callbacks.
  8. var cursor = Thing.find({ name: /^hello/ }).cursor();
  9. cursor.next(function(error, doc) {
  10. console.log(doc);
  11. });
  12. // 由于 `.next()` 返回一个 promise,你可以使用 co
  13. // 很容易地遍历所有文档而不用把它们都加载到内存里
  14. co(function*() {
  15. const cursor = Thing.find({ name: /^hello/ }).cursor();
  16. for (let doc = yield cursor.next(); doc != null; doc = yield cursor.next()) {
  17. console.log(doc);
  18. }
  19. });

可选项

  • transform: 可选 接收一个 mongoose document 参数的函数。函数的返回值会成为 data 事件的响应结果和 .next() 函数的返回值。

Query.prototype.maxscan ()

DEPRECATED Alias of maxScan


Query.prototype.tailable()

Parameters
  • bool «Boolean» 默认值 true
  • [opts] «Object» 要设置的选项
  • [opts.numberOfRetries] «Number» 游标用尽时,重试终止前的次数
  • [opts.tailableRetryInterval] «Number» 游标用尽时,重试之前等待的毫秒数

设置 tailable 选项 (capped collections 中会使用).

示例

  1. query.tailable() // true
  2. query.tailable(true)
  3. query.tailable(false)

注意

不能和 distinct() 一起使用


Query .prototype.intersects ()

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

Declares an intersects query for geometry().

示例

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

注意:

MUST be used after where().

注意:

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


Query .prototype.geometry ()

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

Specifies a $geometry condition

示例

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

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

注意:

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

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


Query .prototype.near ()

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

Specifies a $near or $nearSphere condition

These operators return documents sorted by distance.

示例

  1. query.where('loc').near({ center: [10, 10] });
  2. query.where('loc').near({ center: [10, 10], maxDistance: 5 });
  3. query.where('loc').near({ center: [10, 10], maxDistance: 5, spherical: true });
  4. query.near('loc', { center: [10, 10], maxDistance: 5 });

Query.prototype.nearSphere()

DEPRECATED Specifies a $nearSphere condition

示例

  1. query.where('loc').nearSphere({ center: [10, 10], maxDistance: 5 });

Deprecated. Use query.near() instead with the spherical option set to true.

示例

  1. query.where('loc').near({ center: [10, 10], spherical: true });

Query .prototype.polygon ()

Parameters
  • [path] «String|Array»
  • [coordinatePairs…] «Array|Object»
Returns:
  • «Query» this

Specifies a $polygon condition

示例

  1. query.where('loc').within().polygon([10,20], [13, 25], [7,15])
  2. query.polygon('loc', [10,20], [13, 25], [7,15])

Query .prototype.box ()

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

Specifies a $box condition

示例

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

Query .prototype.circle ()

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

Specifies a $center or $centerSphere condition.

示例

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

New in 3.7.0


Query .prototype.center ()

DEPRECATED Alias for circle

Deprecated. Use circle instead.


Query.prototype.centerSphere()

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

DEPRECATED Specifies a $centerSphere condition

Deprecated. Use circle instead.

示例

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

Query .prototype.selected ()

Returns:
  • «Boolean »

Determines if field selection has been made.


Query .prototype.selectedInclusively ()

Returns:
  • «Boolean »

Determines if inclusive field selection has been made.

  1. query.selectedInclusively() // false
  2. query.select('name')
  3. query.selectedInclusively() // true

Query .prototype.selectedExclusively ()

Returns:
  • «Boolean »

Determines if exclusive field selection has been made.

  1. query.selectedExclusively() // false
  2. query.select('-name')
  3. query.selectedExclusively() // true
  4. query.selectedInclusively() // false

Aggregate


Aggregate()

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

Aggregate constructor used for building aggregation pipelines. Do not instantiate this class directly, use Model.aggregate() instead.

Example:

  1. const aggregate = Model.aggregate([
  2. { $project: { a: 1, b: 1 } },
  3. { $skip: 5 }
  4. ]);
  5. Model.
  6. aggregate([{ $match: { age: { $gte: 21 }}}]).
  7. unwind('tags').
  8. exec(callback);

Note:

  • The documents returned are plain javascript objects, not mongoose documents (since any shape of document can be returned).
  • Mongoose does not cast pipeline stages. The below will not work unless _id is a string in the database
  1. new Aggregate([{ $match: { _id: '00000000000000000000000a' } }]);
  2. // Do this instead to cast to an ObjectId
  3. new Aggregate([{ $match: { _id: mongoose.Types.ObjectId('00000000000000000000000a') } }]);

Aggregate.prototype.model()

Parameters
  • model «Model» the model to which the aggregate is to be bound
Returns:
  • «Aggregate »

Binds this aggregate to a model.


Aggregate.prototype.append()

Parameters
  • ops «Object» operator(s) to append
Returns:
  • «Aggregate »

Appends new operators to this aggregate pipeline

Examples:

  1. aggregate.append({ $project: { field: 1 }}, { $limit: 2 });
  2. // or pass an array
  3. var pipeline = [{ $match: { daw: 'Logic Audio X' }} ];
  4. aggregate.append(pipeline);

Aggregate.prototype.addFields()

Parameters
  • arg «Object» field specification
Returns:
  • «Aggregate »

Appends a new $addFields operator to this aggregate pipeline. Requires MongoDB v3.4+ to work

Examples:

  1. // adding new fields based on existing fields
  2. aggregate.addFields({
  3. newField: '$b.nested'
  4. , plusTen: { $add: ['$val', 10]}
  5. , sub: {
  6. name: '$a'
  7. }
  8. })
  9. // etc
  10. aggregate.addFields({ salary_k: { $divide: [ "$salary", 1000 ] } });

Aggregate.prototype.project()

Parameters
  • arg «Object|String» field specification
Returns:
  • «Aggregate »

Appends a new $project operator to this aggregate pipeline.

Mongoose query selection syntax is also supported.

Examples:

  1. // include a, include b, exclude _id
  2. aggregate.project("a b -_id");
  3. // or you may use object notation, useful when
  4. // you have keys already prefixed with a "-"
  5. aggregate.project({a: 1, b: 1, _id: 0});
  6. // reshaping documents
  7. aggregate.project({
  8. newField: '$b.nested'
  9. , plusTen: { $add: ['$val', 10]}
  10. , sub: {
  11. name: '$a'
  12. }
  13. })
  14. // etc
  15. aggregate.project({ salary_k: { $divide: [ "$salary", 1000 ] } });

Aggregate .prototype.group ()

Parameters
  • arg «Object» $group operator contents
Returns:
  • «Aggregate »

Appends a new custom $group operator to this aggregate pipeline.

Examples:

  1. aggregate.group({ _id: "$department" });

Aggregate .prototype.match ()

Parameters
  • arg «Object» $match operator contents
Returns:
  • «Aggregate »

Appends a new custom $match operator to this aggregate pipeline.

Examples:

  1. aggregate.match({ department: { $in: [ "sales", "engineering" ] } });

Aggregate .prototype.skip ()

Parameters
  • num «Number» number of records to skip before next stage
Returns:
  • «Aggregate »

Appends a new $skip operator to this aggregate pipeline.

Examples:

  1. aggregate.skip(10);

Aggregate .prototype.limit ()

Parameters
  • num «Number» maximum number of records to pass to the next stage
Returns:
  • «Aggregate »

Appends a new $limit operator to this aggregate pipeline.

Examples:

  1. aggregate.limit(10);

Aggregate .prototype.near ()

Parameters
  • parameters «Object»
Returns:
  • «Aggregate »

Appends a new $geoNear operator to this aggregate pipeline.

NOTE:

MUST be used as the first operator in the pipeline.

Examples:

  1. aggregate.near({
  2. near: [40.724, -73.997],
  3. distanceField: "dist.calculated", // required
  4. maxDistance: 0.008,
  5. query: { type: "public" },
  6. includeLocs: "dist.location",
  7. uniqueDocs: true,
  8. num: 5
  9. });

Aggregate.prototype.unwind()

Parameters
  • fields «String» the field(s) to unwind
Returns:
  • «Aggregate »

Appends new custom $unwind operator(s) to this aggregate pipeline.

Note that the $unwind operator requires the path name to start with '$'. Mongoose will prepend '$' if the specified field doesn't start '$'.

Examples:

  1. aggregate.unwind("tags");
  2. aggregate.unwind("a", "b", "c");

Aggregate.prototype.replaceRoot()

Parameters
  • the «String» field which will become the new root document
Returns:
  • «Aggregate »

Appends a new $replaceRoot operator to this aggregate pipeline.

Note that the $replaceRoot operator requires the new root to start with '$'. Mongoose will prepend '$' if the specified field doesn't start '$'.

Examples:

  1. aggregate.replaceRoot("user");

Aggregate.prototype.count()

Parameters
  • the «String» name of the count field
Returns:
  • «Aggregate »

Appends a new $count operator to this aggregate pipeline.

Examples:

  1. aggregate.count("userCount");

Aggregate.prototype.sortByCount()

Parameters
  • arg «Object|String»
Returns:
  • «Aggregate» this

Appends a new $sortByCount operator to this aggregate pipeline. Accepts either a string field name or a pipeline object.

Note that the $sortByCount operator requires the new root to start with '$'. Mongoose will prepend '$' if the specified field name doesn't start with '$'.

Examples:

  1. aggregate.sortByCount('users');
  2. aggregate.sortByCount({ $mergeObjects: [ "$employee", "$business" ] })

Aggregate.prototype.lookup()

Parameters
  • options «Object» to $lookup as described in the above link
Returns:
  • «Aggregate »

Appends new custom $lookup operator(s) to this aggregate pipeline.

Examples:

  1. aggregate.lookup({ from: 'users', localField: 'userId', foreignField: '_id', as: 'users' });

Aggregate.prototype.graphLookup()

Parameters
  • options «Object» to $graphLookup as described in the above link
Returns:
  • «Aggregate »

Appends new custom $graphLookup operator(s) to this aggregate pipeline, performing a recursive search on a collection.

Note that graphLookup can only consume at most 100MB of memory, and does not allow disk use even if { allowDiskUse: true } is specified.

Examples:

  1. // Suppose we have a collection of courses, where a document might look like `{ _id: 0, name: 'Calculus', prerequisite: 'Trigonometry'}` and `{ _id: 0, name: 'Trigonometry', prerequisite: 'Algebra' }`
  2. aggregate.graphLookup({ from: 'courses', startWith: '$prerequisite', connectFromField: 'prerequisite', connectToField: 'name', as: 'prerequisites', maxDepth: 3 }) // this will recursively search the 'courses' collection up to 3 prerequisites

Aggregate.prototype.sample()

Parameters
  • size «Number» number of random documents to pick
Returns:
  • «Aggregate »

Appends new custom $sample operator(s) to this aggregate pipeline.

Examples:

  1. aggregate.sample(3); // Add a pipeline that picks 3 random documents

Aggregate.prototype.sort()

Parameters
  • arg «Object|String»
Returns:
  • «Aggregate» this

Appends a new $sort operator to this aggregate pipeline.

If an object is passed, values allowed are asc, desc, ascending, descending, 1, and -1.

If a string is passed, it must be a space delimited list of path names. The sort order of each path is ascending unless the path name is prefixed with - which will be treated as descending.

Examples:

  1. // these are equivalent
  2. aggregate.sort({ field: 'asc', test: -1 });
  3. aggregate.sort('field -test');

Aggregate.prototype.read()

Parameters
  • pref «String» one of the listed preference options or their aliases
  • [tags] «Array» optional tags for this query

Sets the readPreference option for the aggregation query.

Example:

  1. Model.aggregate(..).read('primaryPreferred').exec(callback)

Aggregate.prototype.explain()

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

Execute the aggregation with explain

Example:

  1. Model.aggregate(..).explain(callback)

Aggregate.prototype.allowDiskUse()

Parameters
  • value «Boolean» Should tell server it can use hard drive to store data during aggregation.
  • [tags] «Array» optional tags for this query

Sets the allowDiskUse option for the aggregation query (ignored for < 2.6.0)

Example:

  1. Model.aggregate(..).allowDiskUse(true).exec(callback)

Aggregate.prototype.hint()

Parameters
  • value «Object|String» a hint object or the index name

Sets the hint option for the aggregation query (ignored for < 3.6.0)

Example:

  1. Model.aggregate(..).hint({ qty: 1, category: 1 } }).exec(callback)

Aggregate.prototype.option()

Parameters
  • options «Object» keys to merge into current options
  • number «[options.maxTimeMS]» limits the time this aggregation will run, see MongoDB docs on maxTimeMS
  • 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()
Returns:
  • «Aggregate» this

Lets you set arbitrary options, for middleware or plugins.

Example:

  1. var agg = Model.aggregate(..).option({ allowDiskUse: true }); // Set the `allowDiskUse` option
  2. agg.options; // `{ allowDiskUse: true }`

Aggregate.prototype.cursor()

Parameters
  • options «Object»
  • options.batchSize «Number» set the cursor batch size
  • [options.useMongooseAggCursor] «Boolean» use experimental mongoose-specific aggregation cursor (for eachAsync() and other query cursor semantics)

Sets the cursor option option for the aggregation query (ignored for < 2.6.0). Note the different syntax below: .exec() returns a cursor object, and no callback is necessary.

Example:

  1. var cursor = Model.aggregate(..).cursor({ batchSize: 1000 }).exec();
  2. cursor.each(function(error, doc) {
  3. // use doc
  4. });

Aggregate.prototype.addCursorFlag()

Parameters
  • flag «String»
  • value «Boolean»

Adds a cursor flag

Example:

  1. Model.aggregate(..).addCursorFlag('noCursorTimeout', true).exec();

Aggregate.prototype.collation()

Parameters
  • collation «Object» options

Adds a collation

Example:

  1. Model.aggregate(..).collation({ locale: 'en_US', strength: 1 }).exec();

Aggregate.prototype.facet()

Parameters
  • facet «Object» options
Returns:
  • «Aggregate» this

Combines multiple aggregation pipelines.

Example:

  1. Model.aggregate(...)
  2. .facet({
  3. books: [{ groupBy: '$author' }],
  4. price: [{ $bucketAuto: { groupBy: '$price', buckets: 2 } }]
  5. })
  6. .exec();
  7. // Output: { books: [...], price: [{...}, {...}] }

Aggregate.prototype.pipeline()

Returns:
  • «Array »

Returns the current pipeline

Example:

  1. MyModel.aggregate().match({ test: 1 }).pipeline(); // [{ $match: { test: 1 } }]

Aggregate.prototype.exec()

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

Executes the aggregate pipeline on the currently bound Model.

Example:

  1. aggregate.exec(callback);
  2. // Because a promise is returned, the `callback` is optional.
  3. var promise = aggregate.exec();
  4. promise.then(..);

Aggregate.prototype.then()

Parameters
  • [resolve] «Function» successCallback
  • [reject] «Function» errorCallback
Returns:
  • «Promise»

Provides promise for aggregate.

Example:

  1. Model.aggregate(..).then(successCallback, errorCallback);

Schematype


SchemaType()

Parameters
  • path «String»
  • [options] «Object»
  • [instance] «String»

SchemaType constructor. Do not instantiate SchemaType directly. Mongoose converts your schema paths into SchemaTypes automatically.

Example:

  1. const schema = new Schema({ name: String });
  2. schema.path('name') instanceof SchemaType; // true

SchemaType.prototype.default()

Parameters
  • val «Function|any» the default value
Returns:
  • «defaultValue »

Sets a default value for this SchemaType.

Example:

  1. var schema = new Schema({ n: { type: Number, default: 10 })
  2. var M = db.model('M', schema)
  3. var m = new M;
  4. console.log(m.n) // 10

Defaults can be either functions which return the value to use as the default or the literal value itself. Either way, the value will be cast based on its schema type before being set during document creation.

Example:

  1. // values are cast:
  2. var schema = new Schema({ aNumber: { type: Number, default: 4.815162342 }})
  3. var M = db.model('M', schema)
  4. var m = new M;
  5. console.log(m.aNumber) // 4.815162342
  6. // default unique objects for Mixed types:
  7. var schema = new Schema({ mixed: Schema.Types.Mixed });
  8. schema.path('mixed').default(function () {
  9. return {};
  10. });
  11. // if we don't use a function to return object literals for Mixed defaults,
  12. // each document will receive a reference to the same object literal creating
  13. // a "shared" object instance:
  14. var schema = new Schema({ mixed: Schema.Types.Mixed });
  15. schema.path('mixed').default({});
  16. var M = db.model('M', schema);
  17. var m1 = new M;
  18. m1.mixed.added = 1;
  19. console.log(m1.mixed); // { added: 1 }
  20. var m2 = new M;
  21. console.log(m2.mixed); // { added: 1 }

SchemaType.prototype.index()

Parameters
  • options «Object|Boolean|String»
Returns:
  • «SchemaType» this

Declares the index options for this schematype.

Example:

  1. var s = new Schema({ name: { type: String, index: true })
  2. var s = new Schema({ loc: { type: [Number], index: 'hashed' })
  3. var s = new Schema({ loc: { type: [Number], index: '2d', sparse: true })
  4. var s = new Schema({ loc: { type: [Number], index: { type: '2dsphere', sparse: true }})
  5. var s = new Schema({ date: { type: Date, index: { unique: true, expires: '1d' }})
  6. Schema.path('my.path').index(true);
  7. Schema.path('my.date').index({ expires: 60 });
  8. Schema.path('my.path').index({ unique: true, sparse: true });

NOTE:

Indexes are created in the background by default. Specify background: false to override.

Direction doesn't matter for single key indexes


SchemaType.prototype.unique()

Parameters
  • bool «Boolean»
Returns:
  • «SchemaType» this

Declares an unique index.

Example:

  1. var s = new Schema({ name: { type: String, unique: true }});
  2. Schema.path('name').index({ unique: true });

NOTE: violating the constraint returns an E11000 error from MongoDB when saving, not a Mongoose validation error.


SchemaType.prototype.text()

Parameters
  • bool «Boolean»
Returns:
  • «SchemaType» this

Declares a full text index.

Example:

  1. var s = new Schema({name : {type: String, text : true })
  2. Schema.path('name').index({text : true});

SchemaType.prototype.sparse()

Parameters
  • bool «Boolean»
Returns:
  • «SchemaType» this

Declares a sparse index.

Example:

  1. var s = new Schema({ name: { type: String, sparse: true })
  2. Schema.path('name').index({ sparse: true });

SchemaType.prototype.set()

Parameters
  • fn «Function»
Returns:
  • «SchemaType» this

Adds a setter to this schematype.

Example:

  1. function capitalize (val) {
  2. if (typeof val !== 'string') val = '';
  3. return val.charAt(0).toUpperCase() + val.substring(1);
  4. }
  5. // defining within the schema
  6. var s = new Schema({ name: { type: String, set: capitalize }});
  7. // or with the SchemaType
  8. var s = new Schema({ name: String })
  9. s.path('name').set(capitalize);

Setters allow you to transform the data before it gets to the raw mongodb document or query.

Suppose you are implementing user registration for a website. Users provide an email and password, which gets saved to mongodb. The email is a string that you will want to normalize to lower case, in order to avoid one email having more than one account — e.g., otherwise, avenue@q.com can be registered for 2 accounts via avenue@q.com and AvEnUe@Q.CoM.

You can set up email lower case normalization easily via a Mongoose setter.

  1. function toLower(v) {
  2. return v.toLowerCase();
  3. }
  4. var UserSchema = new Schema({
  5. email: { type: String, set: toLower }
  6. });
  7. var User = db.model('User', UserSchema);
  8. var user = new User({email: 'AVENUE@Q.COM'});
  9. console.log(user.email); // 'avenue@q.com'
  10. // or
  11. var user = new User();
  12. user.email = 'Avenue@Q.com';
  13. console.log(user.email); // 'avenue@q.com'
  14. User.updateOne({ _id: _id }, { $set: { email: 'AVENUE@Q.COM' } }); // update to 'avenue@q.com'

As you can see above, setters allow you to transform the data before it stored in MongoDB, or before executing a query.

NOTE: we could have also just used the built-in lowercase: true SchemaType option instead of defining our own function.

  1. new Schema({ email: { type: String, lowercase: true }})

Setters are also passed a second argument, the schematype on which the setter was defined. This allows for tailored behavior based on options passed in the schema.

  1. function inspector (val, schematype) {
  2. if (schematype.options.required) {
  3. return schematype.path + ' is required';
  4. } else {
  5. return val;
  6. }
  7. }
  8. var VirusSchema = new Schema({
  9. name: { type: String, required: true, set: inspector },
  10. taxonomy: { type: String, set: inspector }
  11. })
  12. var Virus = db.model('Virus', VirusSchema);
  13. var v = new Virus({ name: 'Parvoviridae', taxonomy: 'Parvovirinae' });
  14. console.log(v.name); // name is required
  15. console.log(v.taxonomy); // Parvovirinae

You can also use setters to modify other properties on the document. If you're setting a property name on a document, the setter will run with this as the document. Be careful, in mongoose 5 setters will also run when querying by name with this as the query.

  1. const nameSchema = new Schema({ name: String, keywords: [String] });
  2. nameSchema.path('name').set(function(v) {
  3. // Need to check if `this` is a document, because in mongoose 5
  4. // setters will also run on queries, in which case `this` will be a
  5. // mongoose query object.
  6. if (this instanceof Document && v != null) {
  7. this.keywords = v.split(' ');
  8. }
  9. return v;
  10. });

SchemaType.prototype.get()

Parameters
  • fn «Function»
Returns:
  • «SchemaType» this

Adds a getter to this schematype.

Example:

  1. function dob (val) {
  2. if (!val) return val;
  3. return (val.getMonth() + 1) + "/" + val.getDate() + "/" + val.getFullYear();
  4. }
  5. // defining within the schema
  6. var s = new Schema({ born: { type: Date, get: dob })
  7. // or by retreiving its SchemaType
  8. var s = new Schema({ born: Date })
  9. s.path('born').get(dob)

Getters allow you to transform the representation of the data as it travels from the raw mongodb document to the value that you see.

Suppose you are storing credit card numbers and you want to hide everything except the last 4 digits to the mongoose user. You can do so by defining a getter in the following way:

  1. function obfuscate (cc) {
  2. return '****-****-****-' + cc.slice(cc.length-4, cc.length);
  3. }
  4. var AccountSchema = new Schema({
  5. creditCardNumber: { type: String, get: obfuscate }
  6. });
  7. var Account = db.model('Account', AccountSchema);
  8. Account.findById(id, function (err, found) {
  9. console.log(found.creditCardNumber); // '****-****-****-1234'
  10. });

Getters are also passed a second argument, the schematype on which the getter was defined. This allows for tailored behavior based on options passed in the schema.

  1. function inspector (val, schematype) {
  2. if (schematype.options.required) {
  3. return schematype.path + ' is required';
  4. } else {
  5. return schematype.path + ' is not';
  6. }
  7. }
  8. var VirusSchema = new Schema({
  9. name: { type: String, required: true, get: inspector },
  10. taxonomy: { type: String, get: inspector }
  11. })
  12. var Virus = db.model('Virus', VirusSchema);
  13. Virus.findById(id, function (err, virus) {
  14. console.log(virus.name); // name is required
  15. console.log(virus.taxonomy); // taxonomy is not
  16. })

SchemaType.prototype.validate()

Parameters
  • obj «RegExp|Function|Object» validator
  • [errorMsg] «String» optional error message
  • [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 means validation failed.

The error message argument is optional. If not passed, the default generic error message template will be used.

Examples:

  1. // make sure every value is equal to "something"
  2. function validator (val) {
  3. return val == 'something';
  4. }
  5. new Schema({ name: { type: String, validate: validator }});
  6. // with a custom error message
  7. var custom = [validator, 'Uh oh, {PATH} does not equal "something".']
  8. new Schema({ name: { type: String, validate: custom }});
  9. // adding many validators at a time
  10. var many = [
  11. { validator: validator, msg: 'uh oh' }
  12. , { validator: anotherValidator, msg: 'failed' }
  13. ]
  14. new Schema({ name: { type: String, validate: many }});
  15. // or utilizing SchemaType methods directly:
  16. var schema = new Schema({ name: 'string' });
  17. schema.path('name').validate(validator, 'validation of `{PATH}` failed with value `{VALUE}`');

Error message templates:

From the examples above, you may have noticed that error messages support basic templating. There are a few other template keywords besides {PATH} and {VALUE} too. To find out more, details are available here

Asynchronous validation:

Passing a validator function that receives two arguments tells mongoose that the validator is an asynchronous validator. The first argument passed to the validator function is the value being validated. The second argument is a callback function that must called when you finish validating the value and passed either true or false to communicate either success or failure respectively.

  1. schema.path('name').validate({
  2. isAsync: true,
  3. validator: function (value, respond) {
  4. doStuff(value, function () {
  5. ...
  6. respond(false); // validation failed
  7. });
  8. },
  9. message: 'Custom error message!' // Optional
  10. });
  11. // Can also return a promise
  12. schema.path('name').validate({
  13. validator: function (value) {
  14. return new Promise(function (resolve, reject) {
  15. resolve(false); // validation failed
  16. });
  17. }
  18. });

You might use asynchronous validators to retreive other documents from the database to validate against or to meet other I/O bound validation needs.

Validation occurs pre('save') or whenever you manually execute document#validate.

If validation fails during pre('save') and no callback was passed to receive the error, an error event will be emitted on your Models associated db connection, passing the validation error object along.

  1. var conn = mongoose.createConnection(..);
  2. conn.on('error', handleError);
  3. var Product = conn.model('Product', yourSchema);
  4. var dvd = new Product(..);
  5. dvd.save(); // emits error on the `conn` above

If you desire handling these errors at the Model level, attach an error listener to your Model and the event will instead be emitted there.

  1. // registering an error listener on the Model lets us handle errors more locally
  2. Product.on('error', handleError);

SchemaType.prototype.required()

Parameters
  • required «Boolean|Function|Object» enable/disable the validator, or function that returns required boolean, or options object
  • [options.isRequired] «Boolean|Function» enable/disable the validator, or function that returns required boolean
  • [options.ErrorConstructor] «Function» custom error constructor. The constructor receives 1 parameter, an object containing the validator properties.
  • [message] «String» optional custom error message
Returns:
  • «SchemaType» this

Adds a required validator to this SchemaType. The validator gets added to the front of this SchemaType's validators array using unshift().

Example:

  1. var s = new Schema({ born: { type: Date, required: true })
  2. // or with custom error message
  3. var s = new Schema({ born: { type: Date, required: '{PATH} is required!' })
  4. // or with a function
  5. var s = new Schema({
  6. userId: ObjectId,
  7. username: {
  8. type: String,
  9. required: function() { return this.userId != null; }
  10. }
  11. })
  12. // or with a function and a custom message
  13. var s = new Schema({
  14. userId: ObjectId,
  15. username: {
  16. type: String,
  17. required: [
  18. function() { return this.userId != null; },
  19. 'username is required if id is specified'
  20. ]
  21. }
  22. })
  23. // or through the path API
  24. Schema.path('name').required(true);
  25. // with custom error messaging
  26. Schema.path('name').required(true, 'grrr :( ');
  27. // or make a path conditionally required based on a function
  28. var isOver18 = function() { return this.age >= 18; };
  29. Schema.path('voterRegistrationId').required(isOver18);

The required validator uses the SchemaType's checkRequired function to determine whether a given value satisfies the required validator. By default, a value satisfies the required validator if val != null (that is, if the value is not null nor undefined). However, most built-in mongoose schema types override the default checkRequired function:


SchemaType.prototype.select()

Parameters
  • val «Boolean»
Returns:
  • «SchemaType» this

Sets default select() behavior for this path.

Set to true if this path should always be included in the results, false if it should be excluded by default. This setting can be overridden at the query level.

Example:

  1. T = db.model('T', new Schema({ x: { type: String, select: true }}));
  2. T.find(..); // field x will always be selected ..
  3. // .. unless overridden;
  4. T.find().select('-x').exec(callback);

Virtualtype


VirtualType()

VirtualType constructor

This is what mongoose uses to define virtual attributes via Schema.prototype.virtual.

Example:

  1. var fullname = schema.virtual('fullname');
  2. fullname instanceof mongoose.VirtualType // true

VirtualType.prototype.get()

Parameters
  • fn «Function»
Returns:
  • «VirtualType» this

Defines a getter.

Example:

  1. var virtual = schema.virtual('fullname');
  2. virtual.get(function () {
  3. return this.name.first + ' ' + this.name.last;
  4. });

VirtualType.prototype.set()

Parameters
  • fn «Function»
Returns:
  • «VirtualType» this

Defines a setter.

Example:

  1. var virtual = schema.virtual('fullname');
  2. virtual.set(function (v) {
  3. var parts = v.split(' ');
  4. this.name.first = parts[0];
  5. this.name.last = parts[1];
  6. });

VirtualType.prototype.applyGetters()

Parameters
  • value «Object»
  • scope «Object»
Returns:
  • «any» the value after applying all getters

Applies getters to value using optional scope.


VirtualType.prototype.applySetters()

Parameters
  • value «Object»
  • scope «Object»
Returns:
  • «any» the value after applying all setters

Applies setters to value using optional scope.


Error


MongooseError()

Parameters
  • msg «String» Error message

MongooseError constructor


MongooseError.messages

The default built-in validator error messages.


MongooseError.DocumentNotFoundError

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.


MongooseError.CastError

An instance of this error class will be returned when mongoose failed to cast a value.


MongooseError.ValidationError

An instance of this error class will be returned when validation failed.


MongooseError.ValidatorError

A ValidationError has a hash of errors that contain individual ValidatorError instances


MongooseError.VersionError

An instance of this error class will be returned when you call save() after the document in the database was changed in a potentially unsafe way. See the versionKey option for more information.


MongooseError.OverwriteModelError

Thrown when a model with the given name was already registered on the connection. See the FAQ about OverwriteModelError.


MongooseError.MissingSchemaError

Thrown when you try to access a model that has not been registered yet


MongooseError.DivergentArrayError

An instance of this error will be returned if you used an array projection and then modified the array in an unsafe way.