private

  • index.js

    Mongoose#_applyPlugins(schema)

    Applies global plugins to schema.

    Parameters:

    show code

    1. Mongoose.prototype._applyPlugins = function(schema) {
    2. if (schema.$globalPluginsApplied) {
    3. return;
    4. }
    5. var i;
    6. var len;
    7. for (i = 0, len = this.plugins.length; i < len; ++i) {
    8. schema.plugin(this.plugins[i][0], this.plugins[i][1]);
    9. }
    10. schema.$globalPluginsApplied = true;
    11. for (i = 0, len = schema.childSchemas.length; i < len; ++i) {
    12. this._applyPlugins(schema.childSchemas[i].schema);
    13. }
    14. };
    15. Mongoose.prototype._applyPlugins.$hasSideEffects = true;

    Mongoose#Aggregate()

    The Mongoose Aggregate constructor


    Mongoose#CastError(type, value, path, [reason])

    The Mongoose CastError constructor

    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

    MongooseThenable#catch(onFulfilled, onRejected)

    Ability to use mongoose object as a pseudo-promise so .connect().then()
    and .disconnect().then() are viable.

    Parameters:

    Returns:

    show code

    1. MongooseThenable.prototype.catch = function(onRejected) {
    2. return this.then(null, onRejected);
    3. };

    checkReplicaSetInUri(uri)

    Checks if ?replicaSet query parameter is specified in URI

    Parameters:

    Returns:

    Example:

    1. checkReplicaSetInUri('localhost:27000?replicaSet=rs0'); // true

    show code

    1. var checkReplicaSetInUri = function(uri) {
    2. if (!uri) {
    3. return false;
    4. }
    5. var queryStringStart = uri.indexOf('?');
    6. var isReplicaSet = false;
    7. if (queryStringStart !== -1) {
    8. try {
    9. var obj = querystring.parse(uri.substr(queryStringStart + 1));
    10. if (obj && obj.replicaSet) {
    11. isReplicaSet = true;
    12. }
    13. } catch (e) {
    14. return false;
    15. }
    16. }
    17. return isReplicaSet;
    18. };

    Mongoose#Collection()

    The Mongoose Collection constructor


    Mongoose#connect(uri(s), [options], [options.useMongoClient], [callback])

    Opens the default mongoose connection.

    Parameters:

    • uri(s) <String>
    • [options] <Object>
    • [options.useMongoClient] <Boolean> false by default, set to true to use new mongoose connection logic
    • [callback] <Function>

    Returns:

    See:

    If arguments are passed, they are proxied to either
    Connection#open or
    Connection#openSet appropriately.

    Options passed take precedence over options included in connection strings.

    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. // connecting to multiple mongos
    8. var uri = 'mongodb://hostA:27501,hostB:27501';
    9. var opts = { mongos: true };
    10. mongoose.connect(uri, opts);
    11. // optional callback that gets fired when initial connection completed
    12. var uri = 'mongodb://nonexistent.domain:27000';
    13. mongoose.connect(uri, function(error) {
    14. // if error is truthy, the initial connection failed.
    15. })

    show code

    1. Mongoose.prototype.connect = function() {
    2. var conn = this.connection;
    3. if ((arguments.length === 2 || arguments.length === 3) &&
    4. typeof arguments[0] === 'string' &&
    5. typeof arguments[1] === 'object' &&
    6. arguments[1].useMongoClient === true) {
    7. return conn.openUri(arguments[0], arguments[1], arguments[2]);
    8. }
    9. if (rgxReplSet.test(arguments[0]) || checkReplicaSetInUri(arguments[0])) {
    10. return new MongooseThenable(this, conn.openSet.apply(conn, arguments));
    11. }
    12. return new MongooseThenable(this, conn.open.apply(conn, arguments));
    13. };
    14. Mongoose.prototype.connect.$hasSideEffects = true;

    Mongoose#Connection()

    The Mongoose Connection constructor


    Mongoose#createConnection([uri], [options], [options.config], [options.config.autoIndex], [options.useMongoClient])

    Creates a Connection instance.

    Parameters:

    • [uri] <String> a mongodb:// URI
    • [options] <Object> options to pass to the driver
    • [options.config] <Object> mongoose-specific options
    • [options.config.autoIndex] <Boolean> set to false to disable automatic index creation for all models associated with this connection.
    • [options.useMongoClient] <Boolean> false by default, set to true to use new mongoose connection logic

    Returns:

    • <Connection, Promise> the created Connection object, or promise that resolves to the connection if `useMongoClient` option specified.

    See:

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

    show code

    1. Mongoose.prototype.createConnection = function(uri, options, callback) {
    2. var conn = new Connection(this);
    3. this.connections.push(conn);
    4. var rsOption = options && (options.replset || options.replSet);
    5. if (options && options.useMongoClient) {
    6. return conn.openUri(uri, options, callback);
    7. }
    8. if (arguments.length) {
    9. if (rgxReplSet.test(arguments[0]) || checkReplicaSetInUri(arguments[0])) {
    10. conn._openSetWithoutPromise.apply(conn, arguments);
    11. } else if (rsOption &&
    12. (rsOption.replicaSet || rsOption.rs_name)) {
    13. conn._openSetWithoutPromise.apply(conn, arguments);
    14. } else {
    15. conn._openWithoutPromise.apply(conn, arguments);
    16. }
    17. }
    18. return conn;
    19. };
    20. Mongoose.prototype.createConnection.$hasSideEffects = true;

    Mongoose#disconnect([fn])

    Disconnects all connections.

    Parameters:

    • [fn] <Function> called after all connection close.

    Returns:

    show code

    1. Mongoose.prototype.disconnect = function(fn) {
    2. var _this = this;
    3. var Promise = PromiseProvider.get();
    4. return new MongooseThenable(this, new Promise.ES6(function(resolve, reject) {
    5. var remaining = _this.connections.length;
    6. if (remaining <= 0) {
    7. fn && fn();
    8. resolve();
    9. return;
    10. }
    11. _this.connections.forEach(function(conn) {
    12. conn.close(function(error) {
    13. if (error) {
    14. fn && fn(error);
    15. reject(error);
    16. return;
    17. }
    18. if (!--remaining) {
    19. fn && fn();
    20. resolve();
    21. }
    22. });
    23. });
    24. }));
    25. };
    26. Mongoose.prototype.disconnect.$hasSideEffects = true;

    Mongoose#Document()

    The Mongoose Document constructor.


    Mongoose#DocumentProvider()

    The Mongoose DocumentProvider constructor.


    Mongoose#Error()

    The MongooseError constructor.


    Mongoose#get(key)

    Gets mongoose options

    Parameters:

    Example:

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

    Mongoose#getPromiseConstructor()

    Returns the current ES6-style promise constructor. In Mongoose 4.x,
    equivalent to mongoose.Promise.ES6, but will change once we get rid
    of the .ES6 bit.


    Mongoose#model(name, [schema], [collection], [skipInit])

    Defines a model or retrieves it.

    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)

    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 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 = mongoose.model('Actor', schema, collectionName)

    show code

    ``` Mongoose.prototype.model = function(name, schema, collection, skipInit) { var model; if (typeof name === ‘function’) {

    1. model = name;
    2. name = model.name;
    3. if (!(model.prototype instanceof Model)) {
    4. throw new mongoose.Error('The provided class ' + name + ' must extend Model');
    5. }

    }

    if (typeof schema === ‘string’) {

    1. collection = schema;
    2. schema = false;

    }

    if (utils.isObject(schema) && !(schema.instanceOfSchema)) {

    1. schema = new Schema(schema);

    } if (schema && !schema.instanceOfSchema) {

    1. throw new Error('The 2nd parameter to `mongoose.model()` should be a ' +
    2. 'schema or a POJO');

    }

    if (typeof collection === ‘boolean’) {

    1. skipInit = collection;
    2. collection = null;

    }

    // handle internal options from connection.model() var options; if (skipInit && utils.isObject(skipInit)) {

    1. options = skipInit;
    2. skipInit = true;

    } else {

    1. options = {};

    }

    // look up schema for the collection. if (!this.modelSchemas[name]) {

    1. if (schema) {
    2. // cache it so we only apply plugins once
    3. this.modelSchemas[name] = schema;
    4. } else {
    5. throw new mongoose.Error.MissingSchemaError(name);
    6. }

    }

    if (schema) {

    1. this._applyPlugins(schema);

    }

    var sub;

    // connection.model() may be passing a different schema for // an existing model name. in this case don’t read from cache. if (this.models[name] && options.cache !== false) {

    1. if (schema && schema.instanceOfSchema && schema !== this.models[name].schema) {
    2. throw new mongoose.Error.OverwriteModelError(name);
    3. }
    4. if (collection) {
    5. // subclass current model with alternate collection
    6. model = this.models[name];
    7. schema = model.prototype.schema;
    8. sub = model.__subclass(this.connection, schema, collection);
    9. // do not cache the sub model
    10. return sub;
    11. }
    12. return this.models[name];

    }

    // ensure a schema exists if (!schema) {

    1. schema = this.modelSchemas[name];
    2. if (!schema) {
    3. throw new mongoose.Error.MissingSchemaError(name);
    4. }

    }

    // Apply relevant “global” options to the schema if (!(‘pluralization’ in schema.options)) schema.options.pluralization = this.options.pluralization;

  1. if (!collection) {
  2. collection = schema.get('collection') || format(name, schema.options);
  3. }
  4. var connection = options.connection || this.connection;
  5. model = this.Model.compile(model || name, schema, collection, connection, this);
  6. if (!skipInit) {
  7. model.init();
  8. }
  9. if (options.cache === false) {
  10. return model;
  11. }
  12. this.models[name] = model;
  13. return this.models[name];
  14. };
  15. Mongoose.prototype.model.$hasSideEffects = true;
  16. ```
  17. ---
  18. ### [Mongoose#Model()](#index_Mongoose-Model)
  19. The Mongoose [Model](#model_Model) constructor.
  20. ---
  21. ### [Mongoose#modelNames()](#index_Mongoose-modelNames)
  22. Returns an array of model names created on this instance of Mongoose.
  23. #### Returns:
  24. - &lt;[Array](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array)&gt;
  25. #### Note:
  26. *Does not include names of models created using `connection.model()`.*
  27. show code
  28. ```
  29. Mongoose.prototype.modelNames = function() {
  30. var names = Object.keys(this.models);
  31. return names;
  32. };
  33. Mongoose.prototype.modelNames.$hasSideEffects = true;
  34. ```
  35. ---
  36. ### [Mongoose()](#index_Mongoose)
  37. Mongoose constructor.
  38. The exports object of the `mongoose` module is an instance of this class.
  39. Most apps will only use this one instance.
  40. show code
  41. ```
  42. function Mongoose() {
  43. this.connections = [];
  44. this.models = {};
  45. this.modelSchemas = {};
  46. // default global options
  47. this.options = {
  48. pluralization: true
  49. };
  50. var conn = this.createConnection(); // default connection
  51. conn.models = this.models;
  52. Object.defineProperty(this, 'plugins', {
  53. configurable: false,
  54. enumerable: true,
  55. writable: false,
  56. value: [
  57. [saveSubdocs, { deduplicate: true }],
  58. [validateBeforeSave, { deduplicate: true }],
  59. [shardingPlugin, { deduplicate: true }]
  60. ]
  61. });
  62. }
  63. ```
  64. ---
  65. ### [Mongoose#Mongoose()](#index_Mongoose-Mongoose)
  66. The Mongoose constructor
  67. The exports of the mongoose module is an instance of this class.
  68. #### Example:
  69. ```
  70. var mongoose = require('mongoose');
  71. var mongoose2 = new mongoose.Mongoose();
  72. ```
  73. ---
  74. ### [MongooseThenable()](#index_MongooseThenable)
  75. Wraps the given Mongoose instance into a thenable (pseudo-promise). This
  76. is so `connect()` and `disconnect()` can return a thenable while maintaining
  77. backwards compatibility.
  78. show code
  79. ```
  80. function MongooseThenable(mongoose, promise) {
  81. var _this = this;
  82. for (var key in mongoose) {
  83. if (typeof mongoose[key] === 'function' && mongoose[key].$hasSideEffects) {
  84. (function(key) {
  85. _this[key] = function() {
  86. return mongoose[key].apply(mongoose, arguments);
  87. };
  88. })(key);
  89. } else if (['connection', 'connections'].indexOf(key) !== -1) {
  90. _this[key] = mongoose[key];
  91. }
  92. }
  93. this.$opPromise = promise;
  94. }
  95. MongooseThenable.prototype = new Mongoose;
  96. ```
  97. ---
  98. ### [Mongoose#plugin(`fn`, `[opts]`)](#index_Mongoose-plugin)
  99. Declares a global plugin executed on all Schemas.
  100. #### Parameters:
  101. - `fn` &lt;[Function](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function)&gt; plugin callback
  102. - `[opts]` &lt;[Object](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object)&gt; optional options
  103. #### Returns:
  104. - &lt;[Mongoose](#index_Mongoose)&gt; this
  105. #### See:
  106. - [plugins]($eb672f4e0179b36b.md "plugins")
  107. Equivalent to calling `.plugin(fn)` on each Schema you create.
  108. show code
  109. ```
  110. Mongoose.prototype.plugin = function(fn, opts) {
  111. this.plugins.push([fn, opts]);
  112. return this;
  113. };
  114. Mongoose.prototype.plugin.$hasSideEffects = true;
  115. ```
  116. ---
  117. ### [function Object() { \[native code\] }#Promise()](#index_function%20Object()%20%7B%20%5Bnative%20code%5D%20%7D-Promise)
  118. The Mongoose [Promise](#promise_Promise) constructor.
  119. ---
  120. ### [Mongoose#PromiseProvider()](#index_Mongoose-PromiseProvider)
  121. Storage layer for mongoose promises
  122. ---
  123. ### [Mongoose#Query()](#index_Mongoose-Query)
  124. The Mongoose [Query](#query_Query) constructor.
  125. ---
  126. ### [Mongoose#Schema()](#index_Mongoose-Schema)
  127. The Mongoose [Schema](#schema_Schema) constructor
  128. #### Example:
  129. ```
  130. var mongoose = require('mongoose');
  131. var Schema = mongoose.Schema;
  132. var CatSchema = new Schema(..);
  133. ```
  134. ---
  135. ### [Mongoose#SchemaType()](#index_Mongoose-SchemaType)
  136. The Mongoose [SchemaType](#schematype_SchemaType) constructor
  137. ---
  138. ### [Mongoose#set(`key`, `value`)](#index_Mongoose-set)
  139. Sets mongoose options
  140. #### Parameters:
  141. - `key` &lt;[String](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String)&gt;
  142. - `value` &lt;[String](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String), [Function](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function), [Boolean](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Boolean)&gt;
  143. #### Example:
  144. ```
  145. mongoose.set('test', value) // sets the 'test' option to `value`
  146. mongoose.set('debug', true) // enable logging collection methods + arguments to the console
  147. mongoose.set('debug', function(collectionName, methodName, arg1, arg2...) {}); // use custom function to log collection methods + arguments
  148. ```
  149. show code
  150. ```
  151. Mongoose.prototype.set = function(key, value) {
  152. if (arguments.length === 1) {
  153. return this.options[key];
  154. }
  155. this.options[key] = value;
  156. return this;
  157. };
  158. Mongoose.prototype.set.$hasSideEffects = true;
  159. ```
  160. ---
  161. ### [()](#index_)
  162. Expose connection states for user-land
  163. show code
  164. ```
  165. Mongoose.prototype.STATES = STATES;
  166. ```
  167. ---
  168. ### [MongooseThenable#then(`onFulfilled`, `onRejected`)](#index_MongooseThenable-then)
  169. Ability to use mongoose object as a pseudo-promise so `.connect().then()`
  170. and `.disconnect().then()` are viable.
  171. #### Parameters:
  172. - `onFulfilled` &lt;[Function](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function)&gt;
  173. - `onRejected` &lt;[Function](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function)&gt;
  174. #### Returns:
  175. - &lt;[Promise](#promise_Promise)&gt;
  176. show code
  177. ```
  178. MongooseThenable.prototype.then = function(onFulfilled, onRejected) {
  179. var Promise = PromiseProvider.get();
  180. if (!this.$opPromise) {
  181. return new Promise.ES6(function(resolve, reject) {
  182. reject(new Error('Can only call `.then()` if connect() or disconnect() ' +
  183. 'has been called'));
  184. }).then(onFulfilled, onRejected);
  185. }
  186. this.$opPromise.$hasHandler = true;
  187. return this.$opPromise.then(onFulfilled, onRejected);
  188. };
  189. ```
  190. ---
  191. ### [Mongoose#VirtualType()](#index_Mongoose-VirtualType)
  192. The Mongoose [VirtualType](#virtualtype_VirtualType) constructor
  193. ---
  194. ### [Mongoose#connection](#index_Mongoose-connection)
  195. The default connection of the mongoose module.
  196. #### Example:
  197. ```
  198. var mongoose = require('mongoose');
  199. mongoose.connect(...);
  200. mongoose.connection.on('error', cb);
  201. ```
  202. This is the connection used by default for every model created using [mongoose.model](#index_Mongoose-model).
  203. show code
  204. ```
  205. Mongoose.prototype.__defineGetter__('connection', function() {
  206. return this.connections[0];
  207. });
  208. Mongoose.prototype.__defineSetter__('connection', function(v) {
  209. if (v instanceof Connection) {
  210. this.connections[0] = v;
  211. this.models = v.models;
  212. }
  213. });
  214. ```
  215. #### Returns:
  216. - &lt;[Connection](#connection_Connection)&gt;
  217. ---
  218. ### [Mongoose#mongo](#index_Mongoose-mongo)
  219. The [node-mongodb-native](https://github.com/mongodb/node-mongodb-native) driver Mongoose uses.
  220. show code
  221. ```
  222. Mongoose.prototype.mongo = require('mongodb');
  223. ```
  224. ---
  225. ### [Mongoose#mquery](#index_Mongoose-mquery)
  226. The [mquery](https://github.com/aheckmann/mquery) query builder Mongoose uses.
  227. show code
  228. ```
  229. Mongoose.prototype.mquery = require('mquery');
  230. ```
  231. ---
  232. ### [Mongoose#SchemaTypes](#index_Mongoose-SchemaTypes)
  233. The various Mongoose SchemaTypes.
  234. #### Note:
  235. *Alias of mongoose.Schema.Types for backwards compatibility.*
  236. show code
  237. ```
  238. Mongoose.prototype.SchemaTypes = Schema.Types;
  239. ```
  240. #### See:
  241. - [Schema.SchemaTypes](#schema_Schema.Types "Schema.SchemaTypes")
  242. ---
  243. ### [Mongoose#Types](#index_Mongoose-Types)
  244. The various Mongoose Types.
  245. #### Example:
  246. ```
  247. var mongoose = require('mongoose');
  248. var array = mongoose.Types.Array;
  249. ```
  250. #### Types:
  251. - [ObjectId](#types-objectid-js)
  252. - [Buffer](#types-buffer-js)
  253. - [SubDocument](#types-embedded-js)
  254. - [Array](#types-array-js)
  255. - [DocumentArray](#types-documentarray-js)
  256. Using this exposed access to the `ObjectId` type, we can construct ids on demand.
  257. ```
  258. var ObjectId = mongoose.Types.ObjectId;
  259. var id1 = new ObjectId;
  260. ```
  261. show code
  262. ```
  263. Mongoose.prototype.Types = Types;
  264. ```
  265. ---
  266. ### [Mongoose#version](#index_Mongoose-version)
  267. The Mongoose version
  268. show code
  269. ```
  270. Mongoose.prototype.version = pkg.version;
  271. ```
  272. ---
  • virtualtype.js

    VirtualType#applyGetters(value, scope)

    Applies getters to value using optional scope.

    Parameters:

    Returns:

    • <T> the value after applying all getters

    show code

    1. VirtualType.prototype.applyGetters = function(value, scope) {
    2. var v = value;
    3. for (var l = this.getters.length - 1; l >= 0; l--) {
    4. v = this.getters[l].call(scope, v, this);
    5. }
    6. return v;
    7. };

    VirtualType#applySetters(value, scope)

    Applies setters to value using optional scope.

    Parameters:

    Returns:

    • <T> the value after applying all setters

    show code

    1. VirtualType.prototype.applySetters = function(value, scope) {
    2. var v = value;
    3. for (var l = this.setters.length - 1; l >= 0; l--) {
    4. v = this.setters[l].call(scope, v, this);
    5. }
    6. return v;
    7. };

    VirtualType#get(fn)

    Defines a getter.

    Parameters:

    Returns:

    Example:

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

    show code

    1. VirtualType.prototype.get = function(fn) {
    2. this.getters.push(fn);
    3. return this;
    4. };

    VirtualType#set(fn)

    Defines a setter.

    Parameters:

    Returns:

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

    show code

    1. VirtualType.prototype.set = function(fn) {
    2. this.setters.push(fn);
    3. return this;
    4. };

    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

    show code

    1. function VirtualType(options, name) {
    2. this.path = name;
    3. this.getters = [];
    4. this.setters = [];
    5. this.options = options || {};
    6. }

  • browserDocument.js

    Document(obj, [fields], [skipId])

    Document constructor.

    Parameters:

    • obj <Object> the values to set
    • [fields] <Object> optional object containing the fields which were selected in the query returning this document and any populated paths data
    • [skipId] <Boolean> bool, should we auto create an ObjectId _id

    Inherits:

    Events:

    • init: Emitted on a document after it has was retrieved from the db and fully hydrated by Mongoose.

    • save: Emitted when the document is successfully saved

    show code

    ``` function Document(obj, schema, fields, skipId, skipInit) { if (!(this instanceof Document)) {

    1. return new Document(obj, schema, fields, skipId, skipInit);

    }

  1. if (utils.isObject(schema) && !schema.instanceOfSchema) {
  2. schema = new Schema(schema);
  3. }
  4. // When creating EmbeddedDocument, it already has the schema and he doesn't need the _id
  5. schema = this.schema || schema;
  6. // Generate ObjectId if it is missing, but it requires a scheme
  7. if (!this.schema && schema.options._id) {
  8. obj = obj || {};
  9. if (obj._id === undefined) {
  10. obj._id = new ObjectId();
  11. }
  12. }
  13. if (!schema) {
  14. throw new MongooseError.MissingSchemaError();
  15. }
  16. this.$__setSchema(schema);
  17. this.$__ = new InternalCache;
  18. this.$__.emitter = new EventEmitter();
  19. this.isNew = true;
  20. this.errors = undefined;
  21. if (typeof fields === 'boolean') {
  22. this.$__.strictMode = fields;
  23. fields = undefined;
  24. } else {
  25. this.$__.strictMode = this.schema.options && this.schema.options.strict;
  26. this.$__.selected = fields;
  27. }
  28. var required = this.schema.requiredPaths();
  29. for (var i = 0; i < required.length; ++i) {
  30. this.$__.activePaths.require(required[i]);
  31. }
  32. this.$__.emitter.setMaxListeners(0);
  33. this._doc = this.$__buildDoc(obj, fields, skipId);
  34. if (!skipInit && obj) {
  35. this.init(obj);
  36. }
  37. this.$__registerHooksFromSchema();
  38. // apply methods
  39. for (var m in schema.methods) {
  40. this[m] = schema.methods[m];
  41. }
  42. // apply statics
  43. for (var s in schema.statics) {
  44. this[s] = schema.statics[s];
  45. }
  46. }
  47. ```
  48. ---
  • types/documentarray.js

    MongooseDocumentArray(values, path, doc)

    DocumentArray constructor

    Parameters:

    Returns:

    Inherits:

    See:

    show code

    1. function MongooseDocumentArray(values, path, doc) {
    2. var arr = [].concat(values);
    3. arr._path = path;
    4. var props = {
    5. isMongooseArray: true,
    6. isMongooseDocumentArray: true,
    7. validators: [],
    8. _atomics: {},
    9. _schema: void 0,
    10. _handlers: void 0
    11. };
    12. // Values always have to be passed to the constructor to initialize, since
    13. // otherwise MongooseArray#push will mark the array as modified to the parent.
    14. var keysMA = Object.keys(MongooseArray.mixin);
    15. var numKeys = keysMA.length;
    16. for (var j = 0; j < numKeys; ++j) {
    17. arr[keysMA[j]] = MongooseArray.mixin[keysMA[j]];
    18. }
    19. var keysMDA = Object.keys(MongooseDocumentArray.mixin);
    20. numKeys = keysMDA.length;
    21. for (var i = 0; i < numKeys; ++i) {
    22. arr[keysMDA[i]] = MongooseDocumentArray.mixin[keysMDA[i]];
    23. }
    24. var keysP = Object.keys(props);
    25. numKeys = keysP.length;
    26. for (var k = 0; k < numKeys; ++k) {
    27. arr[keysP[k]] = props[keysP[k]];
    28. }
    29. // Because doc comes from the context of another function, doc === global
    30. // can happen if there was a null somewhere up the chain (see #3020 && #3034)
    31. // RB Jun 17, 2015 updated to check for presence of expected paths instead
    32. // to make more proof against unusual node environments
    33. if (doc && doc instanceof Document) {
    34. arr._parent = doc;
    35. arr._schema = doc.schema.path(path);
    36. arr._handlers = {
    37. isNew: arr.notify('isNew'),
    38. save: arr.notify('save')
    39. };
    40. doc.on('save', arr._handlers.save);
    41. doc.on('isNew', arr._handlers.isNew);
    42. }
    43. return arr;
    44. }

    MongooseDocumentArray._cast()

    Overrides MongooseArray#cast


    MongooseDocumentArray.id(id)

    Searches array items for the first document with a matching _id.

    Parameters:

    Returns:

    Example:

    1. var embeddedDoc = m.array.id(some_id);

    MongooseDocumentArray.toObject([options])

    Returns a native js Array of plain js objects

    Parameters:

    • [options] <Object> optional options to pass to each documents <code>toObject</code> method call during conversion

    Returns:

    NOTE:

    Each sub-document is converted to a plain object by calling its #toObject method.


    MongooseDocumentArray.inspect()

    Helper for console.log


    MongooseDocumentArray.create(obj)

    Creates a subdocument casted to this schema.

    Parameters:

    • obj <Object> the value to cast to this arrays SubDocument schema

    This is the same subdocument constructor used for casting.


    MongooseDocumentArray.notify(event)

    Creates a fn that notifies all child docs of event.

    Parameters:

    Returns:


  • types/array.js

    MongooseArray#$__getAtomics()

    Depopulates stored atomic operation values as necessary for direct insertion to MongoDB.

    Returns:

    If no atomics exist, we return all array values after conversion.


    MongooseArray#$shift()

    Atomically shifts the array at most one time per document save().

    See:

    NOTE:

    Calling this mulitple times on an array before saving sends the same command as calling it once.
    This update is implemented using the MongoDB $pop method which enforces this restriction.

    1. doc.array = [1,2,3];
    2. var shifted = doc.array.$shift();
    3. console.log(shifted); // 1
    4. console.log(doc.array); // [2,3]
    5. // no affect
    6. shifted = doc.array.$shift();
    7. console.log(doc.array); // [2,3]
    8. doc.save(function (err) {
    9. if (err) return handleError(err);
    10. // we saved, now $shift works again
    11. shifted = doc.array.$shift();
    12. console.log(shifted ); // 2
    13. console.log(doc.array); // [3]
    14. })

    MongooseArray(values, path, doc)

    Mongoose Array constructor.

    Parameters:

    Inherits:

    See:

    NOTE:

    Values always have to be passed to the constructor to initialize, otherwise MongooseArray#push will mark the array as modified.

    show code

    1. function MongooseArray(values, path, doc) {
    2. var arr = [].concat(values);
    3. var keysMA = Object.keys(MongooseArray.mixin);
    4. var numKeys = keysMA.length;
    5. for (var i = 0; i < numKeys; ++i) {
    6. arr[keysMA[i]] = MongooseArray.mixin[keysMA[i]];
    7. }
    8. arr._path = path;
    9. arr.isMongooseArray = true;
    10. arr.validators = [];
    11. arr._atomics = {};
    12. arr._schema = void 0;
    13. // Because doc comes from the context of another function, doc === global
    14. // can happen if there was a null somewhere up the chain (see #3020)
    15. // RB Jun 17, 2015 updated to check for presence of expected paths instead
    16. // to make more proof against unusual node environments
    17. if (doc && doc instanceof Document) {
    18. arr._parent = doc;
    19. arr._schema = doc.schema.path(path);
    20. }
    21. return arr;
    22. }
    23. MongooseArray.mixin = {

    MongooseArray#remove()

    Alias of pull

    See:


    MongooseArray._cast(value)

    Casts a member based on this arrays schema.

    Parameters:

    • value <T>

    Returns:

    • <value> the casted value

    MongooseArray._mapCast()

    Internal helper for .map()

    Returns:


    MongooseArray._markModified(embeddedDoc, embeddedPath)

    Marks this array as modified.

    Parameters:

    • embeddedDoc <EmbeddedDocument> the embedded doc that invoked this method on the Array
    • embeddedPath <String> the path which changed in the embeddedDoc

    If it bubbles up from an embedded document change, then it takes the following arguments (otherwise, takes 0 arguments)


    MongooseArray._registerAtomic(op, val)

    Register an atomic operation with the parent.

    Parameters:

    • op <Array> operation
    • val <T>

    MongooseArray.$pop()

    Pops the array atomically at most one time per document save().

    See:

    NOTE:

    Calling this mulitple times on an array before saving sends the same command as calling it once.
    This update is implemented using the MongoDB $pop method which enforces this restriction.

    1. doc.array = [1,2,3];
    2. var popped = doc.array.$pop();
    3. console.log(popped); // 3
    4. console.log(doc.array); // [1,2]
    5. // no affect
    6. popped = doc.array.$pop();
    7. console.log(doc.array); // [1,2]
    8. doc.save(function (err) {
    9. if (err) return handleError(err);
    10. // we saved, now $pop works again
    11. popped = doc.array.$pop();
    12. console.log(popped); // 2
    13. console.log(doc.array); // [1]
    14. })

    MongooseArray.addToSet([args...])

    Adds values to the array if not already present.

    Parameters:

    • [args...] <T>

    Returns:

    • <Array> the values that were added

    Example:

    1. console.log(doc.array) // [2,3,4]
    2. var added = doc.array.addToSet(4,5);
    3. console.log(doc.array) // [2,3,4,5]
    4. console.log(added) // [5]

    MongooseArray.hasAtomics()

    Returns the number of pending atomic operations to send to the db for this array.

    Returns:


    MongooseArray.indexOf(obj)

    Return the index of obj or -1 if not found.

    Parameters:

    • obj <Object> the item to look for

    Returns:


    MongooseArray.inspect()

    Helper for console.log


    MongooseArray.nonAtomicPush([args...])

    Pushes items to the array non-atomically.

    Parameters:

    • [args...] <T>

    NOTE:

    marks the entire array as modified, which if saved, will store it as a $set operation, potentially overwritting any changes that happen between when you retrieved the object and when you save it.


    MongooseArray.pop()

    Wraps Array#pop with proper change tracking.

    See:

    Note:

    marks the entire array as modified which will pass the entire thing to $set potentially overwritting any changes that happen between when you retrieved the object and when you save it.


    MongooseArray.pull([args...])

    Pulls items from the array atomically. Equality is determined by casting
    the provided value to an embedded document and comparing using
    the Document.equals() function.

    Parameters:

    • [args...] <T>

    See:

    Examples:

    1. doc.array.pull(ObjectId)
    2. doc.array.pull({ _id: 'someId' })
    3. doc.array.pull(36)
    4. doc.array.pull('tag 1', 'tag 2')

    To remove a document from a subdocument array we may pass an object with a matching _id.

    1. doc.subdocs.push({ _id: 4815162342 })
    2. doc.subdocs.pull({ _id: 4815162342 }) // removed

    Or we may passing the _id directly and let mongoose take care of it.

    1. doc.subdocs.push({ _id: 4815162342 })
    2. doc.subdocs.pull(4815162342); // works

    The first pull call will result in a atomic operation on the database, if pull is called repeatedly without saving the document, a $set operation is used on the complete array instead, overwriting possible changes that happened on the database in the meantime.


    MongooseArray.push([args...])

    Wraps Array#push with proper change tracking.

    Parameters:


    MongooseArray.set()

    Sets the casted val at index i and marks the array modified.

    Returns:

    Example:

    1. // given documents based on the following
    2. var Doc = mongoose.model('Doc', new Schema({ array: [Number] }));
    3. var doc = new Doc({ array: [2,3,4] })
    4. console.log(doc.array) // [2,3,4]
    5. doc.array.set(1,"5");
    6. console.log(doc.array); // [2,5,4] // properly cast to number
    7. doc.save() // the change is saved
    8. // VS not using array#set
    9. doc.array[1] = "5";
    10. console.log(doc.array); // [2,"5",4] // no casting
    11. doc.save() // change is not saved

    MongooseArray.shift()

    Wraps Array#shift with proper change tracking.

    Example:

    1. doc.array = [2,3];
    2. var res = doc.array.shift();
    3. console.log(res) // 2
    4. console.log(doc.array) // [3]

    Note:

    marks the entire array as modified, which if saved, will store it as a $set operation, potentially overwritting any changes that happen between when you retrieved the object and when you save it.


    MongooseArray.sort()

    Wraps Array#sort with proper change tracking.

    NOTE:

    marks the entire array as modified, which if saved, will store it as a $set operation, potentially overwritting any changes that happen between when you retrieved the object and when you save it.


    MongooseArray.splice()

    Wraps Array#splice with proper change tracking and casting.

    Note:

    marks the entire array as modified, which if saved, will store it as a $set operation, potentially overwritting any changes that happen between when you retrieved the object and when you save it.


    MongooseArray.toObject(options)

    Returns a native js Array.

    Parameters:

    Returns:


    MongooseArray.unshift()

    Wraps Array#unshift with proper change tracking.

    Note:

    marks the entire array as modified, which if saved, will store it as a $set operation, potentially overwritting any changes that happen between when you retrieved the object and when you save it.


    MongooseArray#_atomics

    Stores a queue of atomic operations to perform

    show code

    1. _atomics: undefined,

    MongooseArray#_parent

    Parent owner document

    show code

    1. _parent: undefined,

  • types/decimal128.js

    exports()

    ObjectId type constructor

    Example

    1. var id = new mongoose.Types.ObjectId;

  • types/objectid.js

    ObjectId()

    ObjectId type constructor

    Example

    1. var id = new mongoose.Types.ObjectId;

  • types/subdocument.js

    Subdocument#ownerDocument()

    Returns the top level document of this sub-document.

    Returns:

    show code

    1. Subdocument.prototype.ownerDocument = function() {
    2. if (this.$__.ownerDocument) {
    3. return this.$__.ownerDocument;
    4. }
    5. var parent = this.$parent;
    6. if (!parent) {
    7. return this;
    8. }
    9. while (parent.$parent || parent.__parent) {
    10. parent = parent.$parent || parent.__parent;
    11. }
    12. this.$__.ownerDocument = parent;
    13. return this.$__.ownerDocument;
    14. };

    Subdocument#parent()

    Returns this sub-documents parent document.

    show code

    1. Subdocument.prototype.parent = function() {
    2. return this.$parent;
    3. };

    Subdocument#remove([options], [callback])

    Null-out this subdoc

    Parameters:

    • [options] <Object>
    • [callback] <Function> optional callback for compatibility with Document.prototype.remove

    show code

    1. Subdocument.prototype.remove = function(options, callback) {
    2. if (typeof options === 'function') {
    3. callback = options;
    4. options = null;
    5. }
    6. registerRemoveListener(this);
    7. // If removing entire doc, no need to remove subdoc
    8. if (!options || !options.noop) {
    9. this.$parent.set(this.$basePath, null);
    10. }
    11. if (typeof callback === 'function') {
    12. callback(null);
    13. }
    14. };

    Subdocument#save([fn])

    Used as a stub for hooks.js

    Parameters:

    Returns:

    NOTE:

    This is a no-op. Does not actually save the doc to the db.

    show code

    1. Subdocument.prototype.save = function(fn) {
    2. var Promise = PromiseProvider.get();
    3. return new Promise.ES6(function(resolve) {
    4. fn && fn();
    5. resolve();
    6. });
    7. };
    8. Subdocument.prototype.$isValid = function(path) {
    9. if (this.$parent && this.$basePath) {
    10. return this.$parent.$isValid([this.$basePath, path].join('.'));
    11. }
    12. return Document.prototype.$isValid.call(this, path);
    13. };
    14. Subdocument.prototype.markModified = function(path) {
    15. Document.prototype.markModified.call(this, path);
    16. if (this.$parent && this.$basePath) {
    17. if (this.$parent.isDirectModified(this.$basePath)) {
    18. return;
    19. }
    20. this.$parent.markModified([this.$basePath, path].join('.'), this);
    21. }
    22. };
    23. Subdocument.prototype.$markValid = function(path) {
    24. Document.prototype.$markValid.call(this, path);
    25. if (this.$parent && this.$basePath) {
    26. this.$parent.$markValid([this.$basePath, path].join('.'));
    27. }
    28. };
    29. Subdocument.prototype.invalidate = function(path, err, val) {
    30. // Hack: array subdocuments' validationError is equal to the owner doc's,
    31. // so validating an array subdoc gives the top-level doc back. Temporary
    32. // workaround for #5208 so we don't have circular errors.
    33. if (err !== this.ownerDocument().$__.validationError) {
    34. Document.prototype.invalidate.call(this, path, err, val);
    35. }
    36. if (this.$parent && this.$basePath) {
    37. this.$parent.invalidate([this.$basePath, path].join('.'), err, val);
    38. } else if (err.kind === 'cast' || err.name === 'CastError') {
    39. throw err;
    40. }
    41. };

    Subdocument()

    Subdocument constructor.

    Inherits:

    show code

    1. function Subdocument(value, fields, parent, skipId, options) {
    2. this.$isSingleNested = true;
    3. Document.call(this, value, fields, skipId, options);
    4. }
    5. Subdocument.prototype = Object.create(Document.prototype);
    6. Subdocument.prototype.toBSON = function() {
    7. return this.toObject({
    8. transform: false,
    9. virtuals: false,
    10. _skipDepopulateTopLevel: true,
    11. depopulate: true,
    12. flattenDecimals: false
    13. });
    14. };

  • types/embedded.js

    EmbeddedDocument#$__fullPath([path])

    Returns the full path to this document. If optional path is passed, it is appended to the full path.

    Parameters:

    Returns:


    EmbeddedDocument(obj, parentArr, skipId)

    EmbeddedDocument constructor.

    Parameters:

    Inherits:

    show code

    1. function EmbeddedDocument(obj, parentArr, skipId, fields, index) {
    2. if (parentArr) {
    3. this.__parentArray = parentArr;
    4. this.__parent = parentArr._parent;
    5. } else {
    6. this.__parentArray = undefined;
    7. this.__parent = undefined;
    8. }
    9. this.__index = index;
    10. Document.call(this, obj, fields, skipId);
    11. var _this = this;
    12. this.on('isNew', function(val) {
    13. _this.isNew = val;
    14. });
    15. _this.on('save', function() {
    16. _this.constructor.emit('save', _this);
    17. });
    18. }

    EmbeddedDocument#inspect()

    Helper for console.log

    show code

    1. EmbeddedDocument.prototype.inspect = function() {
    2. return this.toObject({
    3. transform: false,
    4. retainKeyOrder: true,
    5. virtuals: false,
    6. flattenDecimals: false
    7. });
    8. };

    EmbeddedDocument#invalidate(path, err)

    Marks a path as invalid, causing validation to fail.

    Parameters:

    • path <String> the field to invalidate
    • err <String, Error> error which states the reason path was invalid

    Returns:

    show code

    1. EmbeddedDocument.prototype.invalidate = function(path, err, val, first) {
    2. if (!this.__parent) {
    3. Document.prototype.invalidate.call(this, path, err, val);
    4. if (err.$isValidatorError) {
    5. return true;
    6. }
    7. throw err;
    8. }
    9. var index = this.__index;
    10. if (typeof index !== 'undefined') {
    11. var parentPath = this.__parentArray._path;
    12. var fullPath = [parentPath, index, path].join('.');
    13. this.__parent.invalidate(fullPath, err, val);
    14. }
    15. if (first) {
    16. this.$__.validationError = this.ownerDocument().$__.validationError;
    17. }
    18. return true;
    19. };

    EmbeddedDocument#ownerDocument()

    Returns the top level document of this sub-document.

    Returns:

    show code

    1. EmbeddedDocument.prototype.ownerDocument = function() {
    2. if (this.$__.ownerDocument) {
    3. return this.$__.ownerDocument;
    4. }
    5. var parent = this.__parent;
    6. if (!parent) {
    7. return this;
    8. }
    9. while (parent.__parent || parent.$parent) {
    10. parent = parent.__parent || parent.$parent;
    11. }
    12. this.$__.ownerDocument = parent;
    13. return this.$__.ownerDocument;
    14. };

    EmbeddedDocument#parent()

    Returns this sub-documents parent document.

    show code

    1. EmbeddedDocument.prototype.parent = function() {
    2. return this.__parent;
    3. };

    EmbeddedDocument#parentArray()

    Returns this sub-documents parent array.

    show code

    1. EmbeddedDocument.prototype.parentArray = function() {
    2. return this.__parentArray;
    3. };

    EmbeddedDocument#remove([options], [fn])

    Removes the subdocument from its parent array.

    Parameters:

    show code

    1. EmbeddedDocument.prototype.remove = function(options, fn) {
    2. if ( typeof options === 'function' && !fn ) {
    3. fn = options;
    4. options = undefined;
    5. }
    6. if (!this.__parentArray || (options && options.noop)) {
    7. fn && fn(null);
    8. return this;
    9. }
    10. var _id;
    11. if (!this.willRemove) {
    12. _id = this._doc._id;
    13. if (!_id) {
    14. throw new Error('For your own good, Mongoose does not know ' +
    15. 'how to remove an EmbeddedDocument that has no _id');
    16. }
    17. this.__parentArray.pull({_id: _id});
    18. this.willRemove = true;
    19. registerRemoveListener(this);
    20. }
    21. if (fn) {
    22. fn(null);
    23. }
    24. return this;
    25. };

    EmbeddedDocument#save([fn])

    Used as a stub for hooks.js

    Parameters:

    Returns:

    NOTE:

    This is a no-op. Does not actually save the doc to the db.

    show code

    1. EmbeddedDocument.prototype.save = function(fn) {
    2. var Promise = PromiseProvider.get();
    3. return new Promise.ES6(function(resolve) {
    4. fn && fn();
    5. resolve();
    6. });
    7. };

    EmbeddedDocument#update()

    Override #update method of parent documents.

    show code

    1. EmbeddedDocument.prototype.update = function() {
    2. throw new Error('The #update method is not available on EmbeddedDocuments');
    3. };

    EmbeddedDocument.$isValid(path)

    Checks if a path is invalid

    Parameters:

    • path <String> the field to check

    EmbeddedDocument.$markValid(path)

    Marks a path as valid, removing existing validation errors.

    Parameters:

    • path <String> the field to mark as valid

    EmbeddedDocument.markModified(path)

    Marks the embedded doc modified.

    show code

    1. EmbeddedDocument.prototype.markModified = function(path) {
    2. this.$__.activePaths.modify(path);
    3. if (!this.__parentArray) {
    4. return;
    5. }
    6. if (this.isNew) {
    7. // Mark the WHOLE parent array as modified
    8. // if this is a new document (i.e., we are initializing
    9. // a document),
    10. this.__parentArray._markModified();
    11. } else {
    12. this.__parentArray._markModified(this, path);
    13. }
    14. };

    Parameters:

    • path <String> the path which changed

    Example:

    1. var doc = blogpost.comments.id(hexstring);
    2. doc.mixed.type = 'changed';
    3. doc.markModified('mixed.type');

  • types/buffer.js

    MongooseBuffer(value, encode, offset)

    Mongoose Buffer constructor.

    Parameters:

    Inherits:

    See:

    Values always have to be passed to the constructor to initialize.

    show code

    1. function MongooseBuffer(value, encode, offset) {
    2. var length = arguments.length;
    3. var val;
    4. if (length === 0 || arguments[0] === null || arguments[0] === undefined) {
    5. val = 0;
    6. } else {
    7. val = value;
    8. }
    9. var encoding;
    10. var path;
    11. var doc;
    12. if (Array.isArray(encode)) {
    13. // internal casting
    14. path = encode[0];
    15. doc = encode[1];
    16. } else {
    17. encoding = encode;
    18. }
    19. var buf = new Buffer(val, encoding, offset);
    20. utils.decorate(buf, MongooseBuffer.mixin);
    21. buf.isMongooseBuffer = true;
    22. // make sure these internal props don't show up in Object.keys()
    23. Object.defineProperties(buf, {
    24. validators: {
    25. value: [],
    26. enumerable: false
    27. },
    28. _path: {
    29. value: path,
    30. enumerable: false
    31. },
    32. _parent: {
    33. value: doc,
    34. enumerable: false
    35. }
    36. });
    37. if (doc && typeof path === 'string') {
    38. Object.defineProperty(buf, '_schema', {
    39. value: doc.schema.path(path)
    40. });
    41. }
    42. buf._subtype = 0;
    43. return buf;
    44. }

    MongooseBuffer._markModified()

    Marks this buffer as modified.


    MongooseBuffer.copy(target)

    Copies the buffer.

    Parameters:

    Returns:

    • <Number> The number of bytes copied.

    Note:

    Buffer#copy does not mark target as modified so you must copy from a MongooseBuffer for it to work as expected. This is a work around since copy modifies the target, not this.


    MongooseBuffer.equals(other)

    Determines if this buffer is equals to other buffer

    Parameters:

    Returns:


    MongooseBuffer.subtype(subtype)

    Sets the subtype option and marks the buffer modified.

    Parameters:

    See:

    SubTypes:

    var bson = require(‘bson’)
    bson.BSON_BINARY_SUBTYPE_DEFAULT
    bson.BSON_BINARY_SUBTYPE_FUNCTION
    bson.BSON_BINARY_SUBTYPE_BYTE_ARRAY
    bson.BSON_BINARY_SUBTYPE_UUID
    bson.BSON_BINARY_SUBTYPE_MD5
    bson.BSON_BINARY_SUBTYPE_USER_DEFINED

    doc.buffer.subtype(bson.BSON_BINARY_SUBTYPE_UUID);


    MongooseBuffer.toBSON()

    Converts this buffer for storage in MongoDB, including subtype

    Returns:


    MongooseBuffer.toObject([subtype])

    Converts this buffer to its Binary type representation.

    Parameters:

    • [subtype] <Hex>

    Returns:

    See:

    SubTypes:

    var bson = require(‘bson’)
    bson.BSON_BINARY_SUBTYPE_DEFAULT
    bson.BSON_BINARY_SUBTYPE_FUNCTION
    bson.BSON_BINARY_SUBTYPE_BYTE_ARRAY
    bson.BSON_BINARY_SUBTYPE_UUID
    bson.BSON_BINARY_SUBTYPE_MD5
    bson.BSON_BINARY_SUBTYPE_USER_DEFINED

    doc.buffer.toObject(bson.BSON_BINARY_SUBTYPE_USER_DEFINED);


    MongooseBuffer.write()

    Writes the buffer.


    MongooseBuffer#_parent

    Parent owner document

    show code

    1. _parent: undefined,

    MongooseBuffer#_subtype

    Default subtype for the Binary representing this Buffer

    show code

    1. _subtype: undefined,

  • document_provider.js

    module.exports()

    Returns the Document constructor for the current context

    show code

    1. module.exports = function() {
    2. if (isBrowser) {
    3. return BrowserDocument;
    4. }
    5. return Document;
    6. };

  • cast.js

    module.exports(schema, obj, options, context)

    Handles internal casting for query filters.

    show code

    1. module.exports = function cast(schema, obj, options, context) {
    2. if (Array.isArray(obj)) {
    3. throw new Error('Query filter must be an object, got an array ', util.inspect(obj));
    4. }
    5. var paths = Object.keys(obj);
    6. var i = paths.length;
    7. var _keys;
    8. var any$conditionals;
    9. var schematype;
    10. var nested;
    11. var path;
    12. var type;
    13. var val;
    14. while (i--) {
    15. path = paths[i];
    16. val = obj[path];
    17. if (path === '$or' || path === '$nor' || path === '$and') {
    18. var k = val.length;
    19. while (k--) {
    20. val[k] = cast(schema, val[k], options, context);
    21. }
    22. } else if (path === '$where') {
    23. type = typeof val;
    24. if (type !== 'string' && type !== 'function') {
    25. throw new Error('Must have a string or function for $where');
    26. }
    27. if (type === 'function') {
    28. obj[path] = val.toString();
    29. }
    30. continue;
    31. } else if (path === '$elemMatch') {
    32. val = cast(schema, val, options, context);
    33. } else {
    34. if (!schema) {
    35. // no casting for Mixed types
    36. continue;
    37. }
    38. schematype = schema.path(path);
    39. if (!schematype) {
    40. // Handle potential embedded array queries
    41. var split = path.split('.'),
    42. j = split.length,
    43. pathFirstHalf,
    44. pathLastHalf,
    45. remainingConds;
    46. // Find the part of the var path that is a path of the Schema
    47. while (j--) {
    48. pathFirstHalf = split.slice(0, j).join('.');
    49. schematype = schema.path(pathFirstHalf);
    50. if (schematype) {
    51. break;
    52. }
    53. }
    54. // If a substring of the input path resolves to an actual real path...
    55. if (schematype) {
    56. // Apply the casting; similar code for $elemMatch in schema/array.js
    57. if (schematype.caster && schematype.caster.schema) {
    58. remainingConds = {};
    59. pathLastHalf = split.slice(j).join('.');
    60. remainingConds[pathLastHalf] = val;
    61. obj[path] = cast(schematype.caster.schema, remainingConds, options, context)[pathLastHalf];
    62. } else {
    63. obj[path] = val;
    64. }
    65. continue;
    66. }
    67. if (utils.isObject(val)) {
    68. // handle geo schemas that use object notation
    69. // { loc: { long: Number, lat: Number }
    70. var geo = '';
    71. if (val.$near) {
    72. geo = '$near';
    73. } else if (val.$nearSphere) {
    74. geo = '$nearSphere';
    75. } else if (val.$within) {
    76. geo = '$within';
    77. } else if (val.$geoIntersects) {
    78. geo = '$geoIntersects';
    79. } else if (val.$geoWithin) {
    80. geo = '$geoWithin';
    81. }
    82. if (geo) {
    83. var numbertype = new Types.Number('__QueryCasting__');
    84. var value = val[geo];
    85. if (val.$maxDistance != null) {
    86. val.$maxDistance = numbertype.castForQueryWrapper({
    87. val: val.$maxDistance,
    88. context: context
    89. });
    90. }
    91. if (val.$minDistance != null) {
    92. val.$minDistance = numbertype.castForQueryWrapper({
    93. val: val.$minDistance,
    94. context: context
    95. });
    96. }
    97. if (geo === '$within') {
    98. var withinType = value.$center
    99. || value.$centerSphere
    100. || value.$box
    101. || value.$polygon;
    102. if (!withinType) {
    103. throw new Error('Bad $within paramater: ' + JSON.stringify(val));
    104. }
    105. value = withinType;
    106. } else if (geo === '$near' &&
    107. typeof value.type === 'string' && Array.isArray(value.coordinates)) {
    108. // geojson; cast the coordinates
    109. value = value.coordinates;
    110. } else if ((geo === '$near' || geo === '$nearSphere' || geo === '$geoIntersects') &&
    111. value.$geometry && typeof value.$geometry.type === 'string' &&
    112. Array.isArray(value.$geometry.coordinates)) {
    113. if (value.$maxDistance != null) {
    114. value.$maxDistance = numbertype.castForQueryWrapper({
    115. val: value.$maxDistance,
    116. context: context
    117. });
    118. }
    119. if (value.$minDistance != null) {
    120. value.$minDistance = numbertype.castForQueryWrapper({
    121. val: value.$minDistance,
    122. context: context
    123. });
    124. }
    125. if (utils.isMongooseObject(value.$geometry)) {
    126. value.$geometry = value.$geometry.toObject({
    127. transform: false,
    128. virtuals: false
    129. });
    130. }
    131. value = value.$geometry.coordinates;
    132. } else if (geo === '$geoWithin') {
    133. if (value.$geometry) {
    134. if (utils.isMongooseObject(value.$geometry)) {
    135. value.$geometry = value.$geometry.toObject({ virtuals: false });
    136. }
    137. var geoWithinType = value.$geometry.type;
    138. if (ALLOWED_GEOWITHIN_GEOJSON_TYPES.indexOf(geoWithinType) === -1) {
    139. throw new Error('Invalid geoJSON type for $geoWithin "' +
    140. geoWithinType + '", must be "Polygon" or "MultiPolygon"');
    141. }
    142. value = value.$geometry.coordinates;
    143. } else {
    144. value = value.$box || value.$polygon || value.$center ||
    145. value.$centerSphere;
    146. if (utils.isMongooseObject(value)) {
    147. value = value.toObject({ virtuals: false });
    148. }
    149. }
    150. }
    151. _cast(value, numbertype, context);
    152. continue;
    153. }
    154. }
    155. if (options && options.upsert && options.strict && !schema.nested[path]) {
    156. if (options.strict === 'throw') {
    157. throw new StrictModeError(path);
    158. }
    159. throw new StrictModeError(path, 'Path "' + path + '" is not in ' +
    160. 'schema, strict mode is `true`, and upsert is `true`.');
    161. } else if (options && options.strictQuery === 'throw') {
    162. throw new StrictModeError(path, 'Path "' + path + '" is not in ' +
    163. 'schema and strictQuery is true.');
    164. }
    165. } else if (val === null || val === undefined) {
    166. obj[path] = null;
    167. continue;
    168. } else if (val.constructor.name === 'Object') {
    169. any$conditionals = Object.keys(val).some(function(k) {
    170. return k.charAt(0) === '$' && k !== '$id' && k !== '$ref';
    171. });
    172. if (!any$conditionals) {
    173. obj[path] = schematype.castForQueryWrapper({
    174. val: val,
    175. context: context
    176. });
    177. } else {
    178. var ks = Object.keys(val),
    179. $cond;
    180. k = ks.length;
    181. while (k--) {
    182. $cond = ks[k];
    183. nested = val[$cond];
    184. if ($cond === '$not') {
    185. if (nested && schematype && !schematype.caster) {
    186. _keys = Object.keys(nested);
    187. if (_keys.length && _keys[0].charAt(0) === '$') {
    188. for (var key in nested) {
    189. nested[key] = schematype.castForQueryWrapper({
    190. $conditional: key,
    191. val: nested[key],
    192. context: context
    193. });
    194. }
    195. } else {
    196. val[$cond] = schematype.castForQueryWrapper({
    197. $conditional: $cond,
    198. val: nested,
    199. context: context
    200. });
    201. }
    202. continue;
    203. }
    204. cast(schematype.caster ? schematype.caster.schema : schema, nested, options, context);
    205. } else {
    206. val[$cond] = schematype.castForQueryWrapper({
    207. $conditional: $cond,
    208. val: nested,
    209. context: context
    210. });
    211. }
    212. }
    213. }
    214. } else if (Array.isArray(val) && ['Buffer', 'Array'].indexOf(schematype.instance) === -1) {
    215. var casted = [];
    216. for (var valIndex = 0; valIndex < val.length; valIndex++) {
    217. casted.push(schematype.castForQueryWrapper({
    218. val: val[valIndex],
    219. context: context
    220. }));
    221. }
    222. obj[path] = { $in: casted };
    223. } else {
    224. obj[path] = schematype.castForQueryWrapper({
    225. val: val,
    226. context: context
    227. });
    228. }
    229. }
    230. }
    231. return obj;
    232. };
    233. function _cast(val, numbertype, context) {
    234. if (Array.isArray(val)) {
    235. val.forEach(function(item, i) {
    236. if (Array.isArray(item) || utils.isObject(item)) {
    237. return _cast(item, numbertype, context);
    238. }
    239. val[i] = numbertype.castForQueryWrapper({ val: item, context: context });
    240. });
    241. } else {
    242. var nearKeys = Object.keys(val);
    243. var nearLen = nearKeys.length;
    244. while (nearLen--) {
    245. var nkey = nearKeys[nearLen];
    246. var item = val[nkey];
    247. if (Array.isArray(item) || utils.isObject(item)) {
    248. _cast(item, numbertype, context);
    249. val[nkey] = item;
    250. } else {
    251. val[nkey] = numbertype.castForQuery({ val: item, context: context });
    252. }
    253. }
    254. }
    255. }

    Parameters:


  • document.js

    Document#$__buildDoc(obj, [fields], [skipId])

    Builds the default doc structure

    Parameters:

    Returns:


    Document#$__dirty()

    Returns this documents dirty paths / vals.


    Document#$__fullPath([path])

    Returns the full path to this document.

    Parameters:

    Returns:


    Document#$__getAllSubdocs()

    Get all subdocs (by bfs)


    Document#$__getArrayPathsToValidate()

    Get active path that were changed and are arrays


    Document#$__path(path)

    Returns the schematype for the given path.

    Parameters:


    Document#$__reset()

    Resets the internal modified state of this document.

    Returns:


    Document#$__set()

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


    Document#$__setSchema(schema)

    Assigns/compiles schema into this documents prototype.

    Parameters:


    Document#$__shouldModify()

    Determine if we should mark this change as modified.

    Returns:


    Document#$ignore(path)

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

    Parameters:

    • path <String> the path to ignore

    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#$isDefault([path])

    Checks if a path is set to its default.

    Parameters:

    Returns:

    Example

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

    function Object() { [native code] }#$isDeleted([val])%20%7B%20%5Bnative%20code%5D%20%7D-%24isDeleted)

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

    Parameters:

    • [val] <Boolean> optional, overrides whether mongoose thinks the doc is deleted

    Returns:

    • <Boolean> whether mongoose thinks this doc is deleted.

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

    function Object() { [native code] }#$set(path, val, [type], [options])%20%7B%20%5Bnative%20code%5D%20%7D-%24set)

    Alias for set(), used internally to avoid conflicts

    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

    Document#$toObject()

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


    Document#depopulate(path)

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

    Parameters:

    Returns:

    See:

    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.

    show code

    1. Document.prototype.depopulate = function(path) {
    2. if (typeof path === 'string') {
    3. path = path.split(' ');
    4. }
    5. for (var i = 0; i < path.length; i++) {
    6. var populatedIds = this.populated(path[i]);
    7. if (!populatedIds) {
    8. continue;
    9. }
    10. delete this.$__.populated[path[i]];
    11. this.$set(path[i], populatedIds);
    12. }
    13. return this;
    14. };

    Document(obj, [fields], [skipId])

    Document constructor.

    Parameters:

    • obj <Object> the values to set
    • [fields] <Object> optional object containing the fields which were selected in the query returning this document and any populated paths data
    • [skipId] <Boolean> bool, should we auto create an ObjectId _id

    Inherits:

    Events:

    • init: Emitted on a document after it has was retreived from the db and fully hydrated by Mongoose.

    • save: Emitted when the document is successfully saved

    show code

    1. function Document(obj, fields, skipId, options) {
    2. this.$__ = new InternalCache;
    3. this.$__.emitter = new EventEmitter();
    4. this.isNew = true;
    5. this.errors = undefined;
    6. this.$__.$options = options || {};
    7. if (obj != null && typeof obj !== 'object') {
    8. throw new ObjectParameterError(obj, 'obj', 'Document');
    9. }
    10. var schema = this.schema;
    11. if (typeof fields === 'boolean') {
    12. this.$__.strictMode = fields;
    13. fields = undefined;
    14. } else {
    15. this.$__.strictMode = schema.options && schema.options.strict;
    16. this.$__.selected = fields;
    17. }
    18. var required = schema.requiredPaths(true);
    19. for (var i = 0; i < required.length; ++i) {
    20. this.$__.activePaths.require(required[i]);
    21. }
    22. this.$__.emitter.setMaxListeners(0);
    23. this._doc = this.$__buildDoc(obj, fields, skipId);
    24. if (obj) {
    25. if (obj instanceof Document) {
    26. this.isNew = obj.isNew;
    27. }
    28. // Skip set hooks
    29. if (this.$__original_set) {
    30. this.$__original_set(obj, undefined, true);
    31. } else {
    32. this.$set(obj, undefined, true);
    33. }
    34. }
    35. this.$__._id = this._id;
    36. if (!schema.options.strict && obj) {
    37. var _this = this,
    38. keys = Object.keys(this._doc);
    39. keys.forEach(function(key) {
    40. if (!(key in schema.tree)) {
    41. defineKey(key, null, _this);
    42. }
    43. });
    44. }
    45. applyQueue(this);
    46. }

    Document#equals(doc)

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

    Parameters:

    Returns:

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

    show code

    1. Document.prototype.equals = function(doc) {
    2. if (!doc) {
    3. return false;
    4. }
    5. var tid = this.get('_id');
    6. var docid = doc.get ? doc.get('_id') : doc;
    7. if (!tid && !docid) {
    8. return deepEqual(this, doc);
    9. }
    10. return tid && tid.equals
    11. ? tid.equals(docid)
    12. : tid === docid;
    13. };

    Document#execPopulate()

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

    Returns:

    • <Promise> promise that resolves to the document when population is done

    See:

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

    show code

    1. Document.prototype.execPopulate = function() {
    2. var Promise = PromiseProvider.get();
    3. var _this = this;
    4. return new Promise.ES6(function(resolve, reject) {
    5. _this.populate(function(error, res) {
    6. if (error) {
    7. reject(error);
    8. } else {
    9. resolve(res);
    10. }
    11. });
    12. });
    13. };

    Document#get(path, [type])

    Returns the value of a path.

    Parameters:

    Example

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

    show code

    1. Document.prototype.get = function(path, type) {
    2. var adhoc;
    3. if (type) {
    4. adhoc = Schema.interpretAsType(path, type, this.schema.options);
    5. }
    6. var schema = this.$__path(path) || this.schema.virtualpath(path);
    7. var pieces = path.split('.');
    8. var obj = this._doc;
    9. if (schema instanceof VirtualType) {
    10. if (schema.getters.length === 0) {
    11. return void 0;
    12. }
    13. return schema.applyGetters(null, this);
    14. }
    15. for (var i = 0, l = pieces.length; i < l; i++) {
    16. obj = obj === null || obj === void 0
    17. ? undefined
    18. : obj[pieces[i]];
    19. }
    20. if (adhoc) {
    21. obj = adhoc.cast(obj);
    22. }
    23. if (schema) {
    24. obj = schema.applyGetters(obj, this);
    25. }
    26. return obj;
    27. };

    Document#getValue(path)

    Gets a raw value from a path (no getters)

    Parameters:

    show code

    1. Document.prototype.getValue = function(path) {
    2. return utils.getValue(path, this._doc);
    3. };

    Document#init(doc, fn)

    Initializes the document without setters or marking anything modified.

    Parameters:

    Called internally after a document is returned from mongodb.

    show code

    1. Document.prototype.init = function(doc, opts, fn) {
    2. // do not prefix this method with $__ since its
    3. // used by public hooks
    4. if (typeof opts === 'function') {
    5. fn = opts;
    6. opts = null;
    7. }
    8. this.isNew = false;
    9. this.$init = true;
    10. // handle docs with populated paths
    11. // If doc._id is not null or undefined
    12. if (doc._id !== null && doc._id !== undefined &&
    13. opts && opts.populated && opts.populated.length) {
    14. var id = String(doc._id);
    15. for (var i = 0; i < opts.populated.length; ++i) {
    16. var item = opts.populated[i];
    17. if (item.isVirtual) {
    18. this.populated(item.path, utils.getValue(item.path, doc), item);
    19. } else {
    20. this.populated(item.path, item._docs[id], item);
    21. }
    22. }
    23. }
    24. init(this, doc, this._doc);
    25. this.emit('init', this);
    26. this.constructor.emit('init', this);
    27. this.$__._id = this._id;
    28. if (fn) {
    29. fn(null);
    30. }
    31. return this;
    32. };

    Document#inspect()

    Helper for console.log

    show code

    1. Document.prototype.inspect = function(options) {
    2. var isPOJO = options &&
    3. utils.getFunctionName(options.constructor) === 'Object';
    4. var opts;
    5. if (isPOJO) {
    6. opts = options;
    7. opts.minimize = false;
    8. opts.retainKeyOrder = true;
    9. }
    10. return this.toObject(opts);
    11. };

    Document#invalidate(path, errorMsg, value, [kind])

    Marks a path as invalid, causing validation to fail.

    Parameters:

    • path <String> the field to invalidate
    • errorMsg <String, Error> the error which states the reason path was invalid
    • value <Object, String, Number, T> optional invalid value
    • [kind] <String> optional kind property for the error

    Returns:

    • <ValidationError> the current ValidationError, with all currently invalidated paths

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

    show code

    1. Document.prototype.invalidate = function(path, err, val, kind) {
    2. if (!this.$__.validationError) {
    3. this.$__.validationError = new ValidationError(this);
    4. }
    5. if (this.$__.validationError.errors[path]) {
    6. return;
    7. }
    8. if (!err || typeof err === 'string') {
    9. err = new ValidatorError({
    10. path: path,
    11. message: err,
    12. type: kind || 'user defined',
    13. value: val
    14. });
    15. }
    16. if (this.$__.validationError === err) {
    17. return this.$__.validationError;
    18. }
    19. this.$__.validationError.addError(path, err);
    20. return this.$__.validationError;
    21. };

    Document#isDirectModified(path)

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

    Parameters:

    Returns:

    Example

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

    show code

    1. Document.prototype.isDirectModified = function(path) {
    2. return (path in this.$__.activePaths.states.modify);
    3. };

    Document#isDirectSelected(path)

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

    Parameters:

    Returns:

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

    show code

    1. Document.prototype.isDirectSelected = function isDirectSelected(path) {
    2. if (this.$__.selected) {
    3. if (path === '_id') {
    4. return this.$__.selected._id !== 0;
    5. }
    6. var paths = Object.keys(this.$__.selected);
    7. var i = paths.length;
    8. var inclusive = null;
    9. var cur;
    10. if (i === 1 && paths[0] === '_id') {
    11. // only _id was selected.
    12. return this.$__.selected._id === 0;
    13. }
    14. while (i--) {
    15. cur = paths[i];
    16. if (cur === '_id') {
    17. continue;
    18. }
    19. if (!isDefiningProjection(this.$__.selected[cur])) {
    20. continue;
    21. }
    22. inclusive = !!this.$__.selected[cur];
    23. break;
    24. }
    25. if (inclusive === null) {
    26. return true;
    27. }
    28. if (path in this.$__.selected) {
    29. return inclusive;
    30. }
    31. return !inclusive;
    32. }
    33. return true;
    34. };

    Document#isInit(path)

    Checks if path was initialized.

    Parameters:

    Returns:

    show code

    1. Document.prototype.isInit = function(path) {
    2. return (path in this.$__.activePaths.states.init);
    3. };

    Document#isModified([path])

    Returns true if this document was modified, else false.

    Parameters:

    Returns:

    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

    show code

    1. Document.prototype.isModified = function(paths) {
    2. if (paths) {
    3. if (!Array.isArray(paths)) {
    4. paths = paths.split(' ');
    5. }
    6. var modified = this.modifiedPaths();
    7. var directModifiedPaths = Object.keys(this.$__.activePaths.states.modify);
    8. var isModifiedChild = paths.some(function(path) {
    9. return !!~modified.indexOf(path);
    10. });
    11. return isModifiedChild || paths.some(function(path) {
    12. return directModifiedPaths.some(function(mod) {
    13. return mod === path || path.indexOf(mod + '.') === 0;
    14. });
    15. });
    16. }
    17. return this.$__.activePaths.some('modify');
    18. };

    Document#isSelected(path)

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

    Parameters:

    Returns:

    Example

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

    show code

    1. Document.prototype.isSelected = function isSelected(path) {
    2. if (this.$__.selected) {
    3. if (path === '_id') {
    4. return this.$__.selected._id !== 0;
    5. }
    6. var paths = Object.keys(this.$__.selected);
    7. var i = paths.length;
    8. var inclusive = null;
    9. var cur;
    10. if (i === 1 && paths[0] === '_id') {
    11. // only _id was selected.
    12. return this.$__.selected._id === 0;
    13. }
    14. while (i--) {
    15. cur = paths[i];
    16. if (cur === '_id') {
    17. continue;
    18. }
    19. if (!isDefiningProjection(this.$__.selected[cur])) {
    20. continue;
    21. }
    22. inclusive = !!this.$__.selected[cur];
    23. break;
    24. }
    25. if (inclusive === null) {
    26. return true;
    27. }
    28. if (path in this.$__.selected) {
    29. return inclusive;
    30. }
    31. i = paths.length;
    32. var pathDot = path + '.';
    33. while (i--) {
    34. cur = paths[i];
    35. if (cur === '_id') {
    36. continue;
    37. }
    38. if (cur.indexOf(pathDot) === 0) {
    39. return inclusive || cur !== pathDot;
    40. }
    41. if (pathDot.indexOf(cur + '.') === 0) {
    42. return inclusive;
    43. }
    44. }
    45. return !inclusive;
    46. }
    47. return true;
    48. };

    Document#markModified(path, [scope])

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

    Parameters:

    • path <String> the path to mark modified
    • [scope] <Document> the scope to run validators with

    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

    show code

    1. Document.prototype.markModified = function(path, scope) {
    2. this.$__.activePaths.modify(path);
    3. if (scope != null && !this.ownerDocument) {
    4. this.$__.pathsToScopes[path] = scope;
    5. }
    6. };

    Document#modifiedPaths()

    Returns the list of paths that have been modified.

    Returns:

    show code

    1. Document.prototype.modifiedPaths = function() {
    2. var directModifiedPaths = Object.keys(this.$__.activePaths.states.modify);
    3. return directModifiedPaths.reduce(function(list, path) {
    4. var parts = path.split('.');
    5. return list.concat(parts.reduce(function(chains, part, i) {
    6. return chains.concat(parts.slice(0, i).concat(part).join('.'));
    7. }, []).filter(function(chain) {
    8. return (list.indexOf(chain) === -1);
    9. }));
    10. }, []);
    11. };

    Document#populate([path], [callback])

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

    Parameters:

    • [path] <String, Object> The path to populate or an options object
    • [callback] <Function> When passed, population is invoked

    Returns:

    See:

    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.

    show code

    1. Document.prototype.populate = function populate() {
    2. if (arguments.length === 0) {
    3. return this;
    4. }
    5. var pop = this.$__.populate || (this.$__.populate = {});
    6. var args = utils.args(arguments);
    7. var fn;
    8. if (typeof args[args.length - 1] === 'function') {
    9. fn = args.pop();
    10. }
    11. // allow `doc.populate(callback)`
    12. if (args.length) {
    13. // use hash to remove duplicate paths
    14. var res = utils.populate.apply(null, args);
    15. for (var i = 0; i < res.length; ++i) {
    16. pop[res[i].path] = res[i];
    17. }
    18. }
    19. if (fn) {
    20. var paths = utils.object.vals(pop);
    21. this.$__.populate = undefined;
    22. paths.__noPromise = true;
    23. var topLevelModel = this.constructor;
    24. if (this.$__isNested) {
    25. topLevelModel = this.$__.scope.constructor;
    26. var nestedPath = this.$__.nestedPath;
    27. paths.forEach(function(populateOptions) {
    28. populateOptions.path = nestedPath + '.' + populateOptions.path;
    29. });
    30. }
    31. topLevelModel.populate(this, paths, fn);
    32. }
    33. return this;
    34. };

    Document#populated(path)

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

    Parameters:

    Returns:

    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.

    show code

    1. Document.prototype.populated = function(path, val, options) {
    2. // val and options are internal
    3. if (val === null || val === void 0) {
    4. if (!this.$__.populated) {
    5. return undefined;
    6. }
    7. var v = this.$__.populated[path];
    8. if (v) {
    9. return v.value;
    10. }
    11. return undefined;
    12. }
    13. // internal
    14. if (val === true) {
    15. if (!this.$__.populated) {
    16. return undefined;
    17. }
    18. return this.$__.populated[path];
    19. }
    20. this.$__.populated || (this.$__.populated = {});
    21. this.$__.populated[path] = {value: val, options: options};
    22. return val;
    23. };

    function Object() { [native code] }#save([options], [options.safe], [options.validateBeforeSave], [fn])%20%7B%20%5Bnative%20code%5D%20%7D-save)

    Saves this document.

    Parameters:

    Returns:

    See:

    Example:

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

    The callback will receive three parameters

    1. err if an error occurred
    2. product which is the saved product
    3. 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. });

    For legacy reasons, mongoose stores object keys in reverse order on initial
    save. That is, { a: 1, b: 2 } will be saved as { b: 2, a: 1 } in
    MongoDB. To override this behavior, set
    the toObject.retainKeyOrder option
    to true on your schema.


    (path, val, [type], [options])

    Sets the value of a path, or many paths.

    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

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

    show code

    1. Document.prototype.set = Document.prototype.$set;

    Document#setValue(path, value)

    Sets a raw value for a path (no casting, setters, transformations)

    Parameters:

    show code

    1. Document.prototype.setValue = function(path, val) {
    2. utils.setValue(path, val, this._doc);
    3. return this;
    4. };

    Document#toJSON(options)

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

    Parameters:

    Returns:

    See:

    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.

    show code

    1. Document.prototype.toJSON = function(options) {
    2. return this.$toObject(options, true);
    3. };

    Document#toObject([options])

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

    Parameters:

    Returns:

    See:

    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)
    • retainKeyOrder keep the order of object keys. If this is set to true, Object.keys(new Doc({ a: 1, b: 2}).toObject()) will always produce ['a', 'b'] (defaults to false)

    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.

    show code

    1. Document.prototype.toObject = function(options) {
    2. return this.$toObject(options);
    3. };

    Document#toString()

    Helper for console.log


    Document#unmarkModified(path)

    Clears the modified state on the specified path.

    Parameters:

    • path <String> the path to unmark modified

    Example:

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

    show code

    1. Document.prototype.unmarkModified = function(path) {
    2. this.$__.activePaths.init(path);
    3. delete this.$__.pathsToScopes[path];
    4. };

    Document#update(doc, options, callback)

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

    Parameters:

    Returns:

    See:

    Example:

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

    Valid options:

    show code

    1. Document.prototype.update = function update() {
    2. var args = utils.args(arguments);
    3. args.unshift({_id: this._id});
    4. return this.constructor.update.apply(this.constructor, args);
    5. };

    Document#validate(optional, callback)

    Executes registered validation rules for this document.

    Parameters:

    • optional <Object> options internal options
    • callback <Function> optional callback called after validation completes, passing an error if one occurred

    Returns:

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

    show code

    1. Document.prototype.validate = function(options, callback) {
    2. if (typeof options === 'function') {
    3. callback = options;
    4. options = null;
    5. }
    6. this.$__validate(callback || function() {});
    7. };

    Document#validateSync(pathsToValidate)

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

    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.

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

    show code

    1. Document.prototype.validateSync = function(pathsToValidate) {
    2. var _this = this;
    3. if (typeof pathsToValidate === 'string') {
    4. pathsToValidate = pathsToValidate.split(' ');
    5. }
    6. // only validate required fields when necessary
    7. var paths = _getPathsToValidate(this);
    8. if (pathsToValidate && pathsToValidate.length) {
    9. var tmp = [];
    10. for (var i = 0; i < paths.length; ++i) {
    11. if (pathsToValidate.indexOf(paths[i]) !== -1) {
    12. tmp.push(paths[i]);
    13. }
    14. }
    15. paths = tmp;
    16. }
    17. var validating = {};
    18. paths.forEach(function(path) {
    19. if (validating[path]) {
    20. return;
    21. }
    22. validating[path] = true;
    23. var p = _this.schema.path(path);
    24. if (!p) {
    25. return;
    26. }
    27. if (!_this.$isValid(path)) {
    28. return;
    29. }
    30. var val = _this.getValue(path);
    31. var err = p.doValidateSync(val, _this);
    32. if (err) {
    33. _this.invalidate(path, err, undefined, true);
    34. }
    35. });
    36. var err = _this.$__.validationError;
    37. _this.$__.validationError = undefined;
    38. _this.emit('validate', _this);
    39. _this.constructor.emit('validate', _this);
    40. if (err) {
    41. for (var key in err.errors) {
    42. // Make sure cast errors persist
    43. if (err.errors[key] instanceof MongooseError.CastError) {
    44. _this.invalidate(key, err.errors[key]);
    45. }
    46. }
    47. }
    48. return err;
    49. };

    Document.$isValid(path)

    Checks if a path is invalid

    Parameters:

    • path <String> the field to check

    Document.$markValid(path)

    Marks a path as valid, removing existing validation errors.

    Parameters:

    • path <String> the field to mark as valid

    Document#errors

    Hash containing current validation errors.

    show code

    1. Document.prototype.errors;

    Document#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 });

    show code

    1. Document.prototype.id;

    See:


    Document#isNew

    Boolean flag specifying if the document is new.

    show code

    1. Document.prototype.isNew;

    Document#schema

    The documents schema.

    show code

    1. Document.prototype.schema;

  • cursor/QueryCursor.js

    QueryCursor#addCursorFlag(flag, value)

    Adds a cursor flag.
    Useful for setting the noCursorTimeout and tailable flags.

    Parameters:

    Returns:


    QueryCursor#close(callback)

    Marks this cursor as closed. Will stop streaming and subsequent calls to
    next() will error.

    Parameters:

    Returns:

    See:


    QueryCursor#eachAsync(fn, [options], [options.parallel], [callback])

    Execute fn for every document in the cursor. If fn returns a promise,
    will wait for the promise to resolve before iterating on to the next one.
    Returns a promise that resolves when done.

    Parameters:

    • fn <Function>
    • [options] <Object>
    • [options.parallel] <Number> the number of promises to execute in parallel. Defaults to 1.
    • [callback] <Function> executed when all docs have been processed

    Returns:


    QueryCursor#map(fn)

    Registers a transform function which subsequently maps documents retrieved
    via the streams interface or .next()

    Parameters:

    Returns:

    Example

    1. // Map documents returned by `data` events
    2. Thing.
    3. find({ name: /^hello/ }).
    4. cursor().
    5. map(function (doc) {
    6. doc.foo = "bar";
    7. return doc;
    8. })
    9. on('data', function(doc) { console.log(doc.foo); });
    10. // Or map documents returned by `.next()`
    11. var cursor = Thing.find({ name: /^hello/ }).
    12. cursor().
    13. map(function (doc) {
    14. doc.foo = "bar";
    15. return doc;
    16. });
    17. cursor.next(function(error, doc) {
    18. console.log(doc.foo);
    19. });

    QueryCursor#next(callback)

    Get the next document from this cursor. Will return null when there are
    no documents left.

    Parameters:

    Returns:


    QueryCursor(query, options)

    A QueryCursor is a concurrency primitive for processing query results
    one document at a time. A QueryCursor fulfills the Node.js streams3 API,
    in addition to several other mechanisms for loading documents from MongoDB
    one at a time.

    Parameters:

    • query <Query>
    • options <Object> query options passed to .find()

    Inherits:

    Events:

    • cursor: Emitted when the cursor is created

    • error: Emitted when an error occurred

    • data: Emitted when the stream is flowing and the next doc is ready

    • end: Emitted when the stream is exhausted

    QueryCursors execute the model’s pre find hooks, but not the model’s
    post find hooks.

    Unless you’re an advanced user, do not instantiate this class directly.
    Use Query#cursor() instead.

    show code

    1. function QueryCursor(query, options) {
    2. Readable.call(this, { objectMode: true });
    3. this.cursor = null;
    4. this.query = query;
    5. this._transforms = options.transform ? [options.transform] : [];
    6. var _this = this;
    7. var model = query.model;
    8. model.hooks.execPre('find', query, function() {
    9. model.collection.find(query._conditions, options, function(err, cursor) {
    10. if (_this._error) {
    11. cursor.close(function() {});
    12. _this.listeners('error').length > 0 && _this.emit('error', _this._error);
    13. }
    14. if (err) {
    15. return _this.emit('error', err);
    16. }
    17. _this.cursor = cursor;
    18. _this.emit('cursor', cursor);
    19. });
    20. });
    21. }
    22. util.inherits(QueryCursor, Readable);

  • cursor/AggregationCursor.js

    AggregationCursor#addCursorFlag(flag, value)

    Adds a cursor flag.
    Useful for setting the noCursorTimeout and tailable flags.

    Parameters:

    Returns:


    AggregationCursor(agg, options)

    An AggregationCursor is a concurrency primitive for processing aggregation
    results one document at a time. It is analogous to QueryCursor.

    Parameters:

    Inherits:

    Events:

    • cursor: Emitted when the cursor is created

    • error: Emitted when an error occurred

    • data: Emitted when the stream is flowing and the next doc is ready

    • end: Emitted when the stream is exhausted

    An AggregationCursor fulfills the Node.js streams3 API,
    in addition to several other mechanisms for loading documents from MongoDB
    one at a time.

    Creating an AggregationCursor executes the model’s pre aggregate hooks,
    but not the model’s post aggregate hooks.

    Unless you’re an advanced user, do not instantiate this class directly.
    Use Aggregate#cursor() instead.

    show code

    1. function AggregationCursor(agg) {
    2. Readable.call(this, { objectMode: true });
    3. this.cursor = null;
    4. this.agg = agg;
    5. this._transforms = [];
    6. var model = agg._model;
    7. delete agg.options.cursor.useMongooseAggCursor;
    8. _init(model, this, agg);
    9. }
    10. util.inherits(AggregationCursor, Readable);

    AggregationCursor#close(callback)

    Marks this cursor as closed. Will stop streaming and subsequent calls to
    next() will error.

    Parameters:

    Returns:

    See:


    AggregationCursor#eachAsync(fn, [callback])

    Execute fn for every document in the cursor. If fn returns a promise,
    will wait for the promise to resolve before iterating on to the next one.
    Returns a promise that resolves when done.

    Parameters:

    Returns:


    AggregationCursor#map(fn)

    Registers a transform function which subsequently maps documents retrieved
    via the streams interface or .next()

    Parameters:

    Returns:

    Example

    1. // Map documents returned by `data` events
    2. Thing.
    3. find({ name: /^hello/ }).
    4. cursor().
    5. map(function (doc) {
    6. doc.foo = "bar";
    7. return doc;
    8. })
    9. on('data', function(doc) { console.log(doc.foo); });
    10. // Or map documents returned by `.next()`
    11. var cursor = Thing.find({ name: /^hello/ }).
    12. cursor().
    13. map(function (doc) {
    14. doc.foo = "bar";
    15. return doc;
    16. });
    17. cursor.next(function(error, doc) {
    18. console.log(doc.foo);
    19. });

    AggregationCursor#next(callback)

    Get the next document from this cursor. Will return null when there are
    no documents left.

    Parameters:

    Returns:


  • schema/boolean.js

    SchemaBoolean#cast(value, model)

    Casts to boolean

    Parameters:

    show code

    1. SchemaBoolean.prototype.cast = function(value, model) {
    2. if (value === null) {
    3. return value;
    4. }
    5. if (this.options.strictBool || (model && model.schema.options.strictBool && this.options.strictBool !== false)) {
    6. // strict mode (throws if value is not a boolean, instead of converting)
    7. if (value === true || value === 'true' || value === 1 || value === '1') {
    8. return true;
    9. }
    10. if (value === false || value === 'false' || value === 0 || value === '0') {
    11. return false;
    12. }
    13. throw new CastError('boolean', value, this.path);
    14. } else {
    15. // legacy mode
    16. if (value === '0') {
    17. return false;
    18. }
    19. if (value === 'true') {
    20. return true;
    21. }
    22. if (value === 'false') {
    23. return false;
    24. }
    25. return !!value;
    26. }
    27. };
    28. SchemaBoolean.$conditionalHandlers =
    29. utils.options(SchemaType.prototype.$conditionalHandlers, {});

    SchemaBoolean#castForQuery($conditional, val)

    Casts contents for queries.

    Parameters:

    show code

    1. SchemaBoolean.prototype.castForQuery = function($conditional, val) {
    2. var handler;
    3. if (arguments.length === 2) {
    4. handler = SchemaBoolean.$conditionalHandlers[$conditional];
    5. if (handler) {
    6. return handler.call(this, val);
    7. }
    8. return this._castForQuery(val);
    9. }
    10. return this._castForQuery($conditional);
    11. };

    SchemaBoolean#checkRequired(value)

    Check if the given value satisfies a required validator. For a boolean
    to satisfy a required validator, it must be strictly equal to true or to
    false.

    Parameters:

    Returns:

    show code

    1. SchemaBoolean.prototype.checkRequired = function(value) {
    2. return value === true || value === false;
    3. };

    SchemaBoolean(path, options)

    Boolean SchemaType constructor.

    Parameters:

    Inherits:

    show code

    1. function SchemaBoolean(path, options) {
    2. SchemaType.call(this, path, options, 'Boolean');
    3. }

    SchemaBoolean.schemaName

    This schema type’s name, to defend against minifiers that mangle
    function names.

    show code

    1. SchemaBoolean.schemaName = 'Boolean';

  • schema/documentarray.js

    DocumentArray#cast(value, document)

    Casts contents

    Parameters:

    show code

    1. DocumentArray.prototype.cast = function(value, doc, init, prev, options) {
    2. // lazy load
    3. MongooseDocumentArray || (MongooseDocumentArray = require('../types/documentarray'));
    4. var selected;
    5. var subdoc;
    6. var i;
    7. var _opts = { transform: false, virtuals: false };
    8. if (!Array.isArray(value)) {
    9. // gh-2442 mark whole array as modified if we're initializing a doc from
    10. // the db and the path isn't an array in the document
    11. if (!!doc && init) {
    12. doc.markModified(this.path);
    13. }
    14. return this.cast([value], doc, init, prev);
    15. }
    16. if (!(value && value.isMongooseDocumentArray) &&
    17. (!options || !options.skipDocumentArrayCast)) {
    18. value = new MongooseDocumentArray(value, this.path, doc);
    19. if (prev && prev._handlers) {
    20. for (var key in prev._handlers) {
    21. doc.removeListener(key, prev._handlers[key]);
    22. }
    23. }
    24. } else if (value && value.isMongooseDocumentArray) {
    25. // We need to create a new array, otherwise change tracking will
    26. // update the old doc (gh-4449)
    27. value = new MongooseDocumentArray(value, this.path, doc);
    28. }
    29. i = value.length;
    30. while (i--) {
    31. if (!value[i]) {
    32. continue;
    33. }
    34. var Constructor = this.casterConstructor;
    35. if (Constructor.discriminators &&
    36. typeof value[i][Constructor.schema.options.discriminatorKey] === 'string' &&
    37. Constructor.discriminators[value[i][Constructor.schema.options.discriminatorKey]]) {
    38. Constructor = Constructor.discriminators[value[i][Constructor.schema.options.discriminatorKey]];
    39. }
    40. // Check if the document has a different schema (re gh-3701)
    41. if ((value[i] instanceof Document) &&
    42. value[i].schema !== Constructor.schema) {
    43. value[i] = value[i].toObject({ transform: false, virtuals: false });
    44. }
    45. if (!(value[i] instanceof Subdocument) && value[i]) {
    46. if (init) {
    47. if (doc) {
    48. selected || (selected = scopePaths(this, doc.$__.selected, init));
    49. } else {
    50. selected = true;
    51. }
    52. subdoc = new Constructor(null, value, true, selected, i);
    53. value[i] = subdoc.init(value[i]);
    54. } else {
    55. if (prev && (subdoc = prev.id(value[i]._id))) {
    56. subdoc = prev.id(value[i]._id);
    57. }
    58. if (prev && subdoc && utils.deepEqual(subdoc.toObject(_opts), value[i])) {
    59. // handle resetting doc with existing id and same data
    60. subdoc.set(value[i]);
    61. // if set() is hooked it will have no return value
    62. // see gh-746
    63. value[i] = subdoc;
    64. } else {
    65. try {
    66. subdoc = new Constructor(value[i], value, undefined,
    67. undefined, i);
    68. // if set() is hooked it will have no return value
    69. // see gh-746
    70. value[i] = subdoc;
    71. } catch (error) {
    72. var valueInErrorMessage = util.inspect(value[i]);
    73. throw new CastError('embedded', valueInErrorMessage,
    74. value._path, error);
    75. }
    76. }
    77. }
    78. }
    79. }
    80. return value;
    81. };

    DocumentArray(key, schema, options)

    SubdocsArray SchemaType constructor

    Parameters:

    Inherits:

    show code

    1. function DocumentArray(key, schema, options) {
    2. var EmbeddedDocument = _createConstructor(schema, options);
    3. EmbeddedDocument.prototype.$basePath = key;
    4. ArrayType.call(this, key, EmbeddedDocument, options);
    5. this.schema = schema;
    6. this.$isMongooseDocumentArray = true;
    7. var fn = this.defaultValue;
    8. if (!('defaultValue' in this) || fn !== void 0) {
    9. this.default(function() {
    10. var arr = fn.call(this);
    11. if (!Array.isArray(arr)) {
    12. arr = [arr];
    13. }
    14. // Leave it up to `cast()` to convert this to a documentarray
    15. return arr;
    16. });
    17. }
    18. }

    DocumentArray#doValidate()

    Performs local validations first, then validations on each embedded doc

    show code

    1. DocumentArray.prototype.doValidate = function(array, fn, scope, options) {
    2. // lazy load
    3. MongooseDocumentArray || (MongooseDocumentArray = require('../types/documentarray'));
    4. var _this = this;
    5. SchemaType.prototype.doValidate.call(this, array, function(err) {
    6. if (err) {
    7. return fn(err);
    8. }
    9. var count = array && array.length;
    10. var error;
    11. if (!count) {
    12. return fn();
    13. }
    14. if (options && options.updateValidator) {
    15. return fn();
    16. }
    17. if (!array.isMongooseDocumentArray) {
    18. array = new MongooseDocumentArray(array, _this.path, scope);
    19. }
    20. // handle sparse arrays, do not use array.forEach which does not
    21. // iterate over sparse elements yet reports array.length including
    22. // them :(
    23. function callback(err) {
    24. if (err) {
    25. error = err;
    26. }
    27. --count || fn(error);
    28. }
    29. for (var i = 0, len = count; i < len; ++i) {
    30. // sidestep sparse entries
    31. var doc = array[i];
    32. if (!doc) {
    33. --count || fn(error);
    34. continue;
    35. }
    36. // If you set the array index directly, the doc might not yet be
    37. // a full fledged mongoose subdoc, so make it into one.
    38. if (!(doc instanceof Subdocument)) {
    39. doc = array[i] = new _this.casterConstructor(doc, array, undefined,
    40. undefined, i);
    41. }
    42. // HACK: use $__original_validate to avoid promises so bluebird doesn't
    43. // complain
    44. if (doc.$__original_validate) {
    45. doc.$__original_validate({__noPromise: true}, callback);
    46. } else {
    47. doc.validate({__noPromise: true}, callback);
    48. }
    49. }
    50. }, scope);
    51. };

    DocumentArray#doValidateSync()

    Performs local validations first, then validations on each embedded doc.

    Returns:

    Note:

    This method ignores the asynchronous validators.

    show code

    1. DocumentArray.prototype.doValidateSync = function(array, scope) {
    2. var schemaTypeError = SchemaType.prototype.doValidateSync.call(this, array, scope);
    3. if (schemaTypeError) {
    4. return schemaTypeError;
    5. }
    6. var count = array && array.length,
    7. resultError = null;
    8. if (!count) {
    9. return;
    10. }
    11. // handle sparse arrays, do not use array.forEach which does not
    12. // iterate over sparse elements yet reports array.length including
    13. // them :(
    14. for (var i = 0, len = count; i < len; ++i) {
    15. // only first error
    16. if (resultError) {
    17. break;
    18. }
    19. // sidestep sparse entries
    20. var doc = array[i];
    21. if (!doc) {
    22. continue;
    23. }
    24. // If you set the array index directly, the doc might not yet be
    25. // a full fledged mongoose subdoc, so make it into one.
    26. if (!(doc instanceof Subdocument)) {
    27. doc = array[i] = new this.casterConstructor(doc, array, undefined,
    28. undefined, i);
    29. }
    30. var subdocValidateError = doc.validateSync();
    31. if (subdocValidateError) {
    32. resultError = subdocValidateError;
    33. }
    34. }
    35. return resultError;
    36. };

    DocumentArray.schemaName

    This schema type’s name, to defend against minifiers that mangle
    function names.

    show code

    1. DocumentArray.schemaName = 'DocumentArray';

  • schema/array.js

    SchemaArray#applyGetters(value, scope)

    Overrides the getters application for the population special-case

    Parameters:

    show code

    1. SchemaArray.prototype.applyGetters = function(value, scope) {
    2. if (this.caster.options && this.caster.options.ref) {
    3. // means the object id was populated
    4. return value;
    5. }
    6. return SchemaType.prototype.applyGetters.call(this, value, scope);
    7. };

    SchemaArray#cast(value, doc, init)

    Casts values for set().

    Parameters:

    • value <Object>
    • doc <Document> document that triggers the casting
    • init <Boolean> whether this is an initialization cast

    show code

    1. SchemaArray.prototype.cast = function(value, doc, init) {
    2. // lazy load
    3. MongooseArray || (MongooseArray = require('../types').Array);
    4. if (Array.isArray(value)) {
    5. if (!value.length && doc) {
    6. var indexes = doc.schema.indexedPaths();
    7. for (var i = 0, l = indexes.length; i < l; ++i) {
    8. var pathIndex = indexes[i][0][this.path];
    9. if (pathIndex === '2dsphere' || pathIndex === '2d') {
    10. return;
    11. }
    12. }
    13. }
    14. if (!(value && value.isMongooseArray)) {
    15. value = new MongooseArray(value, this.path, doc);
    16. } else if (value && value.isMongooseArray) {
    17. // We need to create a new array, otherwise change tracking will
    18. // update the old doc (gh-4449)
    19. value = new MongooseArray(value, this.path, doc);
    20. }
    21. if (this.caster) {
    22. try {
    23. for (i = 0, l = value.length; i < l; i++) {
    24. value[i] = this.caster.cast(value[i], doc, init);
    25. }
    26. } catch (e) {
    27. // rethrow
    28. throw new CastError('[' + e.kind + ']', util.inspect(value), this.path, e);
    29. }
    30. }
    31. return value;
    32. }
    33. // gh-2442: if we're loading this from the db and its not an array, mark
    34. // the whole array as modified.
    35. if (!!doc && !!init) {
    36. doc.markModified(this.path);
    37. }
    38. return this.cast([value], doc, init);
    39. };

    SchemaArray#castForQuery($conditional, [value])

    Casts values for queries.

    Parameters:

    • $conditional <String>
    • [value] <T>

    show code

    1. SchemaArray.prototype.castForQuery = function($conditional, value) {
    2. var handler,
    3. val;
    4. if (arguments.length === 2) {
    5. handler = this.$conditionalHandlers[$conditional];
    6. if (!handler) {
    7. throw new Error('Can\'t use ' + $conditional + ' with Array.');
    8. }
    9. val = handler.call(this, value);
    10. } else {
    11. val = $conditional;
    12. var Constructor = this.casterConstructor;
    13. if (val &&
    14. Constructor.discriminators &&
    15. Constructor.schema.options.discriminatorKey &&
    16. typeof val[Constructor.schema.options.discriminatorKey] === 'string' &&
    17. Constructor.discriminators[val[Constructor.schema.options.discriminatorKey]]) {
    18. Constructor = Constructor.discriminators[val[Constructor.schema.options.discriminatorKey]];
    19. }
    20. var proto = this.casterConstructor.prototype;
    21. var method = proto && (proto.castForQuery || proto.cast);
    22. if (!method && Constructor.castForQuery) {
    23. method = Constructor.castForQuery;
    24. }
    25. var caster = this.caster;
    26. if (Array.isArray(val)) {
    27. val = val.map(function(v) {
    28. if (utils.isObject(v) && v.$elemMatch) {
    29. return v;
    30. }
    31. if (method) {
    32. v = method.call(caster, v);
    33. return v;
    34. }
    35. if (v != null) {
    36. v = new Constructor(v);
    37. return v;
    38. }
    39. return v;
    40. });
    41. } else if (method) {
    42. val = method.call(caster, val);
    43. } else if (val != null) {
    44. val = new Constructor(val);
    45. }
    46. }
    47. return val;
    48. };
    49. function cast$all(val) {
    50. if (!Array.isArray(val)) {
    51. val = [val];
    52. }
    53. val = val.map(function(v) {
    54. if (utils.isObject(v)) {
    55. var o = {};
    56. o[this.path] = v;
    57. return cast(this.casterConstructor.schema, o)[this.path];
    58. }
    59. return v;
    60. }, this);
    61. return this.castForQuery(val);
    62. }
    63. function cast$elemMatch(val) {
    64. var keys = Object.keys(val);
    65. var numKeys = keys.length;
    66. var key;
    67. var value;
    68. for (var i = 0; i < numKeys; ++i) {
    69. key = keys[i];
    70. value = val[key];
    71. if (key.indexOf('$') === 0 && value) {
    72. val[key] = this.castForQuery(key, value);
    73. }
    74. }
    75. return cast(this.casterConstructor.schema, val);
    76. }
    77. var handle = SchemaArray.prototype.$conditionalHandlers = {};
    78. handle.$all = cast$all;
    79. handle.$options = String;
    80. handle.$elemMatch = cast$elemMatch;
    81. handle.$geoIntersects = geospatial.cast$geoIntersects;
    82. handle.$or = handle.$and = function(val) {
    83. if (!Array.isArray(val)) {
    84. throw new TypeError('conditional $or/$and require array');
    85. }
    86. var ret = [];
    87. for (var i = 0; i < val.length; ++i) {
    88. ret.push(cast(this.casterConstructor.schema, val[i]));
    89. }
    90. return ret;
    91. };
    92. handle.$near =
    93. handle.$nearSphere = geospatial.cast$near;
    94. handle.$within =
    95. handle.$geoWithin = geospatial.cast$within;
    96. handle.$size =
    97. handle.$minDistance =
    98. handle.$maxDistance = castToNumber;
    99. handle.$exists = $exists;
    100. handle.$type = $type;
    101. handle.$eq =
    102. handle.$gt =
    103. handle.$gte =
    104. handle.$in =
    105. handle.$lt =
    106. handle.$lte =
    107. handle.$ne =
    108. handle.$nin =
    109. handle.$regex = SchemaArray.prototype.castForQuery;

    SchemaArray#checkRequired(value)

    Check if the given value satisfies a required validator. The given value
    must be not null nor undefined, and have a positive length.

    Parameters:

    Returns:

    show code

    1. SchemaArray.prototype.checkRequired = function(value) {
    2. return !!(value && value.length);
    3. };

    SchemaArray(key, cast, options)

    Array SchemaType constructor

    Parameters:

    Inherits:

    show code

    1. function SchemaArray(key, cast, options, schemaOptions) {
    2. // lazy load
    3. EmbeddedDoc || (EmbeddedDoc = require('../types').Embedded);
    4. var typeKey = 'type';
    5. if (schemaOptions && schemaOptions.typeKey) {
    6. typeKey = schemaOptions.typeKey;
    7. }
    8. if (cast) {
    9. var castOptions = {};
    10. if (utils.getFunctionName(cast.constructor) === 'Object') {
    11. if (cast[typeKey]) {
    12. // support { type: Woot }
    13. castOptions = utils.clone(cast); // do not alter user arguments
    14. delete castOptions[typeKey];
    15. cast = cast[typeKey];
    16. } else {
    17. cast = Mixed;
    18. }
    19. }
    20. // support { type: 'String' }
    21. var name = typeof cast === 'string'
    22. ? cast
    23. : utils.getFunctionName(cast);
    24. var caster = name in Types
    25. ? Types[name]
    26. : cast;
    27. this.casterConstructor = caster;
    28. if (typeof caster === 'function' && !caster.$isArraySubdocument) {
    29. this.caster = new caster(null, castOptions);
    30. } else {
    31. this.caster = caster;
    32. }
    33. if (!(this.caster instanceof EmbeddedDoc)) {
    34. this.caster.path = key;
    35. }
    36. }
    37. this.$isMongooseArray = true;
    38. SchemaType.call(this, key, options, 'Array');
    39. var defaultArr;
    40. var fn;
    41. if (this.defaultValue != null) {
    42. defaultArr = this.defaultValue;
    43. fn = typeof defaultArr === 'function';
    44. }
    45. if (!('defaultValue' in this) || this.defaultValue !== void 0) {
    46. this.default(function() {
    47. var arr = [];
    48. if (fn) {
    49. arr = defaultArr();
    50. } else if (defaultArr != null) {
    51. arr = arr.concat(defaultArr);
    52. }
    53. // Leave it up to `cast()` to convert the array
    54. return arr;
    55. });
    56. }
    57. }

    SchemaArray.schemaName

    This schema type’s name, to defend against minifiers that mangle
    function names.

    show code

    1. SchemaArray.schemaName = 'Array';

  • schema/decimal128.js

    Decimal128#cast(value, doc, init)

    Casts to Decimal128

    Parameters:

    show code

    1. Decimal128.prototype.cast = function(value, doc, init) {
    2. if (SchemaType._isRef(this, value, doc, init)) {
    3. // wait! we may need to cast this to a document
    4. if (value === null || value === undefined) {
    5. return value;
    6. }
    7. // lazy load
    8. Document || (Document = require('./../document'));
    9. if (value instanceof Document) {
    10. value.$__.wasPopulated = true;
    11. return value;
    12. }
    13. // setting a populated path
    14. if (value instanceof Decimal128Type) {
    15. return value;
    16. } else if (Buffer.isBuffer(value) || !utils.isObject(value)) {
    17. throw new CastError('Decimal128', value, this.path);
    18. }
    19. // Handle the case where user directly sets a populated
    20. // path to a plain object; cast to the Model used in
    21. // the population query.
    22. var path = doc.$__fullPath(this.path);
    23. var owner = doc.ownerDocument ? doc.ownerDocument() : doc;
    24. var pop = owner.populated(path, true);
    25. var ret = value;
    26. if (!doc.$__.populated ||
    27. !doc.$__.populated[path] ||
    28. !doc.$__.populated[path].options ||
    29. !doc.$__.populated[path].options.options ||
    30. !doc.$__.populated[path].options.options.lean) {
    31. ret = new pop.options.model(value);
    32. ret.$__.wasPopulated = true;
    33. }
    34. return ret;
    35. }
    36. if (value == null) {
    37. return value;
    38. }
    39. if (typeof value === 'object' && typeof value.$numberDecimal === 'string') {
    40. return Decimal128Type.fromString(value.$numberDecimal);
    41. }
    42. if (value instanceof Decimal128Type) {
    43. return value;
    44. }
    45. if (typeof value === 'string') {
    46. return Decimal128Type.fromString(value);
    47. }
    48. if (Buffer.isBuffer(value)) {
    49. return new Decimal128Type(value);
    50. }
    51. throw new CastError('Decimal128', value, this.path);
    52. };

    Decimal128#checkRequired(value, doc)

    Check if the given value satisfies a required validator.

    Parameters:

    Returns:

    show code

    1. Decimal128.prototype.checkRequired = function checkRequired(value, doc) {
    2. if (SchemaType._isRef(this, value, doc, true)) {
    3. return !!value;
    4. }
    5. return value instanceof Decimal128Type;
    6. };

    Decimal128(key, options)

    Decimal128 SchemaType constructor.

    Parameters:

    Inherits:

    show code

    1. function Decimal128(key, options) {
    2. SchemaType.call(this, key, options, 'Decimal128');
    3. }

    Decimal128.schemaName

    This schema type’s name, to defend against minifiers that mangle
    function names.

    show code

    1. Decimal128.schemaName = 'Decimal128';

  • schema/number.js

    SchemaNumber#cast(value, doc, init)

    Casts to number

    Parameters:

    show code

    1. SchemaNumber.prototype.cast = function(value, doc, init) {
    2. if (SchemaType._isRef(this, value, doc, init)) {
    3. // wait! we may need to cast this to a document
    4. if (value === null || value === undefined) {
    5. return value;
    6. }
    7. // lazy load
    8. Document || (Document = require('./../document'));
    9. if (value instanceof Document) {
    10. value.$__.wasPopulated = true;
    11. return value;
    12. }
    13. // setting a populated path
    14. if (typeof value === 'number') {
    15. return value;
    16. } else if (Buffer.isBuffer(value) || !utils.isObject(value)) {
    17. throw new CastError('number', value, this.path);
    18. }
    19. // Handle the case where user directly sets a populated
    20. // path to a plain object; cast to the Model used in
    21. // the population query.
    22. var path = doc.$__fullPath(this.path);
    23. var owner = doc.ownerDocument ? doc.ownerDocument() : doc;
    24. var pop = owner.populated(path, true);
    25. var ret = new pop.options.model(value);
    26. ret.$__.wasPopulated = true;
    27. return ret;
    28. }
    29. var val = value && typeof value._id !== 'undefined' ?
    30. value._id : // documents
    31. value;
    32. if (!isNaN(val)) {
    33. if (val === null) {
    34. return val;
    35. }
    36. if (val === '') {
    37. return null;
    38. }
    39. if (typeof val === 'string' || typeof val === 'boolean') {
    40. val = Number(val);
    41. }
    42. if (val instanceof Number) {
    43. return val;
    44. }
    45. if (typeof val === 'number') {
    46. return val;
    47. }
    48. if (val.toString && !Array.isArray(val) && val.toString() == Number(val)) {
    49. return new Number(val);
    50. }
    51. }
    52. throw new CastError('number', value, this.path);
    53. };

    SchemaNumber#castForQuery($conditional, [value])

    Casts contents for queries.

    Parameters:

    • $conditional <String>
    • [value] <T>

    show code

    1. SchemaNumber.prototype.castForQuery = function($conditional, val) {
    2. var handler;
    3. if (arguments.length === 2) {
    4. handler = this.$conditionalHandlers[$conditional];
    5. if (!handler) {
    6. throw new Error('Can\'t use ' + $conditional + ' with Number.');
    7. }
    8. return handler.call(this, val);
    9. }
    10. val = this._castForQuery($conditional);
    11. return val;
    12. };

    SchemaNumber#checkRequired(value, doc)

    Check if the given value satisfies a required validator.

    Parameters:

    Returns:

    show code

    1. SchemaNumber.prototype.checkRequired = function checkRequired(value, doc) {
    2. if (SchemaType._isRef(this, value, doc, true)) {
    3. return !!value;
    4. }
    5. return typeof value === 'number' || value instanceof Number;
    6. };

    SchemaNumber#max(maximum, [message])

    Sets a maximum number validator.

    Parameters:

    • maximum <Number> number
    • [message] <String> optional custom error message

    Returns:

    See:

    Example:

    1. var s = new Schema({ n: { type: Number, max: 10 })
    2. var M = db.model('M', s)
    3. var m = new M({ n: 11 })
    4. m.save(function (err) {
    5. console.error(err) // validator error
    6. m.n = 10;
    7. m.save() // success
    8. })
    9. // custom error messages
    10. // We can also use the special {MAX} token which will be replaced with the invalid value
    11. var max = [10, 'The value of path `{PATH}` ({VALUE}) exceeds the limit ({MAX}).'];
    12. var schema = new Schema({ n: { type: Number, max: max })
    13. var M = mongoose.model('Measurement', schema);
    14. var s= new M({ n: 4 });
    15. s.validate(function (err) {
    16. console.log(String(err)) // ValidationError: The value of path `n` (4) exceeds the limit (10).
    17. })

    show code

    1. SchemaNumber.prototype.max = function(value, message) {
    2. if (this.maxValidator) {
    3. this.validators = this.validators.filter(function(v) {
    4. return v.validator !== this.maxValidator;
    5. }, this);
    6. }
    7. if (value !== null && value !== undefined) {
    8. var msg = message || MongooseError.messages.Number.max;
    9. msg = msg.replace(/{MAX}/, value);
    10. this.validators.push({
    11. validator: this.maxValidator = function(v) {
    12. return v == null || v <= value;
    13. },
    14. message: msg,
    15. type: 'max',
    16. max: value
    17. });
    18. }
    19. return this;
    20. };

    SchemaNumber#min(value, [message])

    Sets a minimum number validator.

    Parameters:

    • value <Number> minimum number
    • [message] <String> optional custom error message

    Returns:

    See:

    Example:

    1. var s = new Schema({ n: { type: Number, min: 10 })
    2. var M = db.model('M', s)
    3. var m = new M({ n: 9 })
    4. m.save(function (err) {
    5. console.error(err) // validator error
    6. m.n = 10;
    7. m.save() // success
    8. })
    9. // custom error messages
    10. // We can also use the special {MIN} token which will be replaced with the invalid value
    11. var min = [10, 'The value of path `{PATH}` ({VALUE}) is beneath the limit ({MIN}).'];
    12. var schema = new Schema({ n: { type: Number, min: min })
    13. var M = mongoose.model('Measurement', schema);
    14. var s= new M({ n: 4 });
    15. s.validate(function (err) {
    16. console.log(String(err)) // ValidationError: The value of path `n` (4) is beneath the limit (10).
    17. })

    show code

    1. SchemaNumber.prototype.min = function(value, message) {
    2. if (this.minValidator) {
    3. this.validators = this.validators.filter(function(v) {
    4. return v.validator !== this.minValidator;
    5. }, this);
    6. }
    7. if (value !== null && value !== undefined) {
    8. var msg = message || MongooseError.messages.Number.min;
    9. msg = msg.replace(/{MIN}/, value);
    10. this.validators.push({
    11. validator: this.minValidator = function(v) {
    12. return v == null || v >= value;
    13. },
    14. message: msg,
    15. type: 'min',
    16. min: value
    17. });
    18. }
    19. return this;
    20. };

    SchemaNumber(key, options)

    Number SchemaType constructor.

    Parameters:

    Inherits:

    show code

    1. function SchemaNumber(key, options) {
    2. SchemaType.call(this, key, options, 'Number');
    3. }

    SchemaNumber.schemaName

    This schema type’s name, to defend against minifiers that mangle
    function names.

    show code

    1. SchemaNumber.schemaName = 'Number';

  • schema/objectid.js

    ObjectId#auto(turnOn)

    Adds an auto-generated ObjectId default if turnOn is true.

    Parameters:

    • turnOn <Boolean> auto generated ObjectId defaults

    Returns:

    show code

    1. ObjectId.prototype.auto = function(turnOn) {
    2. if (turnOn) {
    3. this.default(defaultId);
    4. this.set(resetId);
    5. }
    6. return this;
    7. };

    ObjectId#cast(value, doc, init)

    Casts to ObjectId

    Parameters:

    show code

    1. ObjectId.prototype.cast = function(value, doc, init) {
    2. if (SchemaType._isRef(this, value, doc, init)) {
    3. // wait! we may need to cast this to a document
    4. if (value === null || value === undefined) {
    5. return value;
    6. }
    7. // lazy load
    8. Document || (Document = require('./../document'));
    9. if (value instanceof Document) {
    10. value.$__.wasPopulated = true;
    11. return value;
    12. }
    13. // setting a populated path
    14. if (value instanceof oid) {
    15. return value;
    16. } else if ((value.constructor.name || '').toLowerCase() === 'objectid') {
    17. return new oid(value.toHexString());
    18. } else if (Buffer.isBuffer(value) || !utils.isObject(value)) {
    19. throw new CastError('ObjectId', value, this.path);
    20. }
    21. // Handle the case where user directly sets a populated
    22. // path to a plain object; cast to the Model used in
    23. // the population query.
    24. var path = doc.$__fullPath(this.path);
    25. var owner = doc.ownerDocument ? doc.ownerDocument() : doc;
    26. var pop = owner.populated(path, true);
    27. var ret = value;
    28. if (!doc.$__.populated ||
    29. !doc.$__.populated[path] ||
    30. !doc.$__.populated[path].options ||
    31. !doc.$__.populated[path].options.options ||
    32. !doc.$__.populated[path].options.options.lean) {
    33. ret = new pop.options.model(value);
    34. ret.$__.wasPopulated = true;
    35. }
    36. return ret;
    37. }
    38. if (value === null || value === undefined) {
    39. return value;
    40. }
    41. if (value instanceof oid) {
    42. return value;
    43. }
    44. if (value._id) {
    45. if (value._id instanceof oid) {
    46. return value._id;
    47. }
    48. if (value._id.toString instanceof Function) {
    49. try {
    50. return new oid(value._id.toString());
    51. } catch (e) {
    52. }
    53. }
    54. }
    55. if (value.toString instanceof Function) {
    56. try {
    57. return new oid(value.toString());
    58. } catch (err) {
    59. throw new CastError('ObjectId', value, this.path);
    60. }
    61. }
    62. throw new CastError('ObjectId', value, this.path);
    63. };

    ObjectId#castForQuery($conditional, [val])

    Casts contents for queries.

    Parameters:

    • $conditional <String>
    • [val] <T>

    show code

    1. ObjectId.prototype.castForQuery = function($conditional, val) {
    2. var handler;
    3. if (arguments.length === 2) {
    4. handler = this.$conditionalHandlers[$conditional];
    5. if (!handler) {
    6. throw new Error('Can\'t use ' + $conditional + ' with ObjectId.');
    7. }
    8. return handler.call(this, val);
    9. }
    10. return this._castForQuery($conditional);
    11. };

    ObjectId#checkRequired(value, doc)

    Check if the given value satisfies a required validator.

    Parameters:

    Returns:

    show code

    1. ObjectId.prototype.checkRequired = function checkRequired(value, doc) {
    2. if (SchemaType._isRef(this, value, doc, true)) {
    3. return !!value;
    4. }
    5. return value instanceof oid;
    6. };

    ObjectId(key, options)

    ObjectId SchemaType constructor.

    Parameters:

    Inherits:

    show code

    1. function ObjectId(key, options) {
    2. var isKeyHexStr = typeof key === 'string' && key.length === 24 && /^a-f0-9$/i.test(key);
    3. var suppressWarning = options && options.suppressWarning;
    4. if ((isKeyHexStr || typeof key === 'undefined') && !suppressWarning) {
    5. console.warn('mongoose: To create a new ObjectId please try ' +
    6. '`Mongoose.Types.ObjectId` instead of using ' +
    7. '`Mongoose.Schema.ObjectId`. Set the `suppressWarning` option if ' +
    8. 'you\'re trying to create a hex char path in your schema.');
    9. console.trace();
    10. }
    11. SchemaType.call(this, key, options, 'ObjectID');
    12. }

    ObjectId.schemaName

    This schema type’s name, to defend against minifiers that mangle
    function names.

    show code

    1. ObjectId.schemaName = 'ObjectId';

  • schema/string.js

    SchemaString#cast()

    Casts to String

    show code

    1. SchemaString.prototype.cast = function(value, doc, init) {
    2. if (SchemaType._isRef(this, value, doc, init)) {
    3. // wait! we may need to cast this to a document
    4. if (value === null || value === undefined) {
    5. return value;
    6. }
    7. // lazy load
    8. Document || (Document = require('./../document'));
    9. if (value instanceof Document) {
    10. value.$__.wasPopulated = true;
    11. return value;
    12. }
    13. // setting a populated path
    14. if (typeof value === 'string') {
    15. return value;
    16. } else if (Buffer.isBuffer(value) || !utils.isObject(value)) {
    17. throw new CastError('string', value, this.path);
    18. }
    19. // Handle the case where user directly sets a populated
    20. // path to a plain object; cast to the Model used in
    21. // the population query.
    22. var path = doc.$__fullPath(this.path);
    23. var owner = doc.ownerDocument ? doc.ownerDocument() : doc;
    24. var pop = owner.populated(path, true);
    25. var ret = new pop.options.model(value);
    26. ret.$__.wasPopulated = true;
    27. return ret;
    28. }
    29. // If null or undefined
    30. if (value === null || value === undefined) {
    31. return value;
    32. }
    33. if (typeof value !== 'undefined') {
    34. // handle documents being passed
    35. if (value._id && typeof value._id === 'string') {
    36. return value._id;
    37. }
    38. // Re: gh-647 and gh-3030, we're ok with casting using `toString()`
    39. // **unless** its the default Object.toString, because "[object Object]"
    40. // doesn't really qualify as useful data
    41. if (value.toString && value.toString !== Object.prototype.toString) {
    42. return value.toString();
    43. }
    44. }
    45. throw new CastError('string', value, this.path);
    46. };

    SchemaString#castForQuery($conditional, [val])

    Casts contents for queries.

    Parameters:

    • $conditional <String>
    • [val] <T>

    show code

    1. SchemaString.prototype.castForQuery = function($conditional, val) {
    2. var handler;
    3. if (arguments.length === 2) {
    4. handler = this.$conditionalHandlers[$conditional];
    5. if (!handler) {
    6. throw new Error('Can\'t use ' + $conditional + ' with String.');
    7. }
    8. return handler.call(this, val);
    9. }
    10. val = $conditional;
    11. if (Object.prototype.toString.call(val) === '[object RegExp]') {
    12. return val;
    13. }
    14. return this._castForQuery(val);
    15. };

    SchemaString#checkRequired(value, doc)

    Check if the given value satisfies the required validator. The value is
    considered valid if it is a string (that is, not null or undefined) and
    has positive length. The required validator will fail for empty
    strings.

    Parameters:

    Returns:

    show code

    1. SchemaString.prototype.checkRequired = function checkRequired(value, doc) {
    2. if (SchemaType._isRef(this, value, doc, true)) {
    3. return !!value;
    4. }
    5. return (value instanceof String || typeof value === 'string') && value.length;
    6. };

    SchemaString#enum([args...])

    Adds an enum validator

    Parameters:

    Returns:

    See:

    Example:

    1. var states = ['opening', 'open', 'closing', 'closed']
    2. var s = new Schema({ state: { type: String, enum: states }})
    3. var M = db.model('M', s)
    4. var m = new M({ state: 'invalid' })
    5. m.save(function (err) {
    6. console.error(String(err)) // ValidationError: `invalid` is not a valid enum value for path `state`.
    7. m.state = 'open'
    8. m.save(callback) // success
    9. })
    10. // or with custom error messages
    11. var enum = {
    12. values: ['opening', 'open', 'closing', 'closed'],
    13. message: 'enum validator failed for path `{PATH}` with value `{VALUE}`'
    14. }
    15. var s = new Schema({ state: { type: String, enum: enum })
    16. var M = db.model('M', s)
    17. var m = new M({ state: 'invalid' })
    18. m.save(function (err) {
    19. console.error(String(err)) // ValidationError: enum validator failed for path `state` with value `invalid`
    20. m.state = 'open'
    21. m.save(callback) // success
    22. })

    show code

    1. SchemaString.prototype.enum = function() {
    2. if (this.enumValidator) {
    3. this.validators = this.validators.filter(function(v) {
    4. return v.validator !== this.enumValidator;
    5. }, this);
    6. this.enumValidator = false;
    7. }
    8. if (arguments[0] === void 0 || arguments[0] === false) {
    9. return this;
    10. }
    11. var values;
    12. var errorMessage;
    13. if (utils.isObject(arguments[0])) {
    14. values = arguments[0].values;
    15. errorMessage = arguments[0].message;
    16. } else {
    17. values = arguments;
    18. errorMessage = MongooseError.messages.String.enum;
    19. }
    20. for (var i = 0; i < values.length; i++) {
    21. if (undefined !== values[i]) {
    22. this.enumValues.push(this.cast(values[i]));
    23. }
    24. }
    25. var vals = this.enumValues;
    26. this.enumValidator = function(v) {
    27. return undefined === v || ~vals.indexOf(v);
    28. };
    29. this.validators.push({
    30. validator: this.enumValidator,
    31. message: errorMessage,
    32. type: 'enum',
    33. enumValues: vals
    34. });
    35. return this;
    36. };

    SchemaString#lowercase()

    Adds a lowercase setter.

    Returns:

    Example:

    1. var s = new Schema({ email: { type: String, lowercase: true }})
    2. var M = db.model('M', s);
    3. var m = new M({ email: 'SomeEmail@example.COM' });
    4. console.log(m.email) // someemail@example.com

    NOTE: Setters do not run on queries by default. Use the runSettersOnQuery option:

    1. // Must use `runSettersOnQuery` as shown below, otherwise `email` will
    2. // **not** be lowercased.
    3. M.updateOne({}, { $set: { email: 'SomeEmail@example.COM' } }, { runSettersOnQuery: true });

    show code

    1. SchemaString.prototype.lowercase = function(shouldApply) {
    2. if (arguments.length > 0 && !shouldApply) {
    3. return this;
    4. }
    5. return this.set(function(v, self) {
    6. if (typeof v !== 'string') {
    7. v = self.cast(v);
    8. }
    9. if (v) {
    10. return v.toLowerCase();
    11. }
    12. return v;
    13. });
    14. };

    SchemaString#match(regExp, [message])

    Sets a regexp validator.

    Parameters:

    • regExp <RegExp> regular expression to test against
    • [message] <String> optional custom error message

    Returns:

    See:

    Any value that does not pass regExp.test(val) will fail validation.

    Example:

    1. var s = new Schema({ name: { type: String, match: /^a/ }})
    2. var M = db.model('M', s)
    3. var m = new M({ name: 'I am invalid' })
    4. m.validate(function (err) {
    5. console.error(String(err)) // "ValidationError: Path `name` is invalid (I am invalid)."
    6. m.name = 'apples'
    7. m.validate(function (err) {
    8. assert.ok(err) // success
    9. })
    10. })
    11. // using a custom error message
    12. var match = [ /\.html$/, "That file doesn't end in .html ({VALUE})" ];
    13. var s = new Schema({ file: { type: String, match: match }})
    14. var M = db.model('M', s);
    15. var m = new M({ file: 'invalid' });
    16. m.validate(function (err) {
    17. console.log(String(err)) // "ValidationError: That file doesn't end in .html (invalid)"
    18. })

    Empty strings, undefined, and null values always pass the match validator. If you require these values, enable the required validator also.

    1. var s = new Schema({ name: { type: String, match: /^a/, required: true }})

    show code

    1. SchemaString.prototype.match = function match(regExp, message) {
    2. // yes, we allow multiple match validators
    3. var msg = message || MongooseError.messages.String.match;
    4. var matchValidator = function(v) {
    5. if (!regExp) {
    6. return false;
    7. }
    8. var ret = ((v != null && v !== '')
    9. ? regExp.test(v)
    10. : true);
    11. return ret;
    12. };
    13. this.validators.push({
    14. validator: matchValidator,
    15. message: msg,
    16. type: 'regexp',
    17. regexp: regExp
    18. });
    19. return this;
    20. };

    SchemaString#maxlength(value, [message])

    Sets a maximum length validator.

    Parameters:

    • value <Number> maximum string length
    • [message] <String> optional custom error message

    Returns:

    See:

    Example:

    1. var schema = new Schema({ postalCode: { type: String, maxlength: 9 })
    2. var Address = db.model('Address', schema)
    3. var address = new Address({ postalCode: '9512512345' })
    4. address.save(function (err) {
    5. console.error(err) // validator error
    6. address.postalCode = '95125';
    7. address.save() // success
    8. })
    9. // custom error messages
    10. // We can also use the special {MAXLENGTH} token which will be replaced with the maximum allowed length
    11. var maxlength = [9, 'The value of path `{PATH}` (`{VALUE}`) exceeds the maximum allowed length ({MAXLENGTH}).'];
    12. var schema = new Schema({ postalCode: { type: String, maxlength: maxlength })
    13. var Address = mongoose.model('Address', schema);
    14. var address = new Address({ postalCode: '9512512345' });
    15. address.validate(function (err) {
    16. console.log(String(err)) // ValidationError: The value of path `postalCode` (`9512512345`) exceeds the maximum allowed length (9).
    17. })

    show code

    1. SchemaString.prototype.maxlength = function(value, message) {
    2. if (this.maxlengthValidator) {
    3. this.validators = this.validators.filter(function(v) {
    4. return v.validator !== this.maxlengthValidator;
    5. }, this);
    6. }
    7. if (value !== null && value !== undefined) {
    8. var msg = message || MongooseError.messages.String.maxlength;
    9. msg = msg.replace(/{MAXLENGTH}/, value);
    10. this.validators.push({
    11. validator: this.maxlengthValidator = function(v) {
    12. return v === null || v.length <= value;
    13. },
    14. message: msg,
    15. type: 'maxlength',
    16. maxlength: value
    17. });
    18. }
    19. return this;
    20. };

    SchemaString#minlength(value, [message])

    Sets a minimum length validator.

    Parameters:

    • value <Number> minimum string length
    • [message] <String> optional custom error message

    Returns:

    See:

    Example:

    1. var schema = new Schema({ postalCode: { type: String, minlength: 5 })
    2. var Address = db.model('Address', schema)
    3. var address = new Address({ postalCode: '9512' })
    4. address.save(function (err) {
    5. console.error(err) // validator error
    6. address.postalCode = '95125';
    7. address.save() // success
    8. })
    9. // custom error messages
    10. // We can also use the special {MINLENGTH} token which will be replaced with the minimum allowed length
    11. var minlength = [5, 'The value of path `{PATH}` (`{VALUE}`) is shorter than the minimum allowed length ({MINLENGTH}).'];
    12. var schema = new Schema({ postalCode: { type: String, minlength: minlength })
    13. var Address = mongoose.model('Address', schema);
    14. var address = new Address({ postalCode: '9512' });
    15. address.validate(function (err) {
    16. console.log(String(err)) // ValidationError: The value of path `postalCode` (`9512`) is shorter than the minimum length (5).
    17. })

    show code

    1. SchemaString.prototype.minlength = function(value, message) {
    2. if (this.minlengthValidator) {
    3. this.validators = this.validators.filter(function(v) {
    4. return v.validator !== this.minlengthValidator;
    5. }, this);
    6. }
    7. if (value !== null && value !== undefined) {
    8. var msg = message || MongooseError.messages.String.minlength;
    9. msg = msg.replace(/{MINLENGTH}/, value);
    10. this.validators.push({
    11. validator: this.minlengthValidator = function(v) {
    12. return v === null || v.length >= value;
    13. },
    14. message: msg,
    15. type: 'minlength',
    16. minlength: value
    17. });
    18. }
    19. return this;
    20. };

    SchemaString(key, options)

    String SchemaType constructor.

    Parameters:

    Inherits:

    show code

    1. function SchemaString(key, options) {
    2. this.enumValues = [];
    3. this.regExp = null;
    4. SchemaType.call(this, key, options, 'String');
    5. }

    SchemaString#trim()

    Adds a trim setter.

    Returns:

    The string value will be trimmed when set.

    Example:

    1. var s = new Schema({ name: { type: String, trim: true }})
    2. var M = db.model('M', s)
    3. var string = ' some name '
    4. console.log(string.length) // 11
    5. var m = new M({ name: string })
    6. console.log(m.name.length) // 9

    NOTE: Setters do not run on queries by default. Use the runSettersOnQuery option:

    1. // Must use `runSettersOnQuery` as shown below, otherwise `email` will
    2. // **not** be lowercased.
    3. M.updateOne({}, { $set: { email: 'SomeEmail@example.COM' } }, { runSettersOnQuery: true });

    show code

    1. SchemaString.prototype.trim = function(shouldTrim) {
    2. if (arguments.length > 0 && !shouldTrim) {
    3. return this;
    4. }
    5. return this.set(function(v, self) {
    6. if (typeof v !== 'string') {
    7. v = self.cast(v);
    8. }
    9. if (v) {
    10. return v.trim();
    11. }
    12. return v;
    13. });
    14. };

    SchemaString#uppercase()

    Adds an uppercase setter.

    Returns:

    Example:

    1. var s = new Schema({ caps: { type: String, uppercase: true }})
    2. var M = db.model('M', s);
    3. var m = new M({ caps: 'an example' });
    4. console.log(m.caps) // AN EXAMPLE

    NOTE: Setters do not run on queries by default. Use the runSettersOnQuery option:

    1. // Must use `runSettersOnQuery` as shown below, otherwise `email` will
    2. // **not** be lowercased.
    3. M.updateOne({}, { $set: { email: 'SomeEmail@example.COM' } }, { runSettersOnQuery: true });

    show code

    1. SchemaString.prototype.uppercase = function(shouldApply) {
    2. if (arguments.length > 0 && !shouldApply) {
    3. return this;
    4. }
    5. return this.set(function(v, self) {
    6. if (typeof v !== 'string') {
    7. v = self.cast(v);
    8. }
    9. if (v) {
    10. return v.toUpperCase();
    11. }
    12. return v;
    13. });
    14. };

    SchemaString.schemaName

    This schema type’s name, to defend against minifiers that mangle
    function names.

    show code

    1. SchemaString.schemaName = 'String';

  • schema/date.js

    SchemaDate#cast(value)

    Casts to date

    Parameters:

    show code

    1. SchemaDate.prototype.cast = function(value) {
    2. // If null or undefined
    3. if (value === null || value === void 0 || value === '') {
    4. return null;
    5. }
    6. if (value instanceof Date) {
    7. if (isNaN(value.valueOf())) {
    8. throw new CastError('date', value, this.path);
    9. }
    10. return value;
    11. }
    12. var date;
    13. if (typeof value === 'boolean') {
    14. throw new CastError('date', value, this.path);
    15. }
    16. if (value instanceof Number || typeof value === 'number'
    17. || String(value) == Number(value)) {
    18. // support for timestamps
    19. date = new Date(Number(value));
    20. } else if (value.valueOf) {
    21. // support for moment.js
    22. date = new Date(value.valueOf());
    23. }
    24. if (!isNaN(date.valueOf())) {
    25. return date;
    26. }
    27. throw new CastError('date', value, this.path);
    28. };

    SchemaDate#castForQuery($conditional, [value])

    Casts contents for queries.

    Parameters:

    • $conditional <String>
    • [value] <T>

    show code

    1. SchemaDate.prototype.castForQuery = function($conditional, val) {
    2. var handler;
    3. if (arguments.length !== 2) {
    4. return this._castForQuery($conditional);
    5. }
    6. handler = this.$conditionalHandlers[$conditional];
    7. if (!handler) {
    8. throw new Error('Can\'t use ' + $conditional + ' with Date.');
    9. }
    10. return handler.call(this, val);
    11. };

    SchemaDate#checkRequired(value, doc)

    Check if the given value satisfies a required validator. To satisfy
    a required validator, the given value must be an instance of Date.

    Parameters:

    Returns:

    show code

    1. SchemaDate.prototype.checkRequired = function(value) {
    2. return value instanceof Date;
    3. };

    SchemaDate#expires(when)

    Declares a TTL index (rounded to the nearest second) for Date types only.

    Parameters:

    Returns:

    This sets the expireAfterSeconds index option available in MongoDB >= 2.1.2.
    This index type is only compatible with Date types.

    Example:

    1. // expire in 24 hours
    2. new Schema({ createdAt: { type: Date, expires: 60*60*24 }});

    expires utilizes the ms module from guille allowing us to use a friendlier syntax:

    Example:

    1. // expire in 24 hours
    2. new Schema({ createdAt: { type: Date, expires: '24h' }});
    3. // expire in 1.5 hours
    4. new Schema({ createdAt: { type: Date, expires: '1.5h' }});
    5. // expire in 7 days
    6. var schema = new Schema({ createdAt: Date });
    7. schema.path('createdAt').expires('7d');

    show code

    1. SchemaDate.prototype.expires = function(when) {
    2. if (!this._index || this._index.constructor.name !== 'Object') {
    3. this._index = {};
    4. }
    5. this._index.expires = when;
    6. utils.expires(this._index);
    7. return this;
    8. };

    SchemaDate#max(maximum, [message])

    Sets a maximum date validator.

    Parameters:

    • maximum <Date> date
    • [message] <String> optional custom error message

    Returns:

    See:

    Example:

    1. var s = new Schema({ d: { type: Date, max: Date('2014-01-01') })
    2. var M = db.model('M', s)
    3. var m = new M({ d: Date('2014-12-08') })
    4. m.save(function (err) {
    5. console.error(err) // validator error
    6. m.d = Date('2013-12-31');
    7. m.save() // success
    8. })
    9. // custom error messages
    10. // We can also use the special {MAX} token which will be replaced with the invalid value
    11. var max = [Date('2014-01-01'), 'The value of path `{PATH}` ({VALUE}) exceeds the limit ({MAX}).'];
    12. var schema = new Schema({ d: { type: Date, max: max })
    13. var M = mongoose.model('M', schema);
    14. var s= new M({ d: Date('2014-12-08') });
    15. s.validate(function (err) {
    16. console.log(String(err)) // ValidationError: The value of path `d` (2014-12-08) exceeds the limit (2014-01-01).
    17. })

    show code

    1. SchemaDate.prototype.max = function(value, message) {
    2. if (this.maxValidator) {
    3. this.validators = this.validators.filter(function(v) {
    4. return v.validator !== this.maxValidator;
    5. }, this);
    6. }
    7. if (value) {
    8. var msg = message || MongooseError.messages.Date.max;
    9. msg = msg.replace(/{MAX}/, (value === Date.now ? 'Date.now()' : this.cast(value).toString()));
    10. var _this = this;
    11. this.validators.push({
    12. validator: this.maxValidator = function(val) {
    13. var max = (value === Date.now ? value() : _this.cast(value));
    14. return val === null || val.valueOf() <= max.valueOf();
    15. },
    16. message: msg,
    17. type: 'max',
    18. max: value
    19. });
    20. }
    21. return this;
    22. };

    SchemaDate#min(value, [message])

    Sets a minimum date validator.

    Parameters:

    • value <Date> minimum date
    • [message] <String> optional custom error message

    Returns:

    See:

    Example:

    1. var s = new Schema({ d: { type: Date, min: Date('1970-01-01') })
    2. var M = db.model('M', s)
    3. var m = new M({ d: Date('1969-12-31') })
    4. m.save(function (err) {
    5. console.error(err) // validator error
    6. m.d = Date('2014-12-08');
    7. m.save() // success
    8. })
    9. // custom error messages
    10. // We can also use the special {MIN} token which will be replaced with the invalid value
    11. var min = [Date('1970-01-01'), 'The value of path `{PATH}` ({VALUE}) is beneath the limit ({MIN}).'];
    12. var schema = new Schema({ d: { type: Date, min: min })
    13. var M = mongoose.model('M', schema);
    14. var s= new M({ d: Date('1969-12-31') });
    15. s.validate(function (err) {
    16. console.log(String(err)) // ValidationError: The value of path `d` (1969-12-31) is before the limit (1970-01-01).
    17. })

    show code

    1. SchemaDate.prototype.min = function(value, message) {
    2. if (this.minValidator) {
    3. this.validators = this.validators.filter(function(v) {
    4. return v.validator !== this.minValidator;
    5. }, this);
    6. }
    7. if (value) {
    8. var msg = message || MongooseError.messages.Date.min;
    9. msg = msg.replace(/{MIN}/, (value === Date.now ? 'Date.now()' : this.cast(value).toString()));
    10. var _this = this;
    11. this.validators.push({
    12. validator: this.minValidator = function(val) {
    13. var min = (value === Date.now ? value() : _this.cast(value));
    14. return val === null || val.valueOf() >= min.valueOf();
    15. },
    16. message: msg,
    17. type: 'min',
    18. min: value
    19. });
    20. }
    21. return this;
    22. };

    SchemaDate(key, options)

    Date SchemaType constructor.

    Parameters:

    Inherits:

    show code

    1. function SchemaDate(key, options) {
    2. SchemaType.call(this, key, options, 'Date');
    3. }

    SchemaDate.schemaName

    This schema type’s name, to defend against minifiers that mangle
    function names.

    show code

    1. SchemaDate.schemaName = 'Date';

  • schema/embedded.js

    Embedded#cast(value)

    Casts contents

    Parameters:

    show code

    1. Embedded.prototype.cast = function(val, doc, init, priorVal) {
    2. if (val && val.$isSingleNested) {
    3. return val;
    4. }
    5. var Constructor = this.caster;
    6. var discriminatorKey = Constructor.schema.options.discriminatorKey;
    7. if (val != null &&
    8. Constructor.discriminators &&
    9. typeof val[discriminatorKey] === 'string' &&
    10. Constructor.discriminators[val[discriminatorKey]]) {
    11. Constructor = Constructor.discriminators[val[discriminatorKey]];
    12. }
    13. var subdoc;
    14. if (init) {
    15. subdoc = new Constructor(void 0, doc ? doc.$__.selected : void 0, doc);
    16. subdoc.init(val);
    17. } else {
    18. if (Object.keys(val).length === 0) {
    19. return new Constructor({}, doc ? doc.$__.selected : void 0, doc);
    20. }
    21. return new Constructor(val, doc ? doc.$__.selected : void 0, doc, undefined, {
    22. priorDoc: priorVal
    23. });
    24. }
    25. return subdoc;
    26. };

    Embedded#castForQuery([$conditional], value)

    Casts contents for query

    Parameters:

    • [$conditional] <string> optional query operator (like $eq or $in)
    • value <T>

    show code

    1. Embedded.prototype.castForQuery = function($conditional, val) {
    2. var handler;
    3. if (arguments.length === 2) {
    4. handler = this.$conditionalHandlers[$conditional];
    5. if (!handler) {
    6. throw new Error('Can\'t use ' + $conditional);
    7. }
    8. return handler.call(this, val);
    9. }
    10. val = $conditional;
    11. if (val == null) {
    12. return val;
    13. }
    14. if (this.options.runSetters) {
    15. val = this._applySetters(val);
    16. }
    17. return new this.caster(val);
    18. };

    Embedded#discriminator(name, schema)

    Adds a discriminator to this property

    Parameters:

    • name <String>
    • schema <Schema> fields to add to the schema for instances of this sub-class

    show code

    1. Embedded.prototype.discriminator = function(name, schema) {
    2. discriminator(this.caster, name, schema);
    3. this.caster.discriminators[name] = _createConstructor(schema);
    4. return this.caster.discriminators[name];
    5. };

    Embedded#doValidate()

    Async validation on this single nested doc.

    show code

    1. Embedded.prototype.doValidate = function(value, fn, scope) {
    2. var Constructor = this.caster;
    3. var discriminatorKey = Constructor.schema.options.discriminatorKey;
    4. if (value != null &&
    5. Constructor.discriminators &&
    6. typeof value[discriminatorKey] === 'string' &&
    7. Constructor.discriminators[value[discriminatorKey]]) {
    8. Constructor = Constructor.discriminators[value[discriminatorKey]];
    9. }
    10. SchemaType.prototype.doValidate.call(this, value, function(error) {
    11. if (error) {
    12. return fn(error);
    13. }
    14. if (!value) {
    15. return fn(null);
    16. }
    17. if (!(value instanceof Constructor)) {
    18. value = new Constructor(value);
    19. }
    20. value.validate({__noPromise: true}, fn);
    21. }, scope);
    22. };

    Embedded#doValidateSync()

    Synchronously validate this single nested doc

    show code

    1. Embedded.prototype.doValidateSync = function(value, scope) {
    2. var schemaTypeError = SchemaType.prototype.doValidateSync.call(this, value, scope);
    3. if (schemaTypeError) {
    4. return schemaTypeError;
    5. }
    6. if (!value) {
    7. return;
    8. }
    9. return value.validateSync();
    10. };

    Embedded(schema, key, options)

    Sub-schema schematype constructor

    Parameters:

    Inherits:

    show code

    1. function Embedded(schema, path, options) {
    2. this.caster = _createConstructor(schema);
    3. this.caster.prototype.$basePath = path;
    4. this.schema = schema;
    5. this.$isSingleNested = true;
    6. SchemaType.call(this, path, options, 'Embedded');
    7. }

  • schema/buffer.js

    SchemaBuffer#cast(value, doc, init)

    Casts contents

    Parameters:

    show code

    1. SchemaBuffer.prototype.cast = function(value, doc, init) {
    2. var ret;
    3. if (SchemaType._isRef(this, value, doc, init)) {
    4. // wait! we may need to cast this to a document
    5. if (value === null || value === undefined) {
    6. return value;
    7. }
    8. // lazy load
    9. Document || (Document = require('./../document'));
    10. if (value instanceof Document) {
    11. value.$__.wasPopulated = true;
    12. return value;
    13. }
    14. // setting a populated path
    15. if (Buffer.isBuffer(value)) {
    16. return value;
    17. } else if (!utils.isObject(value)) {
    18. throw new CastError('buffer', value, this.path);
    19. }
    20. // Handle the case where user directly sets a populated
    21. // path to a plain object; cast to the Model used in
    22. // the population query.
    23. var path = doc.$__fullPath(this.path);
    24. var owner = doc.ownerDocument ? doc.ownerDocument() : doc;
    25. var pop = owner.populated(path, true);
    26. ret = new pop.options.model(value);
    27. ret.$__.wasPopulated = true;
    28. return ret;
    29. }
    30. // documents
    31. if (value && value._id) {
    32. value = value._id;
    33. }
    34. if (value && value.isMongooseBuffer) {
    35. return value;
    36. }
    37. if (Buffer.isBuffer(value)) {
    38. if (!value || !value.isMongooseBuffer) {
    39. value = new MongooseBuffer(value, [this.path, doc]);
    40. if (this.options.subtype != null) {
    41. value._subtype = this.options.subtype;
    42. }
    43. }
    44. return value;
    45. } else if (value instanceof Binary) {
    46. ret = new MongooseBuffer(value.value(true), [this.path, doc]);
    47. if (typeof value.sub_type !== 'number') {
    48. throw new CastError('buffer', value, this.path);
    49. }
    50. ret._subtype = value.sub_type;
    51. return ret;
    52. }
    53. if (value === null) {
    54. return value;
    55. }
    56. var type = typeof value;
    57. if (type === 'string' || type === 'number' || Array.isArray(value)) {
    58. if (type === 'number') {
    59. value = [value];
    60. }
    61. ret = new MongooseBuffer(value, [this.path, doc]);
    62. if (this.options.subtype != null) {
    63. ret._subtype = this.options.subtype;
    64. }
    65. return ret;
    66. }
    67. throw new CastError('buffer', value, this.path);
    68. };

    SchemaBuffer#castForQuery($conditional, [value])

    Casts contents for queries.

    Parameters:

    • $conditional <String>
    • [value] <T>

    show code

    1. SchemaBuffer.prototype.castForQuery = function($conditional, val) {
    2. var handler;
    3. if (arguments.length === 2) {
    4. handler = this.$conditionalHandlers[$conditional];
    5. if (!handler) {
    6. throw new Error('Can\'t use ' + $conditional + ' with Buffer.');
    7. }
    8. return handler.call(this, val);
    9. }
    10. val = $conditional;
    11. var casted = this._castForQuery(val);
    12. return casted ? casted.toObject({ transform: false, virtuals: false }) : casted;
    13. };

    SchemaBuffer#checkRequired(value, doc)

    Check if the given value satisfies a required validator. To satisfy a
    required validator, a buffer must not be null or undefined and have
    non-zero length.

    Parameters:

    Returns:

    show code

    1. SchemaBuffer.prototype.checkRequired = function(value, doc) {
    2. if (SchemaType._isRef(this, value, doc, true)) {
    3. return !!value;
    4. }
    5. return !!(value && value.length);
    6. };

    SchemaBuffer(key, options)

    Buffer SchemaType constructor

    Parameters:

    Inherits:

    show code

    1. function SchemaBuffer(key, options) {
    2. SchemaType.call(this, key, options, 'Buffer');
    3. }

    SchemaBuffer#subtype(subtype)

    Sets the default subtype
    for this buffer. You can find a list of allowed subtypes here.

    Parameters:

    • subtype <Number> the default subtype

    Returns:

    Example:

    1. var s = new Schema({ uuid: { type: Buffer, subtype: 4 });
    2. var M = db.model('M', s);
    3. var m = new M({ uuid: 'test string' });
    4. m.uuid._subtype; // 4

    show code

    1. SchemaBuffer.prototype.subtype = function(subtype) {
    2. this.options.subtype = subtype;
    3. return this;
    4. };

    SchemaBuffer.schemaName

    This schema type’s name, to defend against minifiers that mangle
    function names.

    show code

    1. SchemaBuffer.schemaName = 'Buffer';

  • schema/mixed.js

    Mixed#cast(value)

    Casts val for Mixed.

    Parameters:

    this is a no-op

    show code

    1. Mixed.prototype.cast = function(val) {
    2. return val;
    3. };

    Mixed#castForQuery($cond, [val])

    Casts contents for queries.

    Parameters:

    show code

    1. Mixed.prototype.castForQuery = function($cond, val) {
    2. if (arguments.length === 2) {
    3. return val;
    4. }
    5. return $cond;
    6. };

    Mixed(path, options)

    Mixed SchemaType constructor.

    Parameters:

    Inherits:

    show code

    1. function Mixed(path, options) {
    2. if (options && options.default) {
    3. var def = options.default;
    4. if (Array.isArray(def) && def.length === 0) {
    5. // make sure empty array defaults are handled
    6. options.default = Array;
    7. } else if (!options.shared && utils.isObject(def) && Object.keys(def).length === 0) {
    8. // prevent odd "shared" objects between documents
    9. options.default = function() {
    10. return {};
    11. };
    12. }
    13. }
    14. SchemaType.call(this, path, options, 'Mixed');
    15. }

    Mixed.schemaName

    This schema type’s name, to defend against minifiers that mangle
    function names.

    show code

    1. Mixed.schemaName = 'Mixed';

  • services/cursor/eachAsync.js

    module.exports(next, fn, options, [callback])

    Execute fn for every document in the cursor. If fn returns a promise,
    will wait for the promise to resolve before iterating on to the next one.
    Returns a promise that resolves when done.

    Parameters:

    • next <Function> the thunk to call to get the next document
    • fn <Function>
    • options <Object>
    • [callback] <Function> executed when all docs have been processed

    Returns:


  • services/updateValidators.js

    module.exports(query, schema, castedDoc, options)

    Applies validators and defaults to update and findOneAndUpdate operations,
    specifically passing a null doc as this to validators and defaults

    Parameters:


  • services/setDefaultsOnInsert.js

    module.exports(filter, schema, castedDoc, options)

    Applies defaults to update and findOneAndUpdate operations.

    Parameters:


  • connection.js

    Connection#_close(force, callback)

    Handles closing the connection

    Parameters:

    show code

    1. Connection.prototype._close = function(force, callback) {
    2. var _this = this;
    3. this._closeCalled = true;
    4. switch (this.readyState) {
    5. case 0: // disconnected
    6. callback && callback();
    7. break;
    8. case 1: // connected
    9. case 4: // unauthorized
    10. this.readyState = STATES.disconnecting;
    11. this.doClose(force, function(err) {
    12. if (err) {
    13. _this.error(err, callback);
    14. } else {
    15. _this.onClose(force);
    16. callback && callback();
    17. }
    18. });
    19. break;
    20. case 2: // connecting
    21. this.once('open', function() {
    22. _this.close(callback);
    23. });
    24. break;
    25. case 3: // disconnecting
    26. if (!callback) {
    27. break;
    28. }
    29. this.once('close', function() {
    30. callback();
    31. });
    32. break;
    33. }
    34. return this;
    35. };

    Connection#_open(callback)

    Handles opening the connection with the appropriate method based on connection type.

    Parameters:

    show code

    1. Connection.prototype._open = function(emit, callback) {
    2. this.readyState = STATES.connecting;
    3. this._closeCalled = false;
    4. var _this = this;
    5. var method = this.replica
    6. ? 'doOpenSet'
    7. : 'doOpen';
    8. // open connection
    9. this[method](function(err) {
    10. if (err) {
    11. _this.readyState = STATES.disconnected;
    12. if (_this._hasOpened) {
    13. if (callback) {
    14. callback(err);
    15. }
    16. } else {
    17. _this.error(err, emit && callback);
    18. }
    19. return;
    20. }
    21. _this.onOpen(callback);
    22. });
    23. };

    Connection#authMechanismDoesNotRequirePassword()

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

    Returns:

    • <Boolean> true if the authentication mechanism specified in the options object requires

    show code

    1. Connection.prototype.authMechanismDoesNotRequirePassword = function() {
    2. if (this.options && this.options.auth) {
    3. return authMechanismsWhichDontRequirePassword.indexOf(this.options.auth.authMechanism) >= 0;
    4. }
    5. return true;
    6. };

    Connection#close([force], [callback])

    Closes the connection

    Parameters:

    Returns:

    show code

    1. Connection.prototype.close = function(force, callback) {
    2. var _this = this;
    3. var Promise = PromiseProvider.get();
    4. if (typeof force === 'function') {
    5. callback = force;
    6. force = false;
    7. }
    8. this.$wasForceClosed = !!force;
    9. return new Promise.ES6(function(resolve, reject) {
    10. _this._close(force, function(error) {
    11. callback && callback(error);
    12. if (error) {
    13. reject(error);
    14. return;
    15. }
    16. resolve();
    17. });
    18. });
    19. };

    Connection#collection(name, [options])

    Retrieves a collection, creating it if not cached.

    Parameters:

    • name <String> of the collection
    • [options] <Object> optional collection options

    Returns:

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

    show code

    1. Connection.prototype.collection = function(name, options) {
    2. options = options ? utils.clone(options, { retainKeyOrder: true }) : {};
    3. options.$wasForceClosed = this.$wasForceClosed;
    4. if (!(name in this.collections)) {
    5. this.collections[name] = new Collection(name, this, options);
    6. }
    7. return this.collections[name];
    8. };

    Connection(base)

    Connection constructor

    Parameters:

    Inherits:

    Events:

    • connecting: Emitted when connection.{open,openSet}() is executed on this connection.

    • connected: Emitted when this connection successfully connects to the db. May be emitted multiple times in reconnected scenarios.

    • open: Emitted after we connected and onOpen is executed on all of this connections models.

    • disconnecting: Emitted when connection.close() was executed.

    • disconnected: Emitted after getting disconnected from the db.

    • close: Emitted after we disconnected and onClose executed on all of this connections models.

    • reconnected: Emitted after we connected and subsequently disconnected, followed by successfully another successfull connection.

    • error: Emitted when an error occurs on this connection.

    • fullsetup: Emitted in a replica-set scenario, when primary and at least one seconaries specified in the connection string are connected.

    • all: Emitted in a replica-set scenario, when all nodes specified in the connection string are connected.

    For practical reasons, a Connection equals a Db.

    show code

    1. function Connection(base) {
    2. this.base = base;
    3. this.collections = {};
    4. this.models = {};
    5. this.config = {autoIndex: true};
    6. this.replica = false;
    7. this.hosts = null;
    8. this.host = null;
    9. this.port = null;
    10. this.user = null;
    11. this.pass = null;
    12. this.name = null;
    13. this.options = null;
    14. this.otherDbs = [];
    15. this.states = STATES;
    16. this._readyState = STATES.disconnected;
    17. this._closeCalled = false;
    18. this._hasOpened = false;
    19. }

    (collection, [options], [callback])

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

    Parameters:

    Returns:

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

    show code

    1. Connection.prototype.createCollection = _wrapConnHelper(function createCollection(collection, options, cb) {
    2. if (typeof options === 'function') {
    3. cb = options;
    4. options = {};
    5. }
    6. this.db.createCollection(collection, options, cb);
    7. });

    (collection, [callback])

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

    Parameters:

    Returns:

    show code

    1. Connection.prototype.dropCollection = _wrapConnHelper(function dropCollection(collection, cb) {
    2. this.db.dropCollection(collection, cb);
    3. });

    ([callback])

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

    Parameters:

    Returns:

    show code

    1. Connection.prototype.dropDatabase = _wrapConnHelper(function dropDatabase(cb) {
    2. this.db.dropDatabase(cb);
    3. });

    Connection#error(err, callback)

    error

    Parameters:

    Graceful error handling, passes error to callback
    if available, else emits error on the connection.

    show code

    1. Connection.prototype.error = function(err, callback) {
    2. if (callback) {
    3. return callback(err);
    4. }
    5. this.emit('error', err);
    6. };

    Connection#model(name, [schema], [collection])

    Defines or retrieves a 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

    See:

    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)

    show code

    1. Connection.prototype.model = function(name, schema, collection) {
    2. // collection name discovery
    3. if (typeof schema === 'string') {
    4. collection = schema;
    5. schema = false;
    6. }
    7. if (utils.isObject(schema) && !schema.instanceOfSchema) {
    8. schema = new Schema(schema);
    9. }
    10. if (schema && !schema.instanceOfSchema) {
    11. throw new Error('The 2nd parameter to `mongoose.model()` should be a ' +
    12. 'schema or a POJO');
    13. }
    14. if (this.models[name] && !collection) {
    15. // model exists but we are not subclassing with custom collection
    16. if (schema && schema.instanceOfSchema && schema !== this.models[name].schema) {
    17. throw new MongooseError.OverwriteModelError(name);
    18. }
    19. return this.models[name];
    20. }
    21. var opts = {cache: false, connection: this};
    22. var model;
    23. if (schema && schema.instanceOfSchema) {
    24. // compile a model
    25. model = this.base.model(name, schema, collection, opts);
    26. // only the first model with this name is cached to allow
    27. // for one-offs with custom collection names etc.
    28. if (!this.models[name]) {
    29. this.models[name] = model;
    30. }
    31. model.init();
    32. return model;
    33. }
    34. if (this.models[name] && collection) {
    35. // subclassing current model with alternate collection
    36. model = this.models[name];
    37. schema = model.prototype.schema;
    38. var sub = model.__subclass(this, schema, collection);
    39. // do not cache the sub model
    40. return sub;
    41. }
    42. // lookup model in mongoose module
    43. model = this.base.models[name];
    44. if (!model) {
    45. throw new MongooseError.MissingSchemaError(name);
    46. }
    47. if (this === model.prototype.db
    48. && (!collection || collection === model.collection.name)) {
    49. // model already uses this connection.
    50. // only the first model with this name is cached to allow
    51. // for one-offs with custom collection names etc.
    52. if (!this.models[name]) {
    53. this.models[name] = model;
    54. }
    55. return model;
    56. }
    57. this.models[name] = model.__subclass(this, schema, collection);
    58. return this.models[name];
    59. };

    Connection#modelNames()

    Returns an array of model names created on this connection.

    Returns:

    show code

    1. Connection.prototype.modelNames = function() {
    2. return Object.keys(this.models);
    3. };

    Connection#onClose()

    Called when the connection closes

    show code

    1. Connection.prototype.onClose = function(force) {
    2. this.readyState = STATES.disconnected;
    3. // avoid having the collection subscribe to our event emitter
    4. // to prevent 0.3 warning
    5. for (var i in this.collections) {
    6. if (utils.object.hasOwnProperty(this.collections, i)) {
    7. this.collections[i].onClose(force);
    8. }
    9. }
    10. this.emit('close', force);
    11. };

    Connection#onOpen()

    Called when the connection is opened

    show code

    1. Connection.prototype.onOpen = function(callback) {
    2. var _this = this;
    3. function open(err, isAuth) {
    4. if (err) {
    5. _this.readyState = isAuth ? STATES.unauthorized : STATES.disconnected;
    6. _this.error(err, callback);
    7. return;
    8. }
    9. _this.readyState = STATES.connected;
    10. // avoid having the collection subscribe to our event emitter
    11. // to prevent 0.3 warning
    12. for (var i in _this.collections) {
    13. if (utils.object.hasOwnProperty(_this.collections, i)) {
    14. _this.collections[i].onOpen();
    15. }
    16. }
    17. callback && callback();
    18. _this.emit('open');
    19. }
    20. // re-authenticate if we're not already connected #3871
    21. if (this._readyState !== STATES.connected && this.shouldAuthenticate()) {
    22. _this.db.authenticate(_this.user, _this.pass, _this.options.auth, function(err) {
    23. open(err, true);
    24. });
    25. } else {
    26. open();
    27. }
    28. };

    (connection_string, [database], [port], [options], [callback])

    Opens the connection to MongoDB.

    Parameters:

    • connection_string <String> mongodb://uri or the host to which you are connecting
    • [database] <String> database name
    • [port] <Number> database port
    • [options] <Object> options
    • [callback] <Function>

    See:

    options is a hash with the following possible properties:

    1. config - passed to the connection config instance
    2. db - passed to the connection db instance
    3. server - passed to the connection server instance(s)
    4. replset - passed to the connection ReplSet instance
    5. user - username for authentication
    6. pass - password for authentication
    7. auth - options for authentication (see http://mongodb.github.com/node-mongodb-native/api-generated/db.html#authenticate)

    Notes:

    Mongoose forces the db option forceServerObjectId false and cannot be overridden.
    Mongoose defaults the server auto_reconnect options to true which can be overridden.
    See the node-mongodb-native driver instance for options that it understands.

    Options passed take precedence over options included in connection strings.

    show code

    1. Connection.prototype.open = util.deprecate(function() {
    2. var Promise = PromiseProvider.get();
    3. var callback;
    4. try {
    5. callback = this._handleOpenArgs.apply(this, arguments);
    6. } catch (error) {
    7. return new Promise.ES6(function(resolve, reject) {
    8. reject(error);
    9. });
    10. }
    11. var _this = this;
    12. var promise = new Promise.ES6(function(resolve, reject) {
    13. _this._open(true, function(error) {
    14. callback && callback(error);
    15. if (error) {
    16. // Error can be on same tick re: christkv/mongodb-core#157
    17. setImmediate(function() {
    18. reject(error);
    19. if (!callback && !promise.$hasHandler) {
    20. _this.emit('error', error);
    21. }
    22. });
    23. return;
    24. }
    25. resolve();
    26. });
    27. });
    28. // Monkey-patch `.then()` so if the promise is handled, we don't emit an
    29. // `error` event.
    30. var _then = promise.then;
    31. promise.then = function(resolve, reject) {
    32. promise.$hasHandler = true;
    33. return _then.call(promise, resolve, reject);
    34. };
    35. return promise;
    36. }, '`open()` is deprecated in mongoose >= 4.11.0, use `openUri()` instead, or set the `useMongoClient` option if using `connect()` or `createConnection()`. See http://mongoosejs.com/docs/4.x/docs/connections.html#use-mongo-client');

    (uris, [database], [options], [callback])

    Opens the connection to a replica set.

    Parameters:

    • uris <String> MongoDB connection string
    • [database] <String> database name if not included in uris
    • [options] <Object> passed to the internal driver
    • [callback] <Function>

    See:

    Example:

    1. var db = mongoose.createConnection();
    2. db.openSet("mongodb://user:pwd@localhost:27020,localhost:27021,localhost:27012/mydb");

    The database name and/or auth need only be included in one URI.
    The options is a hash which is passed to the internal driver connection object.

    Valid options

    1. db - passed to the connection db instance
    2. server - passed to the connection server instance(s)
    3. replset - passed to the connection ReplSetServer instance
    4. user - username for authentication
    5. pass - password for authentication
    6. auth - options for authentication (see http://mongodb.github.com/node-mongodb-native/api-generated/db.html#authenticate)
    7. mongos - Boolean - if true, enables High Availability support for mongos

    Options passed take precedence over options included in connection strings.

    Notes:

    If connecting to multiple mongos servers, set the mongos option to true.

    1. conn.open('mongodb://mongosA:27501,mongosB:27501', { mongos: true }, cb);

    Mongoose forces the db option forceServerObjectId false and cannot be overridden.
    Mongoose defaults the server auto_reconnect options to true which can be overridden.
    See the node-mongodb-native driver instance for options that it understands.

    Options passed take precedence over options included in connection strings.

    show code

    1. Connection.prototype.openSet = util.deprecate(function(uris, database, options, callback) {
    2. var Promise = PromiseProvider.get();
    3. try {
    4. callback = this._handleOpenSetArgs.apply(this, arguments);
    5. } catch (err) {
    6. return new Promise.ES6(function(resolve, reject) {
    7. reject(err);
    8. });
    9. }
    10. var _this = this;
    11. var emitted = false;
    12. var promise = new Promise.ES6(function(resolve, reject) {
    13. _this._open(true, function(error) {
    14. callback && callback(error);
    15. if (error) {
    16. reject(error);
    17. if (!callback && !promise.$hasHandler && !emitted) {
    18. emitted = true;
    19. _this.emit('error', error);
    20. }
    21. return;
    22. }
    23. resolve();
    24. });
    25. });
    26. // Monkey-patch `.then()` so if the promise is handled, we don't emit an
    27. // `error` event.
    28. var _then = promise.then;
    29. promise.then = function(resolve, reject) {
    30. promise.$hasHandler = true;
    31. return _then.call(promise, resolve, reject);
    32. };
    33. return promise;
    34. }, '`openSet()` is deprecated in mongoose >= 4.11.0, use `openUri()` instead, or set the `useMongoClient` option if using `connect()` or `createConnection()`. See http://mongoosejs.com/docs/4.x/docs/connections.html#use-mongo-client');

    Connection#openUri(uri, [options], [callback])

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

    Parameters:

    show code

    1. Connection.prototype.openUri = function(uri, options, callback) {
    2. this.readyState = STATES.connecting;
    3. this._closeCalled = false;
    4. try {
    5. var parsed = muri(uri);
    6. this.name = parsed.db;
    7. this.host = parsed.hosts[0].host || parsed.hosts[0].ipc;
    8. this.port = parsed.hosts[0].port || 27017;
    9. if (parsed.auth) {
    10. this.user = parsed.auth.user;
    11. this.pass = parsed.auth.pass;
    12. }
    13. } catch (error) {
    14. this.error(error, callback);
    15. throw error;
    16. }
    17. if (typeof options === 'function') {
    18. callback = options;
    19. options = null;
    20. }
    21. var Promise = PromiseProvider.get();
    22. var _this = this;
    23. if (options) {
    24. options = utils.clone(options, { retainKeyOrder: true });
    25. delete options.useMongoClient;
    26. var autoIndex = options.config && options.config.autoIndex != null ?
    27. options.config.autoIndex :
    28. options.autoIndex;
    29. if (autoIndex != null) {
    30. this.config.autoIndex = autoIndex !== false;
    31. delete options.config;
    32. delete options.autoIndex;
    33. }
    34. // Backwards compat
    35. if (options.user || options.pass) {
    36. options.auth = options.auth || {};
    37. options.auth.user = options.user;
    38. options.auth.password = options.pass;
    39. delete options.user;
    40. delete options.pass;
    41. this.user = options.auth.user;
    42. this.pass = options.auth.password;
    43. }
    44. if (options.bufferCommands != null) {
    45. options.bufferMaxEntries = 0;
    46. this.config.bufferCommands = options.bufferCommands;
    47. delete options.bufferCommands;
    48. }
    49. }
    50. this._connectionOptions = options;
    51. var promise = new Promise.ES6(function(resolve, reject) {
    52. mongodb.MongoClient.connect(uri, options, function(error, db) {
    53. if (error) {
    54. _this.readyState = STATES.disconnected;
    55. if (_this.listeners('error').length) {
    56. _this.emit('error', error);
    57. }
    58. callback && callback(error);
    59. return reject(error);
    60. }
    61. // Backwards compat for mongoose 4.x
    62. db.on('reconnect', function() {
    63. _this.readyState = STATES.connected;
    64. _this.emit('reconnect');
    65. _this.emit('reconnected');
    66. });
    67. db.s.topology.on('reconnectFailed', function() {
    68. _this.emit('reconnectFailed');
    69. });
    70. db.s.topology.on('close', function() {
    71. // Implicitly emits 'disconnected'
    72. _this.readyState = STATES.disconnected;
    73. });
    74. db.on('timeout', function() {
    75. _this.emit('timeout');
    76. });
    77. delete _this.then;
    78. delete _this.catch;
    79. _this.db = db;
    80. _this.readyState = STATES.connected;
    81. for (var i in _this.collections) {
    82. if (utils.object.hasOwnProperty(_this.collections, i)) {
    83. _this.collections[i].onOpen();
    84. }
    85. }
    86. callback && callback(null, _this);
    87. resolve(_this);
    88. _this.emit('open');
    89. });
    90. });
    91. this.then = function(resolve, reject) {
    92. return promise.then(resolve, reject);
    93. };
    94. this.catch = function(reject) {
    95. return promise.catch(reject);
    96. };
    97. return this;
    98. };

    Connection#optionsProvideAuthenticationData([options])

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

    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,

    show code

    1. Connection.prototype.optionsProvideAuthenticationData = function(options) {
    2. return (options) &&
    3. (options.user) &&
    4. ((options.pass) || this.authMechanismDoesNotRequirePassword());
    5. };

    Connection#shouldAuthenticate()

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

    Returns:

    • <Boolean> true if the connection should be authenticated after it is opened, otherwise false.

    show code

    1. Connection.prototype.shouldAuthenticate = function() {
    2. return (this.user !== null && this.user !== void 0) &&
    3. ((this.pass !== null || this.pass !== void 0) || this.authMechanismDoesNotRequirePassword());
    4. };

    Connection#collections

    A hash of the collections associated with this connection

    show code

    1. Connection.prototype.collections;

    Connection#config

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

    show code

    1. Connection.prototype.config;

    Connection#db

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

    show code

    1. Connection.prototype.db;

    Connection#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);

    show code

    1. Object.defineProperty(Connection.prototype, 'readyState', {
    2. get: function() {
    3. return this._readyState;
    4. },
    5. set: function(val) {
    6. if (!(val in STATES)) {
    7. throw new Error('Invalid connection state: ' + val);
    8. }
    9. if (this._readyState !== val) {
    10. this._readyState = val;
    11. // loop over the otherDbs on this connection and change their state
    12. for (var i = 0; i < this.otherDbs.length; i++) {
    13. this.otherDbs[i].readyState = val;
    14. }
    15. if (STATES.connected === val) {
    16. this._hasOpened = true;
    17. }
    18. this.emit(STATES[val]);
    19. }
    20. }
    21. });

  • drivers/node-mongodb-native/collection.js

    function Object() { [native code] }#$format()%20%7B%20%5Bnative%20code%5D%20%7D-%24format)

    Formatter for debug print args


    function Object() { [native code] }#$print()%20%7B%20%5Bnative%20code%5D%20%7D-%24print)

    Debug print helper


    NativeCollection#getIndexes(callback)

    Retreives information about this collections indexes.

    Parameters:


    NativeCollection()

    A node-mongodb-native collection implementation.

    Inherits:

    All methods methods from the node-mongodb-native driver are copied and wrapped in queue management.

    show code

    1. function NativeCollection() {
    2. this.collection = null;
    3. MongooseCollection.apply(this, arguments);
    4. }

    NativeCollection#onClose()

    Called when the connection closes

    show code

    1. NativeCollection.prototype.onClose = function(force) {
    2. MongooseCollection.prototype.onClose.call(this, force);
    3. };

    NativeCollection#onOpen()

    Called when the connection opens.

    show code

    1. NativeCollection.prototype.onOpen = function() {
    2. var _this = this;
    3. // always get a new collection in case the user changed host:port
    4. // of parent db instance when re-opening the connection.
    5. if (!_this.opts.capped.size) {
    6. // non-capped
    7. callback(null, _this.conn.db.collection(_this.name));
    8. return _this.collection;
    9. }
    10. // capped
    11. return _this.conn.db.collection(_this.name, function(err, c) {
    12. if (err) return callback(err);
    13. // discover if this collection exists and if it is capped
    14. _this.conn.db.listCollections({name: _this.name}).toArray(function(err, docs) {
    15. if (err) {
    16. return callback(err);
    17. }
    18. var doc = docs[0];
    19. var exists = !!doc;
    20. if (exists) {
    21. if (doc.options && doc.options.capped) {
    22. callback(null, c);
    23. } else {
    24. var msg = 'A non-capped collection exists with the name: ' + _this.name + '
    25. '
    26. + ' To use this collection as a capped collection, please '
    27. + 'first convert it.
    28. '
    29. + ' http://www.mongodb.org/display/DOCS/Capped+Collections#CappedCollections-Convertingacollectiontocapped';
    30. err = new Error(msg);
    31. callback(err);
    32. }
    33. } else {
    34. // create
    35. var opts = utils.clone(_this.opts.capped);
    36. opts.capped = true;
    37. _this.conn.db.createCollection(_this.name, opts, callback);
    38. }
    39. });
    40. });
    41. function callback(err, collection) {
    42. if (err) {
    43. // likely a strict mode error
    44. _this.conn.emit('error', err);
    45. } else {
    46. _this.collection = collection;
    47. MongooseCollection.prototype.onOpen.call(_this);
    48. }
    49. }
    50. };

  • drivers/node-mongodb-native/connection.js

    NativeConnection#doClose([force], [fn])

    Closes the connection

    Parameters:

    Returns:

    show code

    1. NativeConnection.prototype.doClose = function(force, fn) {
    2. this.db.close(force, fn);
    3. return this;
    4. };

    NativeConnection#doOpen(fn)

    Opens the connection to MongoDB.

    Parameters:

    Returns:

    show code

    1. NativeConnection.prototype.doOpen = function(fn) {
    2. var _this = this;
    3. var server = new Server(this.host, this.port, this.options.server);
    4. if (this.options && this.options.mongos) {
    5. var mongos = new Mongos([server], this.options.mongos);
    6. this.db = new Db(this.name, mongos, this.options.db);
    7. } else {
    8. this.db = new Db(this.name, server, this.options.db);
    9. }
    10. this.db.open(function(err) {
    11. listen(_this);
    12. if (!mongos) {
    13. server.s.server.on('error', function(error) {
    14. if (/after \d+ attempts/.test(error.message)) {
    15. _this.emit('error', new DisconnectedError(server.s.server.name));
    16. }
    17. });
    18. }
    19. if (err) return fn(err);
    20. fn();
    21. });
    22. return this;
    23. };

    NativeConnection#doOpenSet(fn)

    Opens a connection to a MongoDB ReplicaSet.

    Parameters:

    Returns:

    See description of doOpen for server options. In this case options.replset is also passed to ReplSetServers.

    show code

    1. NativeConnection.prototype.doOpenSet = function(fn) {
    2. var servers = [],
    3. _this = this;
    4. this.hosts.forEach(function(server) {
    5. var host = server.host || server.ipc;
    6. var port = server.port || 27017;
    7. servers.push(new Server(host, port, _this.options.server));
    8. });
    9. var server = this.options.mongos
    10. ? new Mongos(servers, this.options.mongos)
    11. : new ReplSetServers(servers, this.options.replset || this.options.replSet);
    12. this.db = new Db(this.name, server, this.options.db);
    13. this.db.s.topology.on('left', function(data) {
    14. _this.emit('left', data);
    15. });
    16. this.db.s.topology.on('joined', function(data) {
    17. _this.emit('joined', data);
    18. });
    19. this.db.on('fullsetup', function() {
    20. _this.emit('fullsetup');
    21. });
    22. this.db.on('all', function() {
    23. _this.emit('all');
    24. });
    25. this.db.open(function(err) {
    26. if (err) return fn(err);
    27. fn();
    28. listen(_this);
    29. });
    30. return this;
    31. };

    NativeConnection()

    A node-mongodb-native connection implementation.

    Inherits:

    show code

    1. function NativeConnection() {
    2. MongooseConnection.apply(this, arguments);
    3. this._listening = false;
    4. }

    NativeConnection#parseOptions(passed, [connStrOptions])

    Prepares default connection options for the node-mongodb-native driver.

    Parameters:

    • passed <Object> options that were passed directly during connection
    • [connStrOptions] <Object> options that were passed in the connection string

    NOTE: passed options take precedence over connection string options.

    show code

    1. NativeConnection.prototype.parseOptions = function(passed, connStrOpts) {
    2. var o = passed ? require('../../utils').clone(passed) : {};
    3. o.db || (o.db = {});
    4. o.auth || (o.auth = {});
    5. o.server || (o.server = {});
    6. o.replset || (o.replset = o.replSet) || (o.replset = {});
    7. o.server.socketOptions || (o.server.socketOptions = {});
    8. o.replset.socketOptions || (o.replset.socketOptions = {});
    9. o.mongos || (o.mongos = (connStrOpts && connStrOpts.mongos));
    10. (o.mongos === true) && (o.mongos = {});
    11. var opts = connStrOpts || {};
    12. Object.keys(opts).forEach(function(name) {
    13. switch (name) {
    14. case 'ssl':
    15. o.server.ssl = opts.ssl;
    16. o.replset.ssl = opts.ssl;
    17. o.mongos && (o.mongos.ssl = opts.ssl);
    18. break;
    19. case 'poolSize':
    20. if (typeof o.server[name] === 'undefined') {
    21. o.server[name] = o.replset[name] = opts[name];
    22. }
    23. break;
    24. case 'slaveOk':
    25. if (typeof o.server.slave_ok === 'undefined') {
    26. o.server.slave_ok = opts[name];
    27. }
    28. break;
    29. case 'autoReconnect':
    30. if (typeof o.server.auto_reconnect === 'undefined') {
    31. o.server.auto_reconnect = opts[name];
    32. }
    33. break;
    34. case 'socketTimeoutMS':
    35. case 'connectTimeoutMS':
    36. if (typeof o.server.socketOptions[name] === 'undefined') {
    37. o.server.socketOptions[name] = o.replset.socketOptions[name] = opts[name];
    38. }
    39. break;
    40. case 'authdb':
    41. if (typeof o.auth.authdb === 'undefined') {
    42. o.auth.authdb = opts[name];
    43. }
    44. break;
    45. case 'authSource':
    46. if (typeof o.auth.authSource === 'undefined') {
    47. o.auth.authSource = opts[name];
    48. }
    49. break;
    50. case 'authMechanism':
    51. if (typeof o.auth.authMechanism === 'undefined') {
    52. o.auth.authMechanism = opts[name];
    53. }
    54. break;
    55. case 'retries':
    56. case 'reconnectWait':
    57. case 'rs_name':
    58. if (typeof o.replset[name] === 'undefined') {
    59. o.replset[name] = opts[name];
    60. }
    61. break;
    62. case 'replicaSet':
    63. if (typeof o.replset.rs_name === 'undefined') {
    64. o.replset.rs_name = opts[name];
    65. }
    66. break;
    67. case 'readSecondary':
    68. if (typeof o.replset.read_secondary === 'undefined') {
    69. o.replset.read_secondary = opts[name];
    70. }
    71. break;
    72. case 'nativeParser':
    73. if (typeof o.db.native_parser === 'undefined') {
    74. o.db.native_parser = opts[name];
    75. }
    76. break;
    77. case 'w':
    78. case 'safe':
    79. case 'fsync':
    80. case 'journal':
    81. case 'wtimeoutMS':
    82. if (typeof o.db[name] === 'undefined') {
    83. o.db[name] = opts[name];
    84. }
    85. break;
    86. case 'readPreference':
    87. if (typeof o.db.readPreference === 'undefined') {
    88. o.db.readPreference = opts[name];
    89. }
    90. break;
    91. case 'readPreferenceTags':
    92. if (typeof o.db.read_preference_tags === 'undefined') {
    93. o.db.read_preference_tags = opts[name];
    94. }
    95. break;
    96. case 'sslValidate':
    97. o.server.sslValidate = opts.sslValidate;
    98. o.replset.sslValidate = opts.sslValidate;
    99. o.mongos && (o.mongos.sslValidate = opts.sslValidate);
    100. }
    101. });
    102. if (!('auto_reconnect' in o.server)) {
    103. o.server.auto_reconnect = true;
    104. }
    105. // mongoose creates its own ObjectIds
    106. o.db.forceServerObjectId = false;
    107. // default safe using new nomenclature
    108. if (!('journal' in o.db || 'j' in o.db ||
    109. 'fsync' in o.db || 'safe' in o.db || 'w' in o.db)) {
    110. o.db.w = 1;
    111. }
    112. if (o.promiseLibrary) {
    113. o.db.promiseLibrary = o.promiseLibrary;
    114. }
    115. validate(o);
    116. return o;
    117. };

    NativeConnection#useDb(name)

    Switches to a different database using the same connection pool.

    Parameters:

    • name <String> The database name

    Returns:

    Returns a new connection object, with the new db.

    show code

    1. NativeConnection.prototype.useDb = function(name) {
    2. // we have to manually copy all of the attributes...
    3. var newConn = new this.constructor();
    4. newConn.name = name;
    5. newConn.base = this.base;
    6. newConn.collections = {};
    7. newConn.models = {};
    8. newConn.replica = this.replica;
    9. newConn.hosts = this.hosts;
    10. newConn.host = this.host;
    11. newConn.port = this.port;
    12. newConn.user = this.user;
    13. newConn.pass = this.pass;
    14. newConn.options = this.options;
    15. newConn._readyState = this._readyState;
    16. newConn._closeCalled = this._closeCalled;
    17. newConn._hasOpened = this._hasOpened;
    18. newConn._listening = false;
    19. // First, when we create another db object, we are not guaranteed to have a
    20. // db object to work with. So, in the case where we have a db object and it
    21. // is connected, we can just proceed with setting everything up. However, if
    22. // we do not have a db or the state is not connected, then we need to wait on
    23. // the 'open' event of the connection before doing the rest of the setup
    24. // the 'connected' event is the first time we'll have access to the db object
    25. var _this = this;
    26. if (this.db && this._readyState === STATES.connected) {
    27. wireup();
    28. } else {
    29. this.once('connected', wireup);
    30. }
    31. function wireup() {
    32. newConn.db = _this.db.db(name);
    33. newConn.onOpen();
    34. // setup the events appropriately
    35. listen(newConn);
    36. }
    37. newConn.name = name;
    38. // push onto the otherDbs stack, this is used when state changes
    39. this.otherDbs.push(newConn);
    40. newConn.otherDbs.push(this);
    41. return newConn;
    42. };

    NativeConnection.STATES

    Expose the possible connection states.

    show code

    1. NativeConnection.STATES = STATES;

  • error/messages.js

    MongooseError.messages()

    The default built-in validator error messages. These may be customized.

    show code

    1. var msg = module.exports = exports = {};
    2. msg.DocumentNotFoundError = null;
    3. msg.general = {};
    4. msg.general.default = 'Validator failed for path `{PATH}` with value `{VALUE}`';
    5. msg.general.required = 'Path `{PATH}` is required.';
    6. msg.Number = {};
    7. msg.Number.min = 'Path `{PATH}` ({VALUE}) is less than minimum allowed value ({MIN}).';
    8. msg.Number.max = 'Path `{PATH}` ({VALUE}) is more than maximum allowed value ({MAX}).';
    9. msg.Date = {};
    10. msg.Date.min = 'Path `{PATH}` ({VALUE}) is before minimum allowed value ({MIN}).';
    11. msg.Date.max = 'Path `{PATH}` ({VALUE}) is after maximum allowed value ({MAX}).';
    12. msg.String = {};
    13. msg.String.enum = '`{VALUE}` is not a valid enum value for path `{PATH}`.';
    14. msg.String.match = 'Path `{PATH}` is invalid ({VALUE}).';
    15. msg.String.minlength = 'Path `{PATH}` (`{VALUE}`) is shorter than the minimum allowed length ({MINLENGTH}).';
    16. msg.String.maxlength = 'Path `{PATH}` (`{VALUE}`) is longer than the maximum allowed length ({MAXLENGTH}).';
    1. // customize within each schema or globally like so
    2. var mongoose = require('mongoose');
    3. mongoose.Error.messages.String.enum = "Your custom message for {PATH}.";

    As you might have noticed, error messages support basic templating

    • {PATH} is replaced with the invalid document path
    • {VALUE} is replaced with the invalid value
    • {TYPE} is replaced with the validator type such as “regexp”, “min”, or “user defined”
    • {MIN} is replaced with the declared min value for the Number.min validator
    • {MAX} is replaced with the declared max value for the Number.max validator

    Click the “show code” link below to see all defaults.


  • error/cast.js

    CastError(type, value)

    Casting Error constructor.

    Parameters:

    Inherits:

    show code

    1. function CastError(type, value, path, reason) {
    2. var stringValue = util.inspect(value);
    3. stringValue = stringValue.replace(/^'/, '"').replace(/'$/, '"');
    4. if (stringValue.charAt(0) !== '"') {
    5. stringValue = '"' + stringValue + '"';
    6. }
    7. MongooseError.call(this, 'Cast to ' + type + ' failed for value ' +
    8. stringValue + ' at path "' + path + '"');
    9. this.name = 'CastError';
    10. if (Error.captureStackTrace) {
    11. Error.captureStackTrace(this);
    12. } else {
    13. this.stack = new Error().stack;
    14. }
    15. this.stringValue = stringValue;
    16. this.kind = type;
    17. this.value = value;
    18. this.path = path;
    19. this.reason = reason;
    20. }

  • error/objectExpected.js

    ObjectExpectedError(type, value)

    Strict mode error constructor

    Parameters:

    Inherits:

    show code

    1. function ObjectExpectedError(path, val) {
    2. MongooseError.call(this, 'Tried to set nested object field `' + path +
    3. '` to primitive value `' + val + '` and strict mode is set to throw.');
    4. this.name = 'ObjectExpectedError';
    5. if (Error.captureStackTrace) {
    6. Error.captureStackTrace(this);
    7. } else {
    8. this.stack = new Error().stack;
    9. }
    10. this.path = path;
    11. }

  • error/disconnected.js

    DisconnectedError(type, value)

    Casting Error constructor.

    Parameters:

    Inherits:

    show code

    1. function DisconnectedError(connectionString) {
    2. MongooseError.call(this, 'Ran out of retries trying to reconnect to "' +
    3. connectionString + '". Try setting `server.reconnectTries` and ' +
    4. '`server.reconnectInterval` to something higher.');
    5. this.name = 'DisconnectedError';
    6. if (Error.captureStackTrace) {
    7. Error.captureStackTrace(this);
    8. } else {
    9. this.stack = new Error().stack;
    10. }
    11. }

  • error/objectParameter.js

    ObjectParameterError(value, paramName, fnName)

    Constructor for errors that happen when a parameter that’s expected to be
    an object isn’t an object

    Parameters:

    Inherits:

    show code

    1. function ObjectParameterError(value, paramName, fnName) {
    2. MongooseError.call(this, 'Parameter "' + paramName + '" to ' + fnName +
    3. '() must be an object, got ' + value.toString());
    4. this.name = 'ObjectParameterError';
    5. if (Error.captureStackTrace) {
    6. Error.captureStackTrace(this);
    7. } else {
    8. this.stack = new Error().stack;
    9. }
    10. }

  • error/validation.js

    ValidationError#toString()

    Console.log helper

    show code

    1. ValidationError.prototype.toString = function() {
    2. return this.name + ': ' + _generateMessage(this);
    3. };

    ValidationError(instance)

    Document Validation Error

    Parameters:

    Inherits:

    show code

    1. function ValidationError(instance) {
    2. this.errors = {};
    3. this._message = '';
    4. if (instance && instance.constructor.name === 'model') {
    5. this._message = instance.constructor.modelName + ' validation failed';
    6. MongooseError.call(this, this._message);
    7. } else {
    8. this._message = 'Validation failed';
    9. MongooseError.call(this, this._message);
    10. }
    11. this.name = 'ValidationError';
    12. if (Error.captureStackTrace) {
    13. Error.captureStackTrace(this);
    14. } else {
    15. this.stack = new Error().stack;
    16. }
    17. if (instance) {
    18. instance.errors = this.errors;
    19. }
    20. }

  • error/validator.js

    ValidatorError(properties)

    Schema validator error

    Parameters:

    Inherits:

    show code

    1. function ValidatorError(properties) {
    2. var msg = properties.message;
    3. if (!msg) {
    4. msg = MongooseError.messages.general.default;
    5. }
    6. var message = this.formatMessage(msg, properties);
    7. MongooseError.call(this, message);
    8. this.name = 'ValidatorError';
    9. if (Error.captureStackTrace) {
    10. Error.captureStackTrace(this);
    11. } else {
    12. this.stack = new Error().stack;
    13. }
    14. this.properties = properties;
    15. this.kind = properties.type;
    16. this.path = properties.path;
    17. this.value = properties.value;
    18. this.reason = properties.reason;
    19. }

  • error/index.js

    MongooseError(msg)

    MongooseError constructor

    Parameters:

    Inherits:

    show code

    1. function MongooseError(msg) {
    2. Error.call(this);
    3. if (Error.captureStackTrace) {
    4. Error.captureStackTrace(this);
    5. } else {
    6. this.stack = new Error().stack;
    7. }
    8. this.message = msg;
    9. this.name = 'MongooseError';
    10. }

    MongooseError.DocumentNotFoundError

    This error will be called 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.

    show code

    1. MongooseError.DocumentNotFoundError = require('./notFound');

    MongooseError.messages

    The default built-in validator error messages.

    show code

    1. MongooseError.messages = require('./messages');
    2. // backward compat
    3. MongooseError.Messages = MongooseError.messages;

    See:


  • error/version.js

    VersionError()

    Version Error constructor.

    Inherits:

    show code

    1. function VersionError(doc, currentVersion, modifiedPaths) {
    2. var modifiedPathsStr = modifiedPaths.join(', ');
    3. MongooseError.call(this, 'No matching document found for id "' + doc._id +
    4. '" version ' + currentVersion + ' modifiedPaths "' + modifiedPathsStr + '"');
    5. this.name = 'VersionError';
    6. this.version = currentVersion;
    7. this.modifiedPaths = modifiedPaths;
    8. }

  • error/strict.js

    StrictModeError(type, value)

    Strict mode error constructor

    Parameters:

    Inherits:

    show code

    1. function StrictModeError(path, msg) {
    2. msg = msg || 'Field `' + path + '` is not in schema and strict ' +
    3. 'mode is set to throw.';
    4. MongooseError.call(this, msg);
    5. this.name = 'StrictModeError';
    6. if (Error.captureStackTrace) {
    7. Error.captureStackTrace(this);
    8. } else {
    9. this.stack = new Error().stack;
    10. }
    11. this.path = path;
    12. }

  • aggregate.js

    Aggregate#addCursorFlag(flag, value)

    Adds a cursor flag

    Parameters:

    See:

    Example:

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

    show code

    1. Aggregate.prototype.addCursorFlag = function(flag, value) {
    2. if (!this.options) {
    3. this.options = {};
    4. }
    5. this.options[flag] = value;
    6. return this;
    7. };

    Aggregate#addFields(arg)

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

    Parameters:

    • arg <Object> field specification

    Returns:

    See:

    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 ] } });

    show code

    1. Aggregate.prototype.addFields = function(arg) {
    2. var fields = {};
    3. if (typeof arg === 'object' && !util.isArray(arg)) {
    4. Object.keys(arg).forEach(function(field) {
    5. fields[field] = arg[field];
    6. });
    7. } else {
    8. throw new Error('Invalid addFields() argument. Must be an object');
    9. }
    10. return this.append({$addFields: fields});
    11. };

    Aggregate([ops])

    Aggregate constructor used for building aggregation pipelines.

    Parameters:

    • [ops] <Object, Array> aggregation operator(s) or operator array

    See:

    Example:

    1. new Aggregate();
    2. new Aggregate({ $project: { a: 1, b: 1 } });
    3. new Aggregate({ $project: { a: 1, b: 1 } }, { $skip: 5 });
    4. new Aggregate([{ $project: { a: 1, b: 1 } }, { $skip: 5 }]);

    Returned when calling Model.aggregate().

    Example:

    1. Model
    2. .aggregate({ $match: { age: { $gte: 21 }}})
    3. .unwind('tags')
    4. .exec(callback)

    Note:

    • The documents returned are plain javascript objects, not mongoose documents (since any shape of document can be returned).
    • Requires MongoDB >= 2.1
    • Mongoose does not cast pipeline stages. new Aggregate({ $match: { _id: '00000000000000000000000a' } }); will not work unless _id is a string in the database. Use new Aggregate({ $match: { _id: mongoose.Types.ObjectId('00000000000000000000000a') } }); instead.

    show code

    1. function Aggregate() {
    2. this._pipeline = [];
    3. this._model = undefined;
    4. this.options = {};
    5. if (arguments.length === 1 && util.isArray(arguments[0])) {
    6. this.append.apply(this, arguments[0]);
    7. } else {
    8. this.append.apply(this, arguments);
    9. }
    10. }

    Aggregate#allowDiskUse(value, [tags])

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

    Parameters:

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

    See:

    Example:

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

    show code

    1. Aggregate.prototype.allowDiskUse = function(value) {
    2. this.options.allowDiskUse = value;
    3. return this;
    4. };

    Aggregate#append(ops)

    Appends new operators to this aggregate pipeline

    Parameters:

    • ops <Object> operator(s) to append

    Returns:

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

    show code

    1. Aggregate.prototype.append = function() {
    2. var args = (arguments.length === 1 && util.isArray(arguments[0]))
    3. ? arguments[0]
    4. : utils.args(arguments);
    5. if (!args.every(isOperator)) {
    6. throw new Error('Arguments must be aggregate pipeline operators');
    7. }
    8. this._pipeline = this._pipeline.concat(args);
    9. return this;
    10. };

    Aggregate#collation(collation)

    Adds a collation

    Parameters:

    See:

    Example:

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

    show code

    1. Aggregate.prototype.collation = function(collation) {
    2. if (!this.options) {
    3. this.options = {};
    4. }
    5. this.options.collation = collation;
    6. return this;
    7. };

    Aggregate#cursor(options, options.batchSize, [options.useMongooseAggCursor])

    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.

    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)

    See:

    Example:

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

    show code

    1. Aggregate.prototype.cursor = function(options) {
    2. if (!this.options) {
    3. this.options = {};
    4. }
    5. this.options.cursor = options || {};
    6. return this;
    7. };

    Aggregate#exec([callback])

    Executes the aggregate pipeline on the currently bound Model.

    Parameters:

    Returns:

    See:

    Example:

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

    show code

    1. Aggregate.prototype.exec = function(callback) {
    2. if (!this._model) {
    3. throw new Error('Aggregate not bound to any Model');
    4. }
    5. var _this = this;
    6. var model = this._model;
    7. var Promise = PromiseProvider.get();
    8. var options = utils.clone(this.options || {});
    9. var pipeline = this._pipeline;
    10. var collection = this._model.collection;
    11. if (options && options.cursor) {
    12. if (options.cursor.async) {
    13. delete options.cursor.async;
    14. return new Promise.ES6(function(resolve) {
    15. if (!collection.buffer) {
    16. process.nextTick(function() {
    17. var cursor = collection.aggregate(pipeline, options);
    18. decorateCursor(cursor);
    19. resolve(cursor);
    20. callback && callback(null, cursor);
    21. });
    22. return;
    23. }
    24. collection.emitter.once('queue', function() {
    25. var cursor = collection.aggregate(pipeline, options);
    26. decorateCursor(cursor);
    27. resolve(cursor);
    28. callback && callback(null, cursor);
    29. });
    30. });
    31. } else if (options.cursor.useMongooseAggCursor) {
    32. delete options.cursor.useMongooseAggCursor;
    33. return new AggregationCursor(this);
    34. }
    35. var cursor = collection.aggregate(pipeline, options);
    36. decorateCursor(cursor);
    37. return cursor;
    38. }
    39. return new Promise.ES6(function(resolve, reject) {
    40. if (!pipeline.length) {
    41. var err = new Error('Aggregate has empty pipeline');
    42. if (callback) {
    43. callback(err);
    44. }
    45. reject(err);
    46. return;
    47. }
    48. prepareDiscriminatorPipeline(_this);
    49. model.hooks.execPre('aggregate', _this, function(error) {
    50. if (error) {
    51. var _opts = { error: error };
    52. return model.hooks.execPost('aggregate', _this, [null], _opts, function(error) {
    53. if (callback) {
    54. callback(error);
    55. }
    56. reject(error);
    57. });
    58. }
    59. collection.aggregate(pipeline, options, function(error, result) {
    60. var _opts = { error: error };
    61. model.hooks.execPost('aggregate', _this, [result], _opts, function(error, result) {
    62. if (error) {
    63. if (callback) {
    64. callback(error);
    65. }
    66. reject(error);
    67. return;
    68. }
    69. if (callback) {
    70. callback(null, result);
    71. }
    72. resolve(result);
    73. });
    74. });
    75. });
    76. });
    77. };

    Aggregate#explain(callback)

    Execute the aggregation with explain

    Parameters:

    Returns:

    Example:

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

    show code

    1. Aggregate.prototype.explain = function(callback) {
    2. var _this = this;
    3. var Promise = PromiseProvider.get();
    4. return new Promise.ES6(function(resolve, reject) {
    5. if (!_this._pipeline.length) {
    6. var err = new Error('Aggregate has empty pipeline');
    7. if (callback) {
    8. callback(err);
    9. }
    10. reject(err);
    11. return;
    12. }
    13. prepareDiscriminatorPipeline(_this);
    14. _this._model
    15. .collection
    16. .aggregate(_this._pipeline, _this.options || {})
    17. .explain(function(error, result) {
    18. if (error) {
    19. if (callback) {
    20. callback(error);
    21. }
    22. reject(error);
    23. return;
    24. }
    25. if (callback) {
    26. callback(null, result);
    27. }
    28. resolve(result);
    29. });
    30. });
    31. };

    Aggregate#facet(facet)

    Combines multiple aggregation pipelines.

    Parameters:

    Returns:

    See:

    Example:

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

    show code

    1. Aggregate.prototype.facet = function(options) {
    2. return this.append({$facet: options});
    3. };

    Aggregate#graphLookup(options)

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

    Parameters:

    • options <Object> to $graphLookup as described in the above link

    Returns:

    See:

    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

    show code

    1. Aggregate.prototype.graphLookup = function(options) {
    2. var cloneOptions = {};
    3. if (options) {
    4. if (!utils.isObject(options)) {
    5. throw new TypeError('Invalid graphLookup() argument. Must be an object.');
    6. }
    7. utils.mergeClone(cloneOptions, options);
    8. var startWith = cloneOptions.startWith;
    9. if (startWith && typeof startWith === 'string') {
    10. cloneOptions.startWith = cloneOptions.startWith.charAt(0) === '$' ?
    11. cloneOptions.startWith :
    12. '$' + cloneOptions.startWith;
    13. }
    14. }
    15. return this.append({ $graphLookup: cloneOptions });
    16. };

    Aggregate#group(arg)

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

    Parameters:

    • arg <Object> $group operator contents

    Returns:

    See:

    Examples:

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

    isOperator(obj)

    Checks whether an object is likely a pipeline operator

    Parameters:

    Returns:

    show code

    1. function isOperator(obj) {
    2. var k;
    3. if (typeof obj !== 'object') {
    4. return false;
    5. }
    6. k = Object.keys(obj);
    7. return k.length === 1 && k
    8. .some(function(key) {
    9. return key[0] === '$';
    10. });
    11. }

    Aggregate#limit(num)

    Appends a new $limit operator to this aggregate pipeline.

    Parameters:

    • num <Number> maximum number of records to pass to the next stage

    Returns:

    See:

    Examples:

    1. aggregate.limit(10);

    Aggregate#lookup(options)

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

    Parameters:

    • options <Object> to $lookup as described in the above link

    Returns:

    See:

    Examples:

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

    show code

    1. Aggregate.prototype.lookup = function(options) {
    2. return this.append({$lookup: options});
    3. };

    Aggregate#match(arg)

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

    Parameters:

    • arg <Object> $match operator contents

    Returns:

    See:

    Examples:

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

    Aggregate#model(model)

    Binds this aggregate to a model.

    Parameters:

    • model <Model> the model to which the aggregate is to be bound

    Returns:

    show code

    1. Aggregate.prototype.model = function(model) {
    2. this._model = model;
    3. if (model.schema != null) {
    4. if (this.options.readPreference == null &&
    5. model.schema.options.read != null) {
    6. this.options.readPreference = model.schema.options.read;
    7. }
    8. if (this.options.collation == null &&
    9. model.schema.options.collation != null) {
    10. this.options.collation = model.schema.options.collation;
    11. }
    12. }
    13. return this;
    14. };

    Aggregate#near(parameters)

    Appends a new $geoNear operator to this aggregate pipeline.

    Parameters:

    Returns:

    See:

    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#option(options, number, boolean, object)

    Lets you set arbitrary options, for middleware or plugins.

    Parameters:

    Returns:

    See:

    Example:

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

    show code

    1. Aggregate.prototype.option = function(value) {
    2. for (var key in value) {
    3. this.options[key] = value[key];
    4. }
    5. return this;
    6. };

    Aggregate#pipeline()

    Returns the current pipeline

    Returns:

    Example:

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

    show code

    1. Aggregate.prototype.pipeline = function() {
    2. return this._pipeline;
    3. };

    Aggregate#project(arg)

    Appends a new $project operator to this aggregate pipeline.

    Parameters:

    Returns:

    See:

    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 ] } });

    show code

    1. Aggregate.prototype.project = function(arg) {
    2. var fields = {};
    3. if (typeof arg === 'object' && !util.isArray(arg)) {
    4. Object.keys(arg).forEach(function(field) {
    5. fields[field] = arg[field];
    6. });
    7. } else if (arguments.length === 1 && typeof arg === 'string') {
    8. arg.split(/\s+/).forEach(function(field) {
    9. if (!field) {
    10. return;
    11. }
    12. var include = field[0] === '-' ? 0 : 1;
    13. if (include === 0) {
    14. field = field.substring(1);
    15. }
    16. fields[field] = include;
    17. });
    18. } else {
    19. throw new Error('Invalid project() argument. Must be string or object');
    20. }
    21. return this.append({$project: fields});
    22. };

    Aggregate#read(pref, [tags])

    Sets the readPreference option for the aggregation query.

    Parameters:

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

    See:

    Example:

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

    show code

    1. Aggregate.prototype.read = function(pref, tags) {
    2. if (!this.options) {
    3. this.options = {};
    4. }
    5. read.call(this, pref, tags);
    6. return this;
    7. };

    Aggregate#sample(size)

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

    Parameters:

    • size <Number> number of random documents to pick

    Returns:

    See:

    Examples:

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

    show code

    1. Aggregate.prototype.sample = function(size) {
    2. return this.append({$sample: {size: size}});
    3. };

    Aggregate#skip(num)

    Appends a new $skip operator to this aggregate pipeline.

    Parameters:

    • num <Number> number of records to skip before next stage

    Returns:

    See:

    Examples:

    1. aggregate.skip(10);

    Aggregate#sort(arg)

    Appends a new $sort operator to this aggregate pipeline.

    Parameters:

    Returns:

    See:

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

    show code

    1. Aggregate.prototype.sort = function(arg) {
    2. // TODO refactor to reuse the query builder logic
    3. var sort = {};
    4. if (arg.constructor.name === 'Object') {
    5. var desc = ['desc', 'descending', -1];
    6. Object.keys(arg).forEach(function(field) {
    7. // If sorting by text score, skip coercing into 1/-1
    8. if (arg[field] instanceof Object && arg[field].$meta) {
    9. sort[field] = arg[field];
    10. return;
    11. }
    12. sort[field] = desc.indexOf(arg[field]) === -1 ? 1 : -1;
    13. });
    14. } else if (arguments.length === 1 && typeof arg === 'string') {
    15. arg.split(/\s+/).forEach(function(field) {
    16. if (!field) {
    17. return;
    18. }
    19. var ascend = field[0] === '-' ? -1 : 1;
    20. if (ascend === -1) {
    21. field = field.substring(1);
    22. }
    23. sort[field] = ascend;
    24. });
    25. } else {
    26. throw new TypeError('Invalid sort() argument. Must be a string or object.');
    27. }
    28. return this.append({$sort: sort});
    29. };

    Aggregate#then([resolve], [reject])

    Provides promise for aggregate.

    Parameters:

    Returns:

    See:

    Example:

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

    show code

    1. Aggregate.prototype.then = function(resolve, reject) {
    2. return this.exec().then(resolve, reject);
    3. };

    Aggregate#unwind(fields)

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

    Parameters:

    • fields <String> the field(s) to unwind

    Returns:

    See:

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

    show code

    1. Aggregate.prototype.unwind = function() {
    2. var args = utils.args(arguments);
    3. var res = [];
    4. for (var i = 0; i < args.length; ++i) {
    5. var arg = args[i];
    6. if (arg && typeof arg === 'object') {
    7. res.push({ $unwind: arg });
    8. } else if (typeof arg === 'string') {
    9. res.push({
    10. $unwind: (arg && arg.charAt(0) === '$') ? arg : '$' + arg
    11. });
    12. } else {
    13. throw new Error('Invalid arg "' + arg + '" to unwind(), ' +
    14. 'must be string or object');
    15. }
    16. }
    17. return this.append.apply(this, res);
    18. };

  • ES6Promise.js

    ES6Promise(fn)

    ES6 Promise wrapper constructor.

    Parameters:

    • fn <Function> a function which will be called when the promise is resolved that accepts fn(err, ...){} as signature

    Promises are returned from executed queries. Example:

    1. var query = Candy.find({ bar: true });
    2. var promise = query.exec();

    DEPRECATED. Mongoose 5.0 will use native promises by default (or bluebird,
    if native promises are not present) but still
    support plugging in your own ES6-compatible promises library. Mongoose 5.0
    will not support mpromise.

    show code

    1. function ES6Promise() {
    2. throw new Error('Can\'t use ES6 promise with mpromise style constructor');
    3. }
    4. ES6Promise.use = function(Promise) {
    5. ES6Promise.ES6 = Promise;
    6. };
    7. module.exports = ES6Promise;

  • utils.js

    exports.each(arr, fn)

    Executes a function on each element of an array (like _.each)

    show code

    1. exports.each = function(arr, fn) {
    2. for (var i = 0; i < arr.length; ++i) {
    3. fn(arr[i]);
    4. }
    5. };

    Parameters:


    exports.mergeClone(to, fromObj)

    merges to with a copy of from

    show code

    1. exports.mergeClone = function(to, fromObj) {
    2. var keys = Object.keys(fromObj);
    3. var len = keys.length;
    4. var i = 0;
    5. var key;
    6. while (i < len) {
    7. key = keys[i++];
    8. if (typeof to[key] === 'undefined') {
    9. // make sure to retain key order here because of a bug handling the $each
    10. // operator in mongodb 2.4.4
    11. to[key] = exports.clone(fromObj[key], {
    12. retainKeyOrder: 1,
    13. flattenDecimals: false
    14. });
    15. } else {
    16. if (exports.isObject(fromObj[key])) {
    17. var obj = fromObj[key];
    18. if (isMongooseObject(fromObj[key]) && !fromObj[key].isMongooseBuffer) {
    19. obj = obj.toObject({ transform: false, virtuals: false });
    20. }
    21. if (fromObj[key].isMongooseBuffer) {
    22. obj = new Buffer(obj);
    23. }
    24. exports.mergeClone(to[key], obj);
    25. } else {
    26. // make sure to retain key order here because of a bug handling the
    27. // $each operator in mongodb 2.4.4
    28. to[key] = exports.clone(fromObj[key], {
    29. retainKeyOrder: 1,
    30. flattenDecimals: false
    31. });
    32. }
    33. }
    34. }
    35. };

    Parameters:


    exports.pluralization

    Pluralization rules.

    show code

    1. exports.pluralization = [
    2. [/(m)an$/gi, '$1en'],
    3. [/(pe)rson$/gi, '$1ople'],
    4. [/(child)$/gi, '$1ren'],
    5. [/^(ox)$/gi, '$1en'],
    6. [/(ax|test)is$/gi, '$1es'],
    7. [/(octop|vir)us$/gi, '$1i'],
    8. [/(alias|status)$/gi, '$1es'],
    9. [/(bu)s$/gi, '$1ses'],
    10. [/(buffal|tomat|potat)o$/gi, '$1oes'],
    11. [/([ti])um$/gi, '$1a'],
    12. [/sis$/gi, 'ses'],
    13. [/(?:([^f])fe|([lr])f)$/gi, '$1$2ves'],
    14. [/(hive)$/gi, '$1s'],
    15. [/([^aeiouy]|qu)y$/gi, '$1ies'],
    16. [/(x|ch|ss|sh)$/gi, '$1es'],
    17. [/(matr|vert|ind)ix|ex$/gi, '$1ices'],
    18. [/([m|l])ouse$/gi, '$1ice'],
    19. [/(kn|w|l)ife$/gi, '$1ives'],
    20. [/(quiz)$/gi, '$1zes'],
    21. [/s$/gi, 's'],
    22. [/([^a-z])$/, '$1'],
    23. [/$/gi, 's']
    24. ];
    25. var rules = exports.pluralization;

    These rules are applied while processing the argument to toCollectionName.


    exports.uncountables

    Uncountable words.

    show code

    1. exports.uncountables = [
    2. 'advice',
    3. 'energy',
    4. 'excretion',
    5. 'digestion',
    6. 'cooperation',
    7. 'health',
    8. 'justice',
    9. 'labour',
    10. 'machinery',
    11. 'equipment',
    12. 'information',
    13. 'pollution',
    14. 'sewage',
    15. 'paper',
    16. 'money',
    17. 'species',
    18. 'series',
    19. 'rain',
    20. 'rice',
    21. 'fish',
    22. 'sheep',
    23. 'moose',
    24. 'deer',
    25. 'news',
    26. 'expertise',
    27. 'status',
    28. 'media'
    29. ];
    30. var uncountables = exports.uncountables;

    These words are applied while processing the argument to toCollectionName.


  • browser.js

    function Object() { [native code] }#Promise()%20%7B%20%5Bnative%20code%5D%20%7D-Promise)

    The Mongoose Promise constructor.


    exports.Document()

    The Mongoose browser Document constructor.


    exports.Error()

    The MongooseError constructor.


    exports.PromiseProvider()

    Storage layer for mongoose promises


    exports.Schema()

    The Mongoose Schema constructor

    Example:

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

    exports.VirtualType()

    The Mongoose VirtualType constructor


    exports#SchemaTypes

    The various Mongoose SchemaTypes.

    Note:

    Alias of mongoose.Schema.Types for backwards compatibility.

    show code

    1. exports.SchemaType = require('./schematype.js');

    See:


    exports#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;

    show code

    1. exports.Types = require('./types');

    exports#utils

    Internal utils

    show code

    1. exports.utils = require('./utils.js');

  • promise.js

    Promise#addBack(listener)

    Adds a single function as a listener to both err and complete.

    Parameters:

    Returns:

    It will be executed with traditional node.js argument position when the promise is resolved.

    1. promise.addBack(function (err, args...) {
    2. if (err) return handleError(err);
    3. console.log('success');
    4. })

    Alias of mpromise#onResolve.

    Deprecated. Use onResolve instead.


    Promise#addCallback(listener)

    Adds a listener to the complete (success) event.

    Parameters:

    Returns:

    Alias of mpromise#onFulfill.

    Deprecated. Use onFulfill instead.


    Promise#addErrback(listener)

    Adds a listener to the err (rejected) event.

    Parameters:

    Returns:

    Alias of mpromise#onReject.

    Deprecated. Use onReject instead.


    Promise#catch(onReject)

    ES6-style .catch() shorthand

    Parameters:

    Returns:


    Promise#end()

    Signifies that this promise was the last in a chain of then()s: if a handler passed to the call to then which produced this promise throws, the exception will go uncaught.

    See:

    Example:

    1. var p = new Promise;
    2. p.then(function(){ throw new Error('shucks') });
    3. setTimeout(function () {
    4. p.fulfill();
    5. // error was caught and swallowed by the promise returned from
    6. // p.then(). we either have to always register handlers on
    7. // the returned promises or we can do the following...
    8. }, 10);
    9. // this time we use .end() which prevents catching thrown errors
    10. var p = new Promise;
    11. var p2 = p.then(function(){ throw new Error('shucks') }).end(); // &lt;--
    12. setTimeout(function () {
    13. p.fulfill(); // throws "shucks"
    14. }, 10);

    Promise#error(err)

    Rejects this promise with err.

    Parameters:

    Returns:

    If the promise has already been fulfilled or rejected, not action is taken.

    Differs from #reject by first casting err to an Error if it is not instanceof Error.

    show code

    1. Promise.prototype.error = function(err) {
    2. if (!(err instanceof Error)) {
    3. if (err instanceof Object) {
    4. err = util.inspect(err);
    5. }
    6. err = new Error(err);
    7. }
    8. return this.reject(err);
    9. };

    Promise#on(event, listener)

    Adds listener to the event.

    Parameters:

    Returns:

    See:

    If event is either the success or failure event and the event has already been emitted, thelistener is called immediately and passed the results of the original emitted event.


    Promise(fn)

    Promise constructor.

    Parameters:

    • fn <Function> a function which will be called when the promise is resolved that accepts fn(err, ...){} as signature

    Inherits:

    Events:

    • err: Emits when the promise is rejected

    • complete: Emits when the promise is fulfilled

    Promises are returned from executed queries. Example:

    1. var query = Candy.find({ bar: true });
    2. var promise = query.exec();

    DEPRECATED. Mongoose 5.0 will use native promises by default (or bluebird,
    if native promises are not present) but still
    support plugging in your own ES6-compatible promises library. Mongoose 5.0
    will not support mpromise.

    show code

    1. function Promise(fn) {
    2. MPromise.call(this, fn);
    3. }

    Promise#reject(reason)

    Rejects this promise with reason.

    Parameters:

    Returns:

    See:

    If the promise has already been fulfilled or rejected, not action is taken.


    Promise#resolve([err], [val])

    Resolves this promise to a rejected state if err is passed or a fulfilled state if no err is passed.

    Parameters:

    • [err] <Error> error or null
    • [val] <Object> value to fulfill the promise with

    If the promise has already been fulfilled or rejected, not action is taken.

    err will be cast to an Error if not already instanceof Error.

    NOTE: overrides mpromise#resolve to provide error casting.

    show code

    1. Promise.prototype.resolve = function(err) {
    2. if (err) return this.error(err);
    3. return this.fulfill.apply(this, Array.prototype.slice.call(arguments, 1));
    4. };

    Promise#then(onFulFill, onReject)

    Creates a new promise and returns it. If onFulfill or onReject are passed, they are added as SUCCESS/ERROR callbacks to this promise after the nextTick.

    Parameters:

    Returns:

    See:

    Conforms to promises/A+ specification.

    Example:

    1. var promise = Meetups.find({ tags: 'javascript' }).select('_id').exec();
    2. promise.then(function (meetups) {
    3. var ids = meetups.map(function (m) {
    4. return m._id;
    5. });
    6. return People.find({ meetups: { $in: ids } }).exec();
    7. }).then(function (people) {
    8. if (people.length &lt; 10000) {
    9. throw new Error('Too few people!!!');
    10. } else {
    11. throw new Error('Still need more people!!!');
    12. }
    13. }).then(null, function (err) {
    14. assert.ok(err instanceof Error);
    15. });

    Promise.complete(args)

    Fulfills this promise with passed arguments.

    Parameters:

    • args <T>

    Alias of mpromise#fulfill.

    Deprecated. Use fulfill instead.


    Promise.ES6(resolver)

    ES6-style promise constructor wrapper around mpromise.

    show code

    1. Promise.ES6 = function(resolver) {
    2. var promise = new Promise();
    3. // No try/catch for backwards compatibility
    4. resolver(
    5. function() {
    6. promise.complete.apply(promise, arguments);
    7. },
    8. function(e) {
    9. promise.error(e);
    10. });
    11. return promise;
    12. };

    Parameters:

    Returns:


    Promise.fulfill(args)

    Fulfills this promise with passed arguments.

    Parameters:

    • args <T>

    See:


  • schematype.js

    SchemaType#applyGetters(value, scope)

    Applies getters to a value

    Parameters:

    show code

    1. SchemaType.prototype.applyGetters = function(value, scope) {
    2. var v = value,
    3. getters = this.getters,
    4. len = getters.length;
    5. if (!len) {
    6. return v;
    7. }
    8. while (len--) {
    9. v = getters[len].call(scope, v, this);
    10. }
    11. return v;
    12. };

    SchemaType#applySetters(value, scope, init)

    Applies setters

    Parameters:

    show code

    1. SchemaType.prototype.applySetters = function(value, scope, init, priorVal, options) {
    2. var v = this._applySetters(value, scope, init, priorVal, options);
    3. if (v == null) {
    4. return v;
    5. }
    6. // do not cast until all setters are applied #665
    7. v = this.cast(v, scope, init, priorVal, options);
    8. return v;
    9. };

    SchemaType#castForQuery([$conditional], val)

    Cast the given value with the given optional query operator.

    Parameters:

    • [$conditional] <String> query operator, like $eq or $in
    • val <T>

    show code

    1. SchemaType.prototype.castForQuery = function($conditional, val) {
    2. var handler;
    3. if (arguments.length === 2) {
    4. handler = this.$conditionalHandlers[$conditional];
    5. if (!handler) {
    6. throw new Error('Can\'t use ' + $conditional);
    7. }
    8. return handler.call(this, val);
    9. }
    10. val = $conditional;
    11. return this._castForQuery(val);
    12. };

    SchemaType#checkRequired(val)

    Default check for if this path satisfies the required validator.

    Parameters:

    • val <T>

    show code

    1. SchemaType.prototype.checkRequired = function(val) {
    2. return val != null;
    3. };

    SchemaType#default(val)

    Sets a default value for this SchemaType.

    Parameters:

    Returns:

    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 }

    show code

    1. SchemaType.prototype.default = function(val) {
    2. if (arguments.length === 1) {
    3. if (val === void 0) {
    4. this.defaultValue = void 0;
    5. return void 0;
    6. }
    7. this.defaultValue = val;
    8. return this.defaultValue;
    9. } else if (arguments.length > 1) {
    10. this.defaultValue = utils.args(arguments);
    11. }
    12. return this.defaultValue;
    13. };

    SchemaType#doValidate(value, callback, scope)

    Performs a validation of value using the validators declared for this SchemaType.

    Parameters:

    show code

    1. SchemaType.prototype.doValidate = function(value, fn, scope) {
    2. var err = false;
    3. var path = this.path;
    4. var count = this.validators.length;
    5. if (!count) {
    6. return fn(null);
    7. }
    8. var validate = function(ok, validatorProperties) {
    9. if (err) {
    10. return;
    11. }
    12. if (ok === undefined || ok) {
    13. --count || fn(null);
    14. } else {
    15. var ErrorConstructor = validatorProperties.ErrorConstructor || ValidatorError;
    16. err = new ErrorConstructor(validatorProperties);
    17. err.$isValidatorError = true;
    18. fn(err);
    19. }
    20. };
    21. var _this = this;
    22. this.validators.forEach(function(v) {
    23. if (err) {
    24. return;
    25. }
    26. var validator = v.validator;
    27. var ok;
    28. var validatorProperties = utils.clone(v);
    29. validatorProperties.path = path;
    30. validatorProperties.value = value;
    31. if (validator instanceof RegExp) {
    32. validate(validator.test(value), validatorProperties);
    33. } else if (typeof validator === 'function') {
    34. if (value === undefined && validator !== _this.requiredValidator) {
    35. validate(true, validatorProperties);
    36. return;
    37. }
    38. if (validatorProperties.isAsync) {
    39. asyncValidate(validator, scope, value, validatorProperties, validate);
    40. } else if (validator.length === 2 && !('isAsync' in validatorProperties)) {
    41. legacyAsyncValidate(validator, scope, value, validatorProperties,
    42. validate);
    43. } else {
    44. try {
    45. ok = validator.call(scope, value);
    46. } catch (error) {
    47. ok = false;
    48. validatorProperties.reason = error;
    49. }
    50. if (ok && typeof ok.then === 'function') {
    51. ok.then(
    52. function(ok) { validate(ok, validatorProperties); },
    53. function(error) {
    54. validatorProperties.reason = error;
    55. ok = false;
    56. validate(ok, validatorProperties);
    57. });
    58. } else {
    59. validate(ok, validatorProperties);
    60. }
    61. }
    62. }
    63. });
    64. };

    SchemaType#doValidateSync(value, scope)

    Performs a validation of value using the validators declared for this SchemaType.

    Parameters:

    Returns:

    Note:

    This method ignores the asynchronous validators.

    show code

    1. SchemaType.prototype.doValidateSync = function(value, scope) {
    2. var err = null,
    3. path = this.path,
    4. count = this.validators.length;
    5. if (!count) {
    6. return null;
    7. }
    8. var validate = function(ok, validatorProperties) {
    9. if (err) {
    10. return;
    11. }
    12. if (ok !== undefined && !ok) {
    13. var ErrorConstructor = validatorProperties.ErrorConstructor || ValidatorError;
    14. err = new ErrorConstructor(validatorProperties);
    15. err.$isValidatorError = true;
    16. }
    17. };
    18. var validators = this.validators;
    19. if (value === void 0) {
    20. if (this.validators.length > 0 && this.validators[0].type === 'required') {
    21. validators = [this.validators[0]];
    22. } else {
    23. return null;
    24. }
    25. }
    26. validators.forEach(function(v) {
    27. if (err) {
    28. return;
    29. }
    30. var validator = v.validator;
    31. var validatorProperties = utils.clone(v);
    32. validatorProperties.path = path;
    33. validatorProperties.value = value;
    34. var ok;
    35. if (validator instanceof RegExp) {
    36. validate(validator.test(value), validatorProperties);
    37. } else if (typeof validator === 'function') {
    38. // if not async validators
    39. if (validator.length !== 2 && !validatorProperties.isAsync) {
    40. try {
    41. ok = validator.call(scope, value);
    42. } catch (error) {
    43. ok = false;
    44. validatorProperties.reason = error;
    45. }
    46. validate(ok, validatorProperties);
    47. }
    48. }
    49. });
    50. return err;
    51. };

    SchemaType#get(fn)

    Adds a getter to this schematype.

    Parameters:

    Returns:

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

    show code

    1. SchemaType.prototype.get = function(fn) {
    2. if (typeof fn !== 'function') {
    3. throw new TypeError('A getter must be a function.');
    4. }
    5. this.getters.push(fn);
    6. return this;
    7. };

    SchemaType#getDefault(scope, init)

    Gets the default value

    Parameters:

    • scope <Object> the scope which callback are executed
    • init <Boolean>

    show code

    1. SchemaType.prototype.getDefault = function(scope, init) {
    2. var ret = typeof this.defaultValue === 'function'
    3. ? this.defaultValue.call(scope)
    4. : this.defaultValue;
    5. if (ret !== null && ret !== undefined) {
    6. if (typeof ret === 'object' && (!this.options || !this.options.shared)) {
    7. ret = utils.clone(ret, { retainKeyOrder: true });
    8. }
    9. var casted = this.cast(ret, scope, init);
    10. if (casted && casted.$isSingleNested) {
    11. casted.$parent = scope;
    12. }
    13. return casted;
    14. }
    15. return ret;
    16. };

    SchemaType#index(options)

    Declares the index options for this schematype.

    Parameters:

    Returns:

    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

    show code

    1. SchemaType.prototype.index = function(options) {
    2. this._index = options;
    3. utils.expires(this._index);
    4. return this;
    5. };

    SchemaType#required(required, [options.isRequired], [options.ErrorConstructor], [message])

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

    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:

    See:

    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 &gt;= 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:

    show code

    1. SchemaType.prototype.required = function(required, message) {
    2. var customOptions = {};
    3. if (typeof required === 'object') {
    4. customOptions = required;
    5. message = customOptions.message || message;
    6. required = required.isRequired;
    7. }
    8. if (required === false) {
    9. this.validators = this.validators.filter(function(v) {
    10. return v.validator !== this.requiredValidator;
    11. }, this);
    12. this.isRequired = false;
    13. return this;
    14. }
    15. var _this = this;
    16. this.isRequired = true;
    17. this.requiredValidator = function(v) {
    18. // in here, `this` refers to the validating document.
    19. // no validation when this path wasn't selected in the query.
    20. if ('isSelected' in this && !this.isSelected(_this.path) && !this.isModified(_this.path)) {
    21. return true;
    22. }
    23. return ((typeof required === 'function') && !required.apply(this)) ||
    24. _this.checkRequired(v, this);
    25. };
    26. this.originalRequiredValue = required;
    27. if (typeof required === 'string') {
    28. message = required;
    29. required = undefined;
    30. }
    31. var msg = message || MongooseError.messages.general.required;
    32. this.validators.unshift(utils.assign({}, customOptions, {
    33. validator: this.requiredValidator,
    34. message: msg,
    35. type: 'required'
    36. }));
    37. return this;
    38. };

    SchemaType(path, [options], [instance])

    SchemaType constructor

    Parameters:

    show code

    1. function SchemaType(path, options, instance) {
    2. this.path = path;
    3. this.instance = instance;
    4. this.validators = [];
    5. this.setters = [];
    6. this.getters = [];
    7. this.options = options;
    8. this._index = null;
    9. this.selected;
    10. for (var prop in options) {
    11. if (this[prop] && typeof this[prop] === 'function') {
    12. // { unique: true, index: true }
    13. if (prop === 'index' && this._index) {
    14. continue;
    15. }
    16. var val = options[prop];
    17. // Special case so we don't screw up array defaults, see gh-5780
    18. if (prop === 'default') {
    19. this.default(val);
    20. continue;
    21. }
    22. var opts = Array.isArray(val) ? val : [val];
    23. this[prop].apply(this, opts);
    24. }
    25. }
    26. Object.defineProperty(this, '$$context', {
    27. enumerable: false,
    28. configurable: false,
    29. writable: true,
    30. value: null
    31. });
    32. }

    SchemaType#select(val)

    Sets default select() behavior for this path.

    Parameters:

    Returns:

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

    show code

    1. SchemaType.prototype.select = function select(val) {
    2. this.selected = !!val;
    3. return this;
    4. };

    SchemaType#set(fn)

    Adds a setter to this schematype.

    Parameters:

    Returns:

    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 by retreiving its 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 and is set as a value on an actual key.

    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'

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

    NOTE: setters by default do not run on queries by default.

    1. // Will **not** run the `toLower()` setter by default.
    2. User.updateOne({ _id: _id }, { $set: { email: 'AVENUE@Q.COM' } });

    Use the runSettersOnQuery option to opt-in to running setters on User.update():

    1. // Turn on `runSettersOnQuery` to run the setters from your schema.
    2. User.updateOne({ _id: _id }, { $set: { email: 'AVENUE@Q.COM' } }, {
    3. runSettersOnQuery: true
    4. });

    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

    show code

    1. SchemaType.prototype.set = function(fn) {
    2. if (typeof fn !== 'function') {
    3. throw new TypeError('A setter must be a function.');
    4. }
    5. this.setters.push(fn);
    6. return this;
    7. };

    SchemaType#sparse(bool)

    Declares a sparse index.

    Parameters:

    Returns:

    Example:

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

    show code

    1. SchemaType.prototype.sparse = function(bool) {
    2. if (this._index === null || this._index === undefined ||
    3. typeof this._index === 'boolean') {
    4. this._index = {};
    5. } else if (typeof this._index === 'string') {
    6. this._index = {type: this._index};
    7. }
    8. this._index.sparse = bool;
    9. return this;
    10. };

    SchemaType#text(bool)

    Declares a full text index.

    Parameters:

    Returns:

    Example:

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

    show code

    1. SchemaType.prototype.text = function(bool) {
    2. if (this._index === null || this._index === undefined ||
    3. typeof this._index === 'boolean') {
    4. this._index = {};
    5. } else if (typeof this._index === 'string') {
    6. this._index = {type: this._index};
    7. }
    8. this._index.text = bool;
    9. return this;
    10. };

    SchemaType#unique(bool)

    Declares an unique index.

    Parameters:

    Returns:

    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.

    show code

    1. SchemaType.prototype.unique = function(bool) {
    2. if (this._index === false) {
    3. if (!bool) {
    4. return;
    5. }
    6. throw new Error('Path "' + this.path + '" may not have `index` set to ' +
    7. 'false and `unique` set to true');
    8. }
    9. if (this._index == null || this._index === true) {
    10. this._index = {};
    11. } else if (typeof this._index === 'string') {
    12. this._index = {type: this._index};
    13. }
    14. this._index.unique = bool;
    15. return this;
    16. };

    SchemaType#validate(obj, [errorMsg], [type])

    Adds validator(s) for this document path.

    Parameters:

    Returns:

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

    show code

    1. SchemaType.prototype.validate = function(obj, message, type) {
    2. if (typeof obj === 'function' || obj && utils.getFunctionName(obj.constructor) === 'RegExp') {
    3. var properties;
    4. if (message instanceof Object && !type) {
    5. properties = utils.clone(message);
    6. if (!properties.message) {
    7. properties.message = properties.msg;
    8. }
    9. properties.validator = obj;
    10. properties.type = properties.type || 'user defined';
    11. } else {
    12. if (!message) {
    13. message = MongooseError.messages.general.default;
    14. }
    15. if (!type) {
    16. type = 'user defined';
    17. }
    18. properties = {message: message, type: type, validator: obj};
    19. }
    20. this.validators.push(properties);
    21. return this;
    22. }
    23. var i,
    24. length,
    25. arg;
    26. for (i = 0, length = arguments.length; i < length; i++) {
    27. arg = arguments[i];
    28. if (!(arg && utils.getFunctionName(arg.constructor) === 'Object')) {
    29. var msg = 'Invalid validator. Received (' + typeof arg + ') '
    30. + arg
    31. + '. See http://mongoosejs.com/docs/api.html#schematype_SchemaType-validate';
    32. throw new Error(msg);
    33. }
    34. this.validate(arg.validator, arg);
    35. }
    36. return this;
    37. };

    SchemaType._isRef(self, value, doc, init)

    Determines if value is a valid Reference.

    show code

    1. SchemaType._isRef = function(self, value, doc, init) {
    2. // fast path
    3. var ref = init && self.options && self.options.ref;
    4. if (!ref && doc && doc.$__fullPath) {
    5. // checks for
    6. // - this populated with adhoc model and no ref was set in schema OR
    7. // - setting / pushing values after population
    8. var path = doc.$__fullPath(self.path);
    9. var owner = doc.ownerDocument ? doc.ownerDocument() : doc;
    10. ref = owner.populated(path);
    11. }
    12. if (ref) {
    13. if (value == null) {
    14. return true;
    15. }
    16. if (!Buffer.isBuffer(value) && // buffers are objects too
    17. value._bsontype !== 'Binary' // raw binary value from the db
    18. && utils.isObject(value) // might have deselected _id in population query
    19. ) {
    20. return true;
    21. }
    22. }
    23. return false;
    24. };

    Parameters:

    Returns:


  • querystream.js

    QueryStream#__next()

    Pulls the next doc from the cursor.

    See:

    show code

    1. QueryStream.prototype.__next = function() {
    2. if (this.paused || this._destroyed) {
    3. this._running = false;
    4. return this._running;
    5. }
    6. var _this = this;
    7. _this._inline = T_INIT;
    8. _this._cursor.nextObject(function cursorcb(err, doc) {
    9. _this._onNextObject(err, doc);
    10. });
    11. // if onNextObject() was already called in this tick
    12. // return ourselves to the trampoline.
    13. if (T_CONT === this._inline) {
    14. return true;
    15. }
    16. // onNextObject() hasn't fired yet. tell onNextObject
    17. // that its ok to call _next b/c we are not within
    18. // the trampoline anymore.
    19. this._inline = T_IDLE;
    20. };

    QueryStream#_init()

    Initializes the query.

    show code

    1. QueryStream.prototype._init = function() {
    2. if (this._destroyed) {
    3. return;
    4. }
    5. var query = this.query,
    6. model = query.model,
    7. options = query._optionsForExec(model),
    8. _this = this;
    9. try {
    10. query.cast(model);
    11. } catch (err) {
    12. return _this.destroy(err);
    13. }
    14. _this._fields = utils.clone(query._fields);
    15. options.fields = query._castFields(_this._fields);
    16. model.collection.find(query._conditions, options, function(err, cursor) {
    17. if (err) {
    18. return _this.destroy(err);
    19. }
    20. _this._cursor = cursor;
    21. _this._next();
    22. });
    23. };

    QueryStream#_next()

    Trampoline for pulling the next doc from cursor.

    See:

    show code

    1. QueryStream.prototype._next = function _next() {
    2. if (this.paused || this._destroyed) {
    3. this._running = false;
    4. return this._running;
    5. }
    6. this._running = true;
    7. if (this._buffer && this._buffer.length) {
    8. var arg;
    9. while (!this.paused && !this._destroyed && (arg = this._buffer.shift())) { // eslint-disable-line no-cond-assign
    10. this._onNextObject.apply(this, arg);
    11. }
    12. }
    13. // avoid stack overflows with large result sets.
    14. // trampoline instead of recursion.
    15. while (this.__next()) {
    16. }
    17. };

    QueryStream#_onNextObject(err, doc)

    Transforms raw docs returned from the cursor into a model instance.

    Parameters:

    show code

    1. QueryStream.prototype._onNextObject = function _onNextObject(err, doc) {
    2. if (this._destroyed) {
    3. return;
    4. }
    5. if (this.paused) {
    6. this._buffer || (this._buffer = []);
    7. this._buffer.push([err, doc]);
    8. this._running = false;
    9. return this._running;
    10. }
    11. if (err) {
    12. return this.destroy(err);
    13. }
    14. // when doc is null we hit the end of the cursor
    15. if (!doc) {
    16. this.emit('end');
    17. return this.destroy();
    18. }
    19. var opts = this.query._mongooseOptions;
    20. if (!opts.populate) {
    21. return opts.lean === true ?
    22. emit(this, doc) :
    23. createAndEmit(this, null, doc);
    24. }
    25. var _this = this;
    26. var pop = helpers.preparePopulationOptionsMQ(_this.query, _this.query._mongooseOptions);
    27. // Hack to work around gh-3108
    28. pop.forEach(function(option) {
    29. delete option.model;
    30. });
    31. pop.__noPromise = true;
    32. _this.query.model.populate(doc, pop, function(err, doc) {
    33. if (err) {
    34. return _this.destroy(err);
    35. }
    36. return opts.lean === true ?
    37. emit(_this, doc) :
    38. createAndEmit(_this, pop, doc);
    39. });
    40. };
    41. function createAndEmit(self, populatedIds, doc) {
    42. var instance = helpers.createModel(self.query.model, doc, self._fields);
    43. var opts = populatedIds ?
    44. {populated: populatedIds} :
    45. undefined;
    46. instance.init(doc, opts, function(err) {
    47. if (err) {
    48. return self.destroy(err);
    49. }
    50. emit(self, instance);
    51. });
    52. }

    QueryStream#destroy([err])

    Destroys the stream, closing the underlying cursor, which emits the close event. No more events will be emitted after the close event.

    Parameters:

    show code

    1. QueryStream.prototype.destroy = function(err) {
    2. if (this._destroyed) {
    3. return;
    4. }
    5. this._destroyed = true;
    6. this._running = false;
    7. this.readable = false;
    8. if (this._cursor) {
    9. this._cursor.close();
    10. }
    11. if (err) {
    12. this.emit('error', err);
    13. }
    14. this.emit('close');
    15. };

    QueryStream#pause()

    Pauses this stream.

    show code

    1. QueryStream.prototype.pause = function() {
    2. this.paused = true;
    3. };

    QueryStream#pipe()

    Pipes this query stream into another stream. This method is inherited from NodeJS Streams.

    See:

    Example:

    1. query.stream().pipe(writeStream [, options])

    QueryStream(query, [options])

    Provides a Node.js 0.8 style ReadStream interface for Queries.

    Parameters:

    Inherits:

    Events:

    • data: emits a single Mongoose document

    • error: emits when an error occurs during streaming. This will emit before the close event.

    • close: emits when the stream reaches the end of the cursor or an error occurs, or the stream is manually destroyed. After this event, no more events are emitted.

    1. var stream = Model.find().stream();
    2. stream.on('data', function (doc) {
    3. // do something with the mongoose document
    4. }).on('error', function (err) {
    5. // handle the error
    6. }).on('close', function () {
    7. // the stream is closed
    8. });

    The stream interface allows us to simply “plug-in” to other Node.js 0.8 style write streams.

    1. Model.where('created').gte(twoWeeksAgo).stream().pipe(writeStream);

    Valid options

    • transform: optional function which accepts a mongoose document. The return value of the function will be emitted on data.

    Example

    1. // JSON.stringify all documents before emitting
    2. var stream = Thing.find().stream({ transform: JSON.stringify });
    3. stream.pipe(writeStream);

    NOTE: plugging into an HTTP response will \not* work out of the box. Those streams expect only strings or buffers to be emitted, so first formatting our documents as strings/buffers is necessary.*

    NOTE: these streams are Node.js 0.8 style read streams which differ from Node.js 0.10 style. Node.js 0.10 streams are not well tested yet and are not guaranteed to work.

    show code

    1. function QueryStream(query, options) {
    2. Stream.call(this);
    3. this.query = query;
    4. this.readable = true;
    5. this.paused = false;
    6. this._cursor = null;
    7. this._destroyed = null;
    8. this._fields = null;
    9. this._buffer = null;
    10. this._inline = T_INIT;
    11. this._running = false;
    12. this._transform = options && typeof options.transform === 'function'
    13. ? options.transform
    14. : K;
    15. // give time to hook up events
    16. var _this = this;
    17. process.nextTick(function() {
    18. _this._init();
    19. });
    20. }

    QueryStream#resume()

    Resumes this stream.

    show code

    1. QueryStream.prototype.resume = function() {
    2. this.paused = false;
    3. if (!this._cursor) {
    4. // cannot start if not initialized
    5. return;
    6. }
    7. // are we within the trampoline?
    8. if (T_INIT === this._inline) {
    9. return;
    10. }
    11. if (!this._running) {
    12. // outside QueryStream control, need manual restart
    13. return this._next();
    14. }
    15. };

    QueryStream#paused

    Flag stating whether or not this stream is paused.

    show code

    1. QueryStream.prototype.paused;
    2. // trampoline flags
    3. var T_INIT = 0;
    4. var T_IDLE = 1;
    5. var T_CONT = 2;

    QueryStream#readable

    Flag stating whether or not this stream is readable.

    show code

    1. QueryStream.prototype.readable;

  • model.js

    Model#$__delta()

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


    Model#$__version()

    Appends versioning to the where and update clauses.


    Model#$__where()

    Returns a query object


    Model#$where(argument)

    Creates a Query and specifies a $where condition.

    Parameters:

    • argument <String, Function> is a javascript string or anonymous function

    Returns:

    See:

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

    Signal that we desire an increment of this documents version.

    See:

    Example:

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

    show code

    1. Model.prototype.increment = function increment() {
    2. this.$__.version = VERSION_ALL;
    3. return this;
    4. };

    Model#model(name)

    Returns another Model instance.

    Parameters:

    Example:

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

    show code

    1. Model.prototype.model = function model(name) {
    2. return this.db.model(name);
    3. };

    Model(doc)

    Model constructor

    Parameters:

    • doc <Object> values with which to create the document

    Inherits:

    Events:

    • error: If listening to this event, ‘error’ is emitted when a document was saved without passing a callback and an error occurred. If not listening, the event bubbles to the connection used to create this Model.

    • index: Emitted after Model#ensureIndexes completes. If an error occurred it is passed with the event.

    • index-single-start: Emitted when an individual index starts within Model#ensureIndexes. The fields and options being used to build the index are also passed with the event.

    • index-single-done: Emitted when an individual index finishes within Model#ensureIndexes. If an error occurred it is passed with the event. The fields, options, and index name are also passed.

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

    show code

    1. function Model(doc, fields, skipId) {
    2. if (fields instanceof Schema) {
    3. throw new TypeError('2nd argument to `Model` must be a POJO or string, ' +
    4. '**not** a schema. Make sure you\'re calling `mongoose.model()`, not ' +
    5. '`mongoose.Model()`.');
    6. }
    7. Document.call(this, doc, fields, skipId, true);
    8. }

    Model#remove([fn])

    Removes this document from the db.

    Parameters:

    Returns:

    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 recive errors

    Example:

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

    show code

    1. Model.prototype.remove = function remove(options, fn) {
    2. if (typeof options === 'function') {
    3. fn = options;
    4. options = undefined;
    5. }
    6. var _this = this;
    7. if (!options) {
    8. options = {};
    9. }
    10. if (this.$__.removing) {
    11. if (fn) {
    12. this.$__.removing.then(
    13. function(res) { fn(null, res); },
    14. function(err) { fn(err); });
    15. }
    16. return this;
    17. }
    18. if (this.$__.isDeleted) {
    19. setImmediate(function() {
    20. fn(null, _this);
    21. });
    22. return this;
    23. }
    24. var Promise = PromiseProvider.get();
    25. if (fn) {
    26. fn = this.constructor.$wrapCallback(fn);
    27. }
    28. this.$__.removing = new Promise.ES6(function(resolve, reject) {
    29. var where = _this.$__where();
    30. if (where instanceof Error) {
    31. reject(where);
    32. fn && fn(where);
    33. return;
    34. }
    35. if (!options.safe && _this.schema.options.safe) {
    36. options.safe = _this.schema.options.safe;
    37. }
    38. _this.collection.remove(where, options, function(err) {
    39. if (!err) {
    40. _this.$__.isDeleted = true;
    41. _this.emit('remove', _this);
    42. _this.constructor.emit('remove', _this);
    43. resolve(_this);
    44. fn && fn(null, _this);
    45. return;
    46. }
    47. _this.$__.isDeleted = false;
    48. reject(err);
    49. fn && fn(err);
    50. });
    51. });
    52. return this.$__.removing;
    53. };

    Model#save([options], [options.safe], [options.validateBeforeSave], [fn])

    Saves this document.

    Parameters:

    Returns:

    See:

    Example:

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

    The callback will receive three parameters

    1. err if an error occurred
    2. product which is the saved product
    3. 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. });

    For legacy reasons, mongoose stores object keys in reverse order on initial
    save. That is, { a: 1, b: 2 } will be saved as { b: 2, a: 1 } in
    MongoDB. To override this behavior, set
    the toObject.retainKeyOrder option
    to true on your schema.

    show code

    1. Model.prototype.save = function(options, fn) {
    2. if (typeof options === 'function') {
    3. fn = options;
    4. options = undefined;
    5. }
    6. if (!options) {
    7. options = {};
    8. }
    9. if (fn) {
    10. fn = this.constructor.$wrapCallback(fn);
    11. }
    12. return this.$__save(options, fn);
    13. };

    Model.aggregate([...], [callback])

    Performs aggregations on the models collection.

    show code

    1. Model.aggregate = function aggregate() {
    2. var args = [].slice.call(arguments),
    3. aggregate,
    4. callback;
    5. if (typeof args[args.length - 1] === 'function') {
    6. callback = args.pop();
    7. }
    8. if (args.length === 1 && util.isArray(args[0])) {
    9. aggregate = new Aggregate(args[0]);
    10. } else {
    11. aggregate = new Aggregate(args);
    12. }
    13. aggregate.model(this);
    14. if (typeof callback === 'undefined') {
    15. return aggregate;
    16. }
    17. if (callback) {
    18. callback = this.$wrapCallback(callback);
    19. }
    20. aggregate.exec(callback);
    21. };

    Parameters:

    Returns:

    See:

    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. function (err, res) {
    6. if (err) return handleError(err);
    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.bulkWrite(ops, [options], [callback])

    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.

    show code

    1. Model.bulkWrite = function(ops, options, callback) {
    2. var Promise = PromiseProvider.get();
    3. var _this = this;
    4. if (typeof options === 'function') {
    5. callback = options;
    6. options = null;
    7. }
    8. if (callback) {
    9. callback = this.$wrapCallback(callback);
    10. }
    11. options = options || {};
    12. var validations = ops.map(function(op) {
    13. if (op['insertOne']) {
    14. return function(callback) {
    15. op['insertOne']['document'] = new _this(op['insertOne']['document']);
    16. op['insertOne']['document'].validate({ __noPromise: true }, function(error) {
    17. if (error) {
    18. return callback(error);
    19. }
    20. callback(null);
    21. });
    22. };
    23. } else if (op['updateOne']) {
    24. op = op['updateOne'];
    25. return function(callback) {
    26. try {
    27. op['filter'] = cast(_this.schema, op['filter']);
    28. op['update'] = castUpdate(_this.schema, op['update'],
    29. _this.schema.options.strict);
    30. if (op.setDefaultsOnInsert) {
    31. setDefaultsOnInsert(op['filter'], _this.schema, op['update'], {
    32. setDefaultsOnInsert: true,
    33. upsert: op.upsert
    34. });
    35. }
    36. } catch (error) {
    37. return callback(error);
    38. }
    39. callback(null);
    40. };
    41. } else if (op['updateMany']) {
    42. op = op['updateMany'];
    43. return function(callback) {
    44. try {
    45. op['filter'] = cast(_this.schema, op['filter']);
    46. op['update'] = castUpdate(_this.schema, op['update'], {
    47. strict: _this.schema.options.strict,
    48. overwrite: false
    49. });
    50. if (op.setDefaultsOnInsert) {
    51. setDefaultsOnInsert(op['filter'], _this.schema, op['update'], {
    52. setDefaultsOnInsert: true,
    53. upsert: op.upsert
    54. });
    55. }
    56. } catch (error) {
    57. return callback(error);
    58. }
    59. callback(null);
    60. };
    61. } else if (op['replaceOne']) {
    62. return function(callback) {
    63. try {
    64. op['replaceOne']['filter'] = cast(_this.schema,
    65. op['replaceOne']['filter']);
    66. } catch (error) {
    67. return callback(error);
    68. }
    69. // set `skipId`, otherwise we get "_id field cannot be changed"
    70. op['replaceOne']['replacement'] =
    71. new _this(op['replaceOne']['replacement'], null, true);
    72. op['replaceOne']['replacement'].validate({ __noPromise: true }, function(error) {
    73. if (error) {
    74. return callback(error);
    75. }
    76. callback(null);
    77. });
    78. };
    79. } else if (op['deleteOne']) {
    80. return function(callback) {
    81. try {
    82. op['deleteOne']['filter'] = cast(_this.schema,
    83. op['deleteOne']['filter']);
    84. } catch (error) {
    85. return callback(error);
    86. }
    87. callback(null);
    88. };
    89. } else if (op['deleteMany']) {
    90. return function(callback) {
    91. try {
    92. op['deleteMany']['filter'] = cast(_this.schema,
    93. op['deleteMany']['filter']);
    94. } catch (error) {
    95. return callback(error);
    96. }
    97. callback(null);
    98. };
    99. } else {
    100. return function(callback) {
    101. callback(new Error('Invalid op passed to `bulkWrite()`'));
    102. };
    103. }
    104. });
    105. var promise = new Promise.ES6(function(resolve, reject) {
    106. parallel(validations, function(error) {
    107. if (error) {
    108. callback && callback(error);
    109. return reject(error);
    110. }
    111. _this.collection.bulkWrite(ops, options, function(error, res) {
    112. if (error) {
    113. callback && callback(error);
    114. return reject(error);
    115. }
    116. callback && callback(null, res);
    117. resolve(res);
    118. });
    119. });
    120. });
    121. return promise;
    122. };

    Parameters:

    • ops <Array>
    • [options] <Object>
    • [callback] <Function> callback <code>function(error, bulkWriteOpResult) {}</code>

    Returns:

    • <Promise> resolves to a `BulkWriteOpResult` if the operation succeeds

    See:

    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.count(conditions, [callback])

    Counts number of matching documents in a database collection.

    show code

    1. Model.count = function count(conditions, callback) {
    2. if (typeof conditions === 'function') {
    3. callback = conditions;
    4. conditions = {};
    5. }
    6. // get the mongodb collection object
    7. var mq = new this.Query({}, {}, this, this.collection);
    8. if (callback) {
    9. callback = this.$wrapCallback(callback);
    10. }
    11. return mq.count(conditions, callback);
    12. };

    Parameters:

    Returns:

    Example:

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

    Model.create(doc(s), [callback])

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

    show code

    1. Model.create = function create(doc, callback) {
    2. var args;
    3. var cb;
    4. var discriminatorKey = this.schema.options.discriminatorKey;
    5. if (Array.isArray(doc)) {
    6. args = doc;
    7. cb = callback;
    8. } else {
    9. var last = arguments[arguments.length - 1];
    10. // Handle falsy callbacks re: #5061
    11. if (typeof last === 'function' || !last) {
    12. cb = last;
    13. args = utils.args(arguments, 0, arguments.length - 1);
    14. } else {
    15. args = utils.args(arguments);
    16. }
    17. }
    18. var Promise = PromiseProvider.get();
    19. var _this = this;
    20. if (cb) {
    21. cb = this.$wrapCallback(cb);
    22. }
    23. var promise = new Promise.ES6(function(resolve, reject) {
    24. if (args.length === 0) {
    25. setImmediate(function() {
    26. cb && cb(null);
    27. resolve(null);
    28. });
    29. return;
    30. }
    31. var toExecute = [];
    32. var firstError;
    33. args.forEach(function(doc) {
    34. toExecute.push(function(callback) {
    35. var Model = _this.discriminators && doc[discriminatorKey] ?
    36. _this.discriminators[doc[discriminatorKey]] :
    37. _this;
    38. var toSave = doc;
    39. var callbackWrapper = function(error, doc) {
    40. if (error) {
    41. if (!firstError) {
    42. firstError = error;
    43. }
    44. return callback(null, { error: error });
    45. }
    46. callback(null, { doc: doc });
    47. };
    48. if (!(toSave instanceof Model)) {
    49. try {
    50. toSave = new Model(toSave);
    51. } catch (error) {
    52. return callbackWrapper(error);
    53. }
    54. }
    55. // Hack to avoid getting a promise because of
    56. // $__registerHooksFromSchema
    57. if (toSave.$__original_save) {
    58. toSave.$__original_save({ __noPromise: true }, callbackWrapper);
    59. } else {
    60. toSave.save({ __noPromise: true }, callbackWrapper);
    61. }
    62. });
    63. });
    64. parallel(toExecute, function(error, res) {
    65. var savedDocs = [];
    66. var len = res.length;
    67. for (var i = 0; i < len; ++i) {
    68. if (res[i].doc) {
    69. savedDocs.push(res[i].doc);
    70. }
    71. }
    72. if (firstError) {
    73. if (cb) {
    74. cb(firstError, savedDocs);
    75. } else {
    76. reject(firstError);
    77. }
    78. return;
    79. }
    80. if (doc instanceof Array) {
    81. resolve(savedDocs);
    82. cb && cb.call(_this, null, savedDocs);
    83. } else {
    84. resolve.apply(promise, savedDocs);
    85. if (cb) {
    86. cb.apply(_this, [null].concat(savedDocs));
    87. }
    88. }
    89. });
    90. });
    91. return promise;
    92. };

    Parameters:

    Returns:

    This function triggers the following middleware

    • save()

    Example:

    1. // pass individual docs
    2. Candy.create({ type: 'jelly bean' }, { type: 'snickers' }, function (err, jellybean, snickers) {
    3. if (err) // ...
    4. });
    5. // pass an array
    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.createIndexes([options], [cb])

    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.

    show code

    1. Model.createIndexes = function createIndexes(options, callback) {
    2. if (typeof options === 'function') {
    3. callback = options;
    4. options = {};
    5. }
    6. options = options || {};
    7. options.createIndex = true;
    8. return this.ensureIndexes(options, callback);
    9. };
    10. function _ensureIndexes(model, options, callback) {
    11. var indexes = model.schema.indexes();
    12. options = options || {};
    13. var done = function(err) {
    14. if (err && model.schema.options.emitIndexErrors) {
    15. model.emit('error', err);
    16. }
    17. model.emit('index', err);
    18. callback && callback(err);
    19. };
    20. if (!indexes.length) {
    21. setImmediate(function() {
    22. done();
    23. });
    24. return;
    25. }
    26. // Indexes are created one-by-one to support how MongoDB < 2.4 deals
    27. // with background indexes.
    28. var indexSingleDone = function(err, fields, options, name) {
    29. model.emit('index-single-done', err, fields, options, name);
    30. };
    31. var indexSingleStart = function(fields, options) {
    32. model.emit('index-single-start', fields, options);
    33. };
    34. var create = function() {
    35. if (options._automatic) {
    36. if (model.schema.options.autoIndex === false ||
    37. (model.schema.options.autoIndex == null && model.db.config.autoIndex === false)) {
    38. return done();
    39. }
    40. }
    41. var index = indexes.shift();
    42. if (!index) return done();
    43. var indexFields = index[0];
    44. var indexOptions = index[1];
    45. _handleSafe(options);
    46. indexSingleStart(indexFields, options);
    47. var methodName = options.createIndex ? 'createIndex' : 'ensureIndex';
    48. model.collection[methodName](indexFields, indexOptions, utils.tick(function(err, name) {
    49. indexSingleDone(err, indexFields, indexOptions, name);
    50. if (err) {
    51. return done(err);
    52. }
    53. create();
    54. }));
    55. };
    56. setImmediate(function() {
    57. // If buffering is off, do this manually.
    58. if (options._automatic && !model.collection.collection) {
    59. model.collection.addQueue(create, []);
    60. } else {
    61. create();
    62. }
    63. });
    64. }
    65. function _handleSafe(options) {
    66. if (options.safe) {
    67. if (typeof options.safe === 'boolean') {
    68. options.w = options.safe;
    69. delete options.safe;
    70. }
    71. if (typeof options.safe === 'object') {
    72. options.w = options.safe.w;
    73. options.j = options.safe.j;
    74. options.wtimeout = options.safe.wtimeout;
    75. delete options.safe;
    76. }
    77. }
    78. }

    Parameters:

    Returns:


    Model.deleteMany(conditions, [callback])

    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.

    show code

    1. Model.deleteMany = function deleteMany(conditions, callback) {
    2. if (typeof conditions === 'function') {
    3. callback = conditions;
    4. conditions = {};
    5. }
    6. // get the mongodb collection object
    7. var mq = new this.Query(conditions, {}, this, this.collection);
    8. if (callback) {
    9. callback = this.$wrapCallback(callback);
    10. }
    11. return mq.deleteMany(callback);
    12. };

    Parameters:

    Returns:

    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.deleteOne(conditions, [callback])

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

    show code

    1. Model.deleteOne = function deleteOne(conditions, callback) {
    2. if (typeof conditions === 'function') {
    3. callback = conditions;
    4. conditions = {};
    5. }
    6. // get the mongodb collection object
    7. var mq = new this.Query(conditions, {}, this, this.collection);
    8. if (callback) {
    9. callback = this.$wrapCallback(callback);
    10. }
    11. return mq.deleteOne(callback);
    12. };

    Parameters:

    Returns:

    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.discriminator(name, schema)

    Adds a discriminator type.

    show code

    1. Model.discriminator = function(name, schema) {
    2. var model;
    3. if (typeof name === 'function') {
    4. model = name;
    5. name = utils.getFunctionName(model);
    6. if (!(model.prototype instanceof Model)) {
    7. throw new Error('The provided class ' + name + ' must extend Model');
    8. }
    9. }
    10. schema = discriminator(this, name, schema);
    11. if (this.db.models[name]) {
    12. throw new OverwriteModelError(name);
    13. }
    14. schema.$isRootDiscriminator = true;
    15. model = this.db.model(model || name, schema, this.collection.name);
    16. this.discriminators[name] = model;
    17. var d = this.discriminators[name];
    18. d.prototype.__proto__ = this.prototype;
    19. Object.defineProperty(d, 'baseModelName', {
    20. value: this.modelName,
    21. configurable: true,
    22. writable: false
    23. });
    24. // apply methods and statics
    25. applyMethods(d, schema);
    26. applyStatics(d, schema);
    27. return d;
    28. };
    29. // Model (class) features

    Parameters:

    • name <String> discriminator model name
    • schema <Schema> discriminator model schema

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

    Model.distinct(field, [conditions], [callback])

    Creates a Query for a distinct operation.

    show code

    1. Model.distinct = function distinct(field, conditions, callback) {
    2. // get the mongodb collection object
    3. var mq = new this.Query({}, {}, this, this.collection);
    4. if (typeof conditions === 'function') {
    5. callback = conditions;
    6. conditions = {};
    7. }
    8. if (callback) {
    9. callback = this.$wrapCallback(callback);
    10. }
    11. return mq.distinct(field, conditions, callback);
    12. };

    Parameters:

    Returns:

    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.ensureIndexes([options], [cb])

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

    show code

    1. Model.ensureIndexes = function ensureIndexes(options, callback) {
    2. if (typeof options === 'function') {
    3. callback = options;
    4. options = null;
    5. }
    6. if (options && options.__noPromise) {
    7. _ensureIndexes(this, options, callback);
    8. return;
    9. }
    10. if (callback) {
    11. callback = this.$wrapCallback(callback);
    12. }
    13. var _this = this;
    14. var Promise = PromiseProvider.get();
    15. return new Promise.ES6(function(resolve, reject) {
    16. _ensureIndexes(_this, options || {}, function(error) {
    17. if (error) {
    18. callback && callback(error);
    19. reject(error);
    20. }
    21. callback && callback();
    22. resolve();
    23. });
    24. });
    25. };

    Parameters:

    Returns:

    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.find(conditions, [projection], [options], [callback])

    Finds documents

    show code

    1. Model.find = function find(conditions, projection, options, callback) {
    2. if (typeof conditions === 'function') {
    3. callback = conditions;
    4. conditions = {};
    5. projection = null;
    6. options = null;
    7. } else if (typeof projection === 'function') {
    8. callback = projection;
    9. projection = null;
    10. options = null;
    11. } else if (typeof options === 'function') {
    12. callback = options;
    13. options = null;
    14. }
    15. var mq = new this.Query({}, {}, this, this.collection);
    16. mq.select(projection);
    17. mq.setOptions(options);
    18. if (this.schema.discriminatorMapping &&
    19. this.schema.discriminatorMapping.isRoot &&
    20. mq.selectedInclusively()) {
    21. // Need to select discriminator key because original schema doesn't have it
    22. mq.select(this.schema.options.discriminatorKey);
    23. }
    24. if (callback) {
    25. callback = this.$wrapCallback(callback);
    26. }
    27. return mq.find(conditions, callback);
    28. };

    Parameters:

    Returns:

    See:

    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(id, [projection], [options], [callback])

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

    show code

    1. Model.findById = function findById(id, projection, options, callback) {
    2. if (typeof id === 'undefined') {
    3. id = null;
    4. }
    5. if (callback) {
    6. callback = this.$wrapCallback(callback);
    7. }
    8. return this.findOne({_id: id}, projection, options, callback);
    9. };

    Parameters:

    Returns:

    See:

    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.findByIdAndRemove(id, [options], [callback])

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

    show code

    1. Model.findByIdAndRemove = function(id, options, callback) {
    2. if (arguments.length === 1 && typeof id === 'function') {
    3. var msg = 'Model.findByIdAndRemove(): First argument must not be a function.
    4. '
    5. + ' ' + this.modelName + '.findByIdAndRemove(id, callback)
    6. '
    7. + ' ' + this.modelName + '.findByIdAndRemove(id)
    8. '
    9. + ' ' + this.modelName + '.findByIdAndRemove()
    10. ';
    11. throw new TypeError(msg);
    12. }
    13. if (callback) {
    14. callback = this.$wrapCallback(callback);
    15. }
    16. return this.findOneAndRemove({_id: id}, options, callback);
    17. };

    Parameters:

    Returns:

    See:

    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:

    Examples:

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

    Model.findByIdAndUpdate(id, [update], [options], [options.lean], [callback])

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

    show code

    1. Model.findByIdAndUpdate = function(id, update, options, callback) {
    2. if (callback) {
    3. callback = this.$wrapCallback(callback);
    4. }
    5. if (arguments.length === 1) {
    6. if (typeof id === 'function') {
    7. var msg = 'Model.findByIdAndUpdate(): First argument must not be a function.
    8. '
    9. + ' ' + this.modelName + '.findByIdAndUpdate(id, callback)
    10. '
    11. + ' ' + this.modelName + '.findByIdAndUpdate(id)
    12. '
    13. + ' ' + this.modelName + '.findByIdAndUpdate()
    14. ';
    15. throw new TypeError(msg);
    16. }
    17. return this.findOneAndUpdate({_id: id}, undefined);
    18. }
    19. // if a model is passed in instead of an id
    20. if (id instanceof Document) {
    21. id = id._id;
    22. }
    23. return this.findOneAndUpdate.call(this, {_id: id}, update, options, callback);
    24. };

    Parameters:

    Returns:

    See:

    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
    • passRawResult: if true, passes the raw result from the MongoDB driver as the third callback parameter
    • strict: overwrites the schema’s strict mode option for this update
    • runSettersOnQuery: bool - if true, run all setters defined on the associated model’s schema for all fields defined in the query and the 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.
    • setters. Use the runSettersOnQuery 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.findOne([conditions], [projection], [options], [callback])

    Finds one document.

    show code

    1. Model.findOne = function findOne(conditions, projection, options, callback) {
    2. if (typeof options === 'function') {
    3. callback = options;
    4. options = null;
    5. } else if (typeof projection === 'function') {
    6. callback = projection;
    7. projection = null;
    8. options = null;
    9. } else if (typeof conditions === 'function') {
    10. callback = conditions;
    11. conditions = {};
    12. projection = null;
    13. options = null;
    14. }
    15. // get the mongodb collection object
    16. var mq = new this.Query({}, {}, this, this.collection);
    17. mq.select(projection);
    18. mq.setOptions(options);
    19. if (this.schema.discriminatorMapping &&
    20. this.schema.discriminatorMapping.isRoot &&
    21. mq.selectedInclusively()) {
    22. mq.select(this.schema.options.discriminatorKey);
    23. }
    24. if (callback) {
    25. callback = this.$wrapCallback(callback);
    26. }
    27. return mq.findOne(conditions, callback);
    28. };

    Parameters:

    Returns:

    See:

    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.findOneAndRemove(conditions, [options], [callback])

    Issue a mongodb findAndModify remove command.

    show code

    1. Model.findOneAndRemove = function(conditions, options, callback) {
    2. if (arguments.length === 1 && typeof conditions === 'function') {
    3. var msg = 'Model.findOneAndRemove(): First argument must not be a function.
    4. '
    5. + ' ' + this.modelName + '.findOneAndRemove(conditions, callback)
    6. '
    7. + ' ' + this.modelName + '.findOneAndRemove(conditions)
    8. '
    9. + ' ' + this.modelName + '.findOneAndRemove()
    10. ';
    11. throw new TypeError(msg);
    12. }
    13. if (typeof options === 'function') {
    14. callback = options;
    15. options = undefined;
    16. }
    17. if (callback) {
    18. callback = this.$wrapCallback(callback);
    19. }
    20. var fields;
    21. if (options) {
    22. fields = options.select;
    23. options.select = undefined;
    24. }
    25. var mq = new this.Query({}, {}, this, this.collection);
    26. mq.select(fields);
    27. return mq.findOneAndRemove(conditions, options, callback);
    28. };

    Parameters:

    Returns:

    See:

    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:

    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.
    • setters. Use the runSettersOnQuery 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.findOneAndUpdate([conditions], [update], [options], [options.lean], [callback])

    Issues a mongodb findAndModify update command.

    show code

    1. Model.findOneAndUpdate = function(conditions, update, options, callback) {
    2. if (typeof options === 'function') {
    3. callback = options;
    4. options = null;
    5. } else if (arguments.length === 1) {
    6. if (typeof conditions === 'function') {
    7. var msg = 'Model.findOneAndUpdate(): First argument must not be a function.
    8. '
    9. + ' ' + this.modelName + '.findOneAndUpdate(conditions, update, options, callback)
    10. '
    11. + ' ' + this.modelName + '.findOneAndUpdate(conditions, update, options)
    12. '
    13. + ' ' + this.modelName + '.findOneAndUpdate(conditions, update)
    14. '
    15. + ' ' + this.modelName + '.findOneAndUpdate(update)
    16. '
    17. + ' ' + this.modelName + '.findOneAndUpdate()
    18. ';
    19. throw new TypeError(msg);
    20. }
    21. update = conditions;
    22. conditions = undefined;
    23. }
    24. if (callback) {
    25. callback = this.$wrapCallback(callback);
    26. }
    27. var fields;
    28. if (options && options.fields) {
    29. fields = options.fields;
    30. }
    31. var retainKeyOrder = get(options, 'retainKeyOrder') ||
    32. get(this, 'schema.options.retainKeyOrder') ||
    33. false;
    34. update = utils.clone(update, {
    35. depopulate: true,
    36. _isNested: true,
    37. retainKeyOrder: retainKeyOrder
    38. });
    39. if (this.schema.options.versionKey && options && options.upsert) {
    40. if (options.overwrite) {
    41. update[this.schema.options.versionKey] = 0;
    42. } else {
    43. if (!update.$setOnInsert) {
    44. update.$setOnInsert = {};
    45. }
    46. update.$setOnInsert[this.schema.options.versionKey] = 0;
    47. }
    48. }
    49. var mq = new this.Query({}, {}, this, this.collection);
    50. mq.select(fields);
    51. return mq.findOneAndUpdate(conditions, update, options, callback);
    52. };

    Parameters:

    Returns:

    See:

    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.
    • passRawResult: if true, passes the raw result from the MongoDB driver as the third callback parameter
    • strict: overwrites the schema’s strict mode option for this update
    • runSettersOnQuery: bool - if true, run all setters defined on the associated model’s schema for all fields defined in the query and the 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.
    • setters. Use the runSettersOnQuery 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.geoNear(GeoJSON, options, [callback])

    geoNear support for Mongoose

    show code

    1. Model.geoNear = function(near, options, callback) {
    2. if (typeof options === 'function') {
    3. callback = options;
    4. options = {};
    5. }
    6. if (callback) {
    7. callback = this.$wrapCallback(callback);
    8. }
    9. var _this = this;
    10. var Promise = PromiseProvider.get();
    11. if (!near) {
    12. return new Promise.ES6(function(resolve, reject) {
    13. var error = new Error('Must pass a near option to geoNear');
    14. reject(error);
    15. callback && callback(error);
    16. });
    17. }
    18. var x;
    19. var y;
    20. var schema = this.schema;
    21. return new Promise.ES6(function(resolve, reject) {
    22. var handler = function(err, res) {
    23. if (err) {
    24. reject(err);
    25. callback && callback(err);
    26. return;
    27. }
    28. if (options.lean) {
    29. resolve(res.results, res.stats);
    30. callback && callback(null, res.results, res.stats);
    31. return;
    32. }
    33. var count = res.results.length;
    34. // if there are no results, fulfill the promise now
    35. if (count === 0) {
    36. resolve(res.results, res.stats);
    37. callback && callback(null, res.results, res.stats);
    38. return;
    39. }
    40. var errSeen = false;
    41. function init(err) {
    42. if (err && !errSeen) {
    43. errSeen = true;
    44. reject(err);
    45. callback && callback(err);
    46. return;
    47. }
    48. if (--count <= 0) {
    49. resolve(res.results, res.stats);
    50. callback && callback(null, res.results, res.stats);
    51. }
    52. }
    53. for (var i = 0; i < res.results.length; i++) {
    54. var temp = res.results[i].obj;
    55. res.results[i].obj = new _this();
    56. res.results[i].obj.init(temp, init);
    57. }
    58. };
    59. if (options.query != null) {
    60. options.query = utils.clone(options.query, { retainKeyOrder: 1 });
    61. cast(schema, options.query);
    62. }
    63. if (Array.isArray(near)) {
    64. if (near.length !== 2) {
    65. var error = new Error('If using legacy coordinates, must be an array ' +
    66. 'of size 2 for geoNear');
    67. reject(error);
    68. callback && callback(error);
    69. return;
    70. }
    71. x = near[0];
    72. y = near[1];
    73. _this.collection.geoNear(x, y, options, handler);
    74. } else {
    75. if (near.type !== 'Point' || !Array.isArray(near.coordinates)) {
    76. error = new Error('Must pass either a legacy coordinate array or ' +
    77. 'GeoJSON Point to geoNear');
    78. reject(error);
    79. callback && callback(error);
    80. return;
    81. }
    82. _this.collection.geoNear(near, options, handler);
    83. }
    84. });
    85. };

    Parameters:

    • GeoJSON <Object, Array> point or legacy coordinate pair [x,y] to search near
    • options <Object> for the query
    • [callback] <Function> optional callback for the query

    Returns:

    See:

    This function does not trigger any middleware. In particular, this
    bypasses find() middleware.

    Options:

    • lean {Boolean} return the raw object
    • All options supported by the driver are also supported

    Example:

    1. // Legacy point
    2. Model.geoNear([1,3], { maxDistance : 5, spherical : true }, function(err, results, stats) {
    3. console.log(results);
    4. });
    5. // geoJson
    6. var point = { type : "Point", coordinates : [9,9] };
    7. Model.geoNear(point, { maxDistance : 5, spherical : true }, function(err, results, stats) {
    8. console.log(results);
    9. });

    Model.geoSearch(conditions, [options], [options.lean], [callback])

    Implements $geoSearch functionality for Mongoose

    show code

    1. Model.geoSearch = function(conditions, options, callback) {
    2. if (typeof options === 'function') {
    3. callback = options;
    4. options = {};
    5. }
    6. if (callback) {
    7. callback = this.$wrapCallback(callback);
    8. }
    9. var _this = this;
    10. var Promise = PromiseProvider.get();
    11. return new Promise.ES6(function(resolve, reject) {
    12. var error;
    13. if (conditions === undefined || !utils.isObject(conditions)) {
    14. error = new Error('Must pass conditions to geoSearch');
    15. } else if (!options.near) {
    16. error = new Error('Must specify the near option in geoSearch');
    17. } else if (!Array.isArray(options.near)) {
    18. error = new Error('near option must be an array [x, y]');
    19. }
    20. if (error) {
    21. callback && callback(error);
    22. reject(error);
    23. return;
    24. }
    25. // send the conditions in the options object
    26. options.search = conditions;
    27. _this.collection.geoHaystackSearch(options.near[0], options.near[1], options, function(err, res) {
    28. // have to deal with driver problem. Should be fixed in a soon-ish release
    29. // (7/8/2013)
    30. if (err) {
    31. callback && callback(err);
    32. reject(err);
    33. return;
    34. }
    35. var count = res.results.length;
    36. if (options.lean || count === 0) {
    37. callback && callback(null, res.results, res.stats);
    38. resolve(res.results, res.stats);
    39. return;
    40. }
    41. var errSeen = false;
    42. function init(err) {
    43. if (err && !errSeen) {
    44. callback && callback(err);
    45. reject(err);
    46. return;
    47. }
    48. if (!--count && !errSeen) {
    49. callback && callback(null, res.results, res.stats);
    50. resolve(res.results, res.stats);
    51. }
    52. }
    53. for (var i = 0; i < res.results.length; i++) {
    54. var temp = res.results[i];
    55. res.results[i] = new _this();
    56. res.results[i].init(temp, {}, init);
    57. }
    58. });
    59. });
    60. };

    Parameters:

    Returns:

    See:

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

    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.

    show code

    1. Model.hydrate = function(obj) {
    2. var model = require('./queryhelpers').createModel(this, obj);
    3. model.init(obj);
    4. return model;
    5. };

    Parameters:

    Returns:

    Example:

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

    Model.init([callback])

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

    show code

    1. Model.init = function init(callback) {
    2. this.schema.emit('init', this);
    3. if (this.$init) {
    4. return this.$init;
    5. }
    6. var _this = this;
    7. var Promise = PromiseProvider.get();
    8. this.$init = new Promise.ES6(function(resolve, reject) {
    9. if ((_this.schema.options.autoIndex) ||
    10. (_this.schema.options.autoIndex == null && _this.db.config.autoIndex)) {
    11. _this.ensureIndexes({ _automatic: true, __noPromise: true }, function(error) {
    12. if (error) {
    13. callback && callback(error);
    14. return reject(error);
    15. }
    16. callback && callback(null, _this);
    17. resolve(_this);
    18. });
    19. } else {
    20. resolve(_this);
    21. }
    22. });
    23. return this.$init;
    24. };

    Parameters:

    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.insertMany(doc(s), [options], [options.ordered, [options.rawResult, [callback])

    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.

    show code

    1. Model.insertMany = function(arr, options, callback) {
    2. var _this = this;
    3. if (typeof options === 'function') {
    4. callback = options;
    5. options = null;
    6. }
    7. if (callback) {
    8. callback = this.$wrapCallback(callback);
    9. }
    10. callback = callback || utils.noop;
    11. options = options || {};
    12. var limit = get(options, 'limit', 1000);
    13. var rawResult = get(options, 'rawResult', false);
    14. var ordered = get(options, 'ordered', true);
    15. if (!Array.isArray(arr)) {
    16. arr = [arr];
    17. }
    18. var toExecute = [];
    19. var validationErrors = [];
    20. arr.forEach(function(doc) {
    21. toExecute.push(function(callback) {
    22. doc = new _this(doc);
    23. doc.validate({ __noPromise: true }, function(error) {
    24. if (error) {
    25. // Option `ordered` signals that insert should be continued after reaching
    26. // a failing insert. Therefore we delegate "null", meaning the validation
    27. // failed. It's up to the next function to filter out all failed models
    28. if (ordered === false) {
    29. validationErrors.push(error);
    30. return callback(null, null);
    31. }
    32. return callback(error);
    33. }
    34. callback(null, doc);
    35. });
    36. });
    37. });
    38. parallelLimit(toExecute, limit, function(error, docs) {
    39. if (error) {
    40. callback && callback(error);
    41. return;
    42. }
    43. // We filter all failed pre-validations by removing nulls
    44. var docAttributes = docs.filter(function(doc) {
    45. return doc != null;
    46. });
    47. // Quickly escape while there aren't any valid docAttributes
    48. if (docAttributes.length < 1) {
    49. callback(null, []);
    50. return;
    51. }
    52. var docObjects = docAttributes.map(function(doc) {
    53. if (doc.schema.options.versionKey) {
    54. doc[doc.schema.options.versionKey] = 0;
    55. }
    56. if (doc.initializeTimestamps) {
    57. return doc.initializeTimestamps().toObject(INSERT_MANY_CONVERT_OPTIONS);
    58. }
    59. return doc.toObject(INSERT_MANY_CONVERT_OPTIONS);
    60. });
    61. _this.collection.insertMany(docObjects, options, function(error, res) {
    62. if (error) {
    63. callback && callback(error);
    64. return;
    65. }
    66. for (var i = 0; i < docAttributes.length; ++i) {
    67. docAttributes[i].isNew = false;
    68. docAttributes[i].emit('isNew', false);
    69. docAttributes[i].constructor.emit('isNew', false);
    70. }
    71. if (rawResult) {
    72. if (ordered === false) {
    73. // Decorate with mongoose validation errors in case of unordered,
    74. // because then still do `insertMany()`
    75. res.mongoose = {
    76. validationErrors: validationErrors
    77. };
    78. }
    79. return callback(null, res);
    80. }
    81. callback(null, docAttributes);
    82. });
    83. });
    84. };

    Parameters:

    Returns:

    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.mapReduce(o, [callback])

    Executes a mapReduce command.

    show code

    1. Model.mapReduce = function mapReduce(o, callback) {
    2. var _this = this;
    3. if (callback) {
    4. callback = this.$wrapCallback(callback);
    5. }
    6. var resolveToObject = o.resolveToObject;
    7. var Promise = PromiseProvider.get();
    8. return new Promise.ES6(function(resolve, reject) {
    9. if (!Model.mapReduce.schema) {
    10. var opts = {noId: true, noVirtualId: true, strict: false};
    11. Model.mapReduce.schema = new Schema({}, opts);
    12. }
    13. if (!o.out) o.out = {inline: 1};
    14. if (o.verbose !== false) o.verbose = true;
    15. o.map = String(o.map);
    16. o.reduce = String(o.reduce);
    17. if (o.query) {
    18. var q = new _this.Query(o.query);
    19. q.cast(_this);
    20. o.query = q._conditions;
    21. q = undefined;
    22. }
    23. _this.collection.mapReduce(null, null, o, function(err, ret, stats) {
    24. if (err) {
    25. callback && callback(err);
    26. reject(err);
    27. return;
    28. }
    29. if (ret.findOne && ret.mapReduce) {
    30. // returned a collection, convert to Model
    31. var model = Model.compile(
    32. '_mapreduce_' + ret.collectionName
    33. , Model.mapReduce.schema
    34. , ret.collectionName
    35. , _this.db
    36. , _this.base);
    37. model._mapreduce = true;
    38. callback && callback(null, model, stats);
    39. return resolveToObject ? resolve({
    40. model: model,
    41. stats: stats
    42. }) : resolve(model, stats);
    43. }
    44. callback && callback(null, ret, stats);
    45. if (resolveToObject) {
    46. return resolve({ model: ret, stats: stats });
    47. }
    48. resolve(ret, stats);
    49. });
    50. });
    51. };

    Parameters:

    • o <Object> an object specifying map-reduce options
    • [callback] <Function> optional callback

    Returns:

    See:

    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.populate(docs, options, [callback(err,doc)])

    Populates document references.

    show code

    1. Model.populate = function(docs, paths, callback) {
    2. var _this = this;
    3. if (callback) {
    4. callback = this.$wrapCallback(callback);
    5. }
    6. // normalized paths
    7. var noPromise = paths && !!paths.__noPromise;
    8. paths = utils.populate(paths);
    9. // data that should persist across subPopulate calls
    10. var cache = {};
    11. if (noPromise) {
    12. _populate(this, docs, paths, cache, callback);
    13. } else {
    14. var Promise = PromiseProvider.get();
    15. return new Promise.ES6(function(resolve, reject) {
    16. _populate(_this, docs, paths, cache, function(error, docs) {
    17. if (error) {
    18. callback && callback(error);
    19. reject(error);
    20. } else {
    21. callback && callback(null, docs);
    22. resolve(docs);
    23. }
    24. });
    25. });
    26. }
    27. };

    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 <code>err</code> and the <code>doc(s)</code>.

    Returns:

    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

    Model.remove(conditions, [callback])

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

    show code

    1. Model.remove = function remove(conditions, callback) {
    2. if (typeof conditions === 'function') {
    3. callback = conditions;
    4. conditions = {};
    5. }
    6. // get the mongodb collection object
    7. var mq = new this.Query({}, {}, this, this.collection);
    8. if (callback) {
    9. callback = this.$wrapCallback(callback);
    10. }
    11. return mq.remove(conditions, callback);
    12. };

    Parameters:

    Returns:

    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.replaceOne(conditions, doc, [options], [callback])

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

    show code

    1. Model.replaceOne = function replaceOne(conditions, doc, options, callback) {
    2. return _update(this, 'replaceOne', conditions, doc, options, callback);
    3. };

    Parameters:

    Returns:

    This function triggers the following middleware

    • replaceOne()

    Model.translateAliases(raw)

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

    show code

    1. Model.translateAliases = function translateAliases(fields) {
    2. var aliases = this.schema.aliases;
    3. if (typeof fields === 'object') {
    4. // Fields is an object (query conditions or document fields)
    5. for (var key in fields) {
    6. if (aliases[key]) {
    7. fields[aliases[key]] = fields[key];
    8. delete fields[key];
    9. }
    10. }
    11. return fields;
    12. } else {
    13. // Don't know typeof fields
    14. return fields;
    15. }
    16. };

    Parameters:

    • raw <Object> fields/conditions that may contain aliased keys

    Returns:

    • <Object> the translated ‘pure’ fields/conditions

    Example:

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

    Note:

    Only translate arguments of object type anything else is returned raw


    Model.update(conditions, doc, [options], [callback])

    Updates one document in the database without returning it.

    show code

    1. Model.update = function update(conditions, doc, options, callback) {
    2. return _update(this, 'update', conditions, doc, options, callback);
    3. };

    Parameters:

    Returns:

    See:

    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(conditions, doc, [options], [callback])

    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.

    show code

    1. Model.updateMany = function updateMany(conditions, doc, options, callback) {
    2. return _update(this, 'updateMany', conditions, doc, options, callback);
    3. };

    Parameters:

    Returns:

    Note updateMany will not fire update middleware. Use pre('updateMany')
    and post('updateMany') instead.

    This function triggers the following middleware

    • updateMany()

    Model.updateOne(conditions, doc, [options], [callback])

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

    show code

    1. Model.updateOne = function updateOne(conditions, doc, options, callback) {
    2. return _update(this, 'updateOne', conditions, doc, options, callback);
    3. };

    Parameters:

    Returns:

    This function triggers the following middleware

    • updateOne()

    Model.where(path, [val])

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

    show code

    1. Model.where = function where(path, val) {
    2. void val; // eslint
    3. // get the mongodb collection object
    4. var mq = new this.Query({}, {}, this, this.collection).find({});
    5. return mq.where.apply(mq, arguments);
    6. };

    Parameters:

    Returns:

    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#$where

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

    show code

    1. Model.prototype.$where;

    Model#base

    Base Mongoose instance the model uses.

    show code

    1. Model.base;

    Model#baseModelName

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

    show code

    1. Model.prototype.baseModelName;
    2. Model.prototype.$__handleSave = function(options, callback) {
    3. var _this = this;
    4. var i;
    5. var keys;
    6. var len;
    7. if (!options.safe && this.schema.options.safe) {
    8. options.safe = this.schema.options.safe;
    9. }
    10. if (typeof options.safe === 'boolean') {
    11. options.safe = null;
    12. }
    13. var safe = options.safe ? utils.clone(options.safe, { retainKeyOrder: true }) : options.safe;
    14. if (this.isNew) {
    15. // send entire doc
    16. var toObjectOptions = {};
    17. toObjectOptions.retainKeyOrder = this.schema.options.retainKeyOrder;
    18. toObjectOptions.depopulate = 1;
    19. toObjectOptions._skipDepopulateTopLevel = true;
    20. toObjectOptions.transform = false;
    21. toObjectOptions.flattenDecimals = false;
    22. var obj = this.toObject(toObjectOptions);
    23. if ((obj || {})._id === void 0) {
    24. // documents must have an _id else mongoose won't know
    25. // what to update later if more changes are made. the user
    26. // wouldn't know what _id was generated by mongodb either
    27. // nor would the ObjectId generated my mongodb necessarily
    28. // match the schema definition.
    29. setTimeout(function() {
    30. callback(new Error('document must have an _id before saving'));
    31. }, 0);
    32. return;
    33. }
    34. this.$__version(true, obj);
    35. this.collection.insert(obj, safe, function(err, ret) {
    36. if (err) {
    37. _this.isNew = true;
    38. _this.emit('isNew', true);
    39. _this.constructor.emit('isNew', true);
    40. callback(err);
    41. return;
    42. }
    43. callback(null, ret);
    44. });
    45. this.$__reset();
    46. this.isNew = false;
    47. this.emit('isNew', false);
    48. this.constructor.emit('isNew', false);
    49. // Make it possible to retry the insert
    50. this.$__.inserting = true;
    51. } else {
    52. // Make sure we don't treat it as a new object on error,
    53. // since it already exists
    54. this.$__.inserting = false;
    55. var delta = this.$__delta();
    56. if (delta) {
    57. if (delta instanceof Error) {
    58. callback(delta);
    59. return;
    60. }
    61. var where = this.$__where(delta[0]);
    62. if (where instanceof Error) {
    63. callback(where);
    64. return;
    65. }
    66. if (this.$where) {
    67. keys = Object.keys(this.$where);
    68. len = keys.length;
    69. for (i = 0; i < len; ++i) {
    70. where[keys[i]] = this.$where[keys[i]];
    71. }
    72. }
    73. this.collection.update(where, delta[1], safe, function(err, ret) {
    74. if (err) {
    75. callback(err);
    76. return;
    77. }
    78. ret.$where = where;
    79. callback(null, ret);
    80. });
    81. } else {
    82. this.$__reset();
    83. callback();
    84. return;
    85. }
    86. this.emit('isNew', false);
    87. this.constructor.emit('isNew', false);
    88. }
    89. };

    Model#collection

    Collection the model uses.

    show code

    1. Model.prototype.collection;

    Model#db

    Connection the model uses.

    show code

    1. Model.prototype.db;

    Model#discriminators

    Registered discriminators for this model.

    show code

    1. Model.discriminators;

    Model#modelName

    The name of the model

    show code

    1. Model.prototype.modelName;

    Model#schema

    Schema the model uses.

    show code

    1. Model.schema;

  • query.js

    Query#_applyPaths()

    Applies schematype selected options to this query.

    show code

    1. Query.prototype._applyPaths = function applyPaths() {
    2. this._fields = this._fields || {};
    3. helpers.applyPaths(this._fields, this.model.schema);
    4. selectPopulatedFields(this);
    5. };

    Query#_castFields(fields)

    Casts selected field arguments for field selection with mongo 2.2

    Parameters:

    See:

    1. query.select({ ids: { $elemMatch: { $in: [hexString] }})

    show code

    1. Query.prototype._castFields = function _castFields(fields) {
    2. var selected,
    3. elemMatchKeys,
    4. keys,
    5. key,
    6. out,
    7. i;
    8. if (fields) {
    9. keys = Object.keys(fields);
    10. elemMatchKeys = [];
    11. i = keys.length;
    12. // collect $elemMatch args
    13. while (i--) {
    14. key = keys[i];
    15. if (fields[key].$elemMatch) {
    16. selected || (selected = {});
    17. selected[key] = fields[key];
    18. elemMatchKeys.push(key);
    19. }
    20. }
    21. }
    22. if (selected) {
    23. // they passed $elemMatch, cast em
    24. try {
    25. out = this.cast(this.model, selected);
    26. } catch (err) {
    27. return err;
    28. }
    29. // apply the casted field args
    30. i = elemMatchKeys.length;
    31. while (i--) {
    32. key = elemMatchKeys[i];
    33. fields[key] = out[key];
    34. }
    35. }
    36. return fields;
    37. };

    Query#_count([callback])

    Thunk around count()

    Parameters:

    See:

    show code

    1. Query.prototype._count = function(callback) {
    2. try {
    3. this.cast(this.model);
    4. } catch (err) {
    5. this.error(err);
    6. }
    7. if (this.error()) {
    8. return callback(this.error());
    9. }
    10. var conds = this._conditions;
    11. var options = this._optionsForExec();
    12. this._collection.count(conds, options, utils.tick(callback));
    13. };

    Query#_find([callback])

    Thunk around find()

    Parameters:

    Returns:

    show code

    1. Query.prototype._find = function(callback) {
    2. this._castConditions();
    3. if (this.error() != null) {
    4. callback(this.error());
    5. return this;
    6. }
    7. this._applyPaths();
    8. this._fields = this._castFields(this._fields);
    9. var fields = this._fieldsForExec();
    10. var mongooseOptions = this._mongooseOptions;
    11. var _this = this;
    12. var userProvidedFields = _this._userProvidedFields || {};
    13. var cb = function(err, docs) {
    14. if (err) {
    15. return callback(err);
    16. }
    17. if (docs.length === 0) {
    18. return callback(null, docs);
    19. }
    20. if (!mongooseOptions.populate) {
    21. return !!mongooseOptions.lean === true
    22. ? callback(null, docs)
    23. : completeMany(_this.model, docs, fields, userProvidedFields, null, callback);
    24. }
    25. var pop = helpers.preparePopulationOptionsMQ(_this, mongooseOptions);
    26. pop.__noPromise = true;
    27. _this.model.populate(docs, pop, function(err, docs) {
    28. if (err) return callback(err);
    29. return !!mongooseOptions.lean === true
    30. ? callback(null, docs)
    31. : completeMany(_this.model, docs, fields, userProvidedFields, pop, callback);
    32. });
    33. };
    34. var options = this._optionsForExec();
    35. options.fields = this._fieldsForExec();
    36. var filter = this._conditions;
    37. return this._collection.find(filter, options, cb);
    38. };

    Query#_findOne([callback])

    Thunk around findOne()

    Parameters:

    See:

    show code

    1. Query.prototype._findOne = function(callback) {
    2. this._castConditions();
    3. if (this.error()) {
    4. return callback(this.error());
    5. }
    6. this._applyPaths();
    7. this._fields = this._castFields(this._fields);
    8. var options = this._mongooseOptions;
    9. var projection = this._fieldsForExec();
    10. var userProvidedFields = this._userProvidedFields || {};
    11. var _this = this;
    12. // don't pass in the conditions because we already merged them in
    13. Query.base.findOne.call(_this, {}, function(err, doc) {
    14. if (err) {
    15. return callback(err);
    16. }
    17. if (!doc) {
    18. return callback(null, null);
    19. }
    20. if (!options.populate) {
    21. return !!options.lean === true
    22. ? callback(null, doc)
    23. : completeOne(_this.model, doc, null, {}, projection, userProvidedFields, null, callback);
    24. }
    25. var pop = helpers.preparePopulationOptionsMQ(_this, options);
    26. pop.__noPromise = true;
    27. _this.model.populate(doc, pop, function(err, doc) {
    28. if (err) {
    29. return callback(err);
    30. }
    31. return !!options.lean === true
    32. ? callback(null, doc)
    33. : completeOne(_this.model, doc, null, {}, projection, userProvidedFields, pop, callback);
    34. });
    35. });
    36. };

    Query#_optionsForExec(model)

    Returns default options for this query.

    Parameters:

    show code

    1. Query.prototype._optionsForExec = function(model) {
    2. var options = Query.base._optionsForExec.call(this);
    3. delete options.populate;
    4. delete options.retainKeyOrder;
    5. model = model || this.model;
    6. if (!model) {
    7. return options;
    8. }
    9. if (!('safe' in options) && model.schema.options.safe) {
    10. options.safe = model.schema.options.safe;
    11. }
    12. if (!('readPreference' in options) && model.schema.options.read) {
    13. options.readPreference = model.schema.options.read;
    14. }
    15. if (options.upsert !== void 0) {
    16. options.upsert = !!options.upsert;
    17. }
    18. return options;
    19. };

    Query#$where(js)

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

    Parameters:

    Returns:

    See:

    Example

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

    NOTE:

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


    Query#all([path], val)

    Specifies an $all query condition.

    Parameters:

    See:

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


    Query#and(array)

    Specifies arguments for a $and condition.

    Parameters:

    • array <Array> array of conditions

    Returns:

    See:

    Example

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

    Query#batchSize(val)

    Specifies the batchSize option.

    Parameters:

    See:

    Example

    1. query.batchSize(100)

    Note

    Cannot be used with distinct()


    Query#box(val, Upper)

    Specifies a $box condition

    Parameters:

    Returns:

    See:

    Example

    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#canMerge(conds)

    Determines if conds can be merged using mquery().merge()

    Parameters:

    Returns:


    Query#cast(model, [obj])

    Casts this query to the schema of model

    Parameters:

    Returns:

    Note

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

    show code

    1. Query.prototype.cast = function(model, obj) {
    2. obj || (obj = this._conditions);
    3. try {
    4. return cast(model.schema, obj, {
    5. upsert: this.options && this.options.upsert,
    6. strict: (this.options && 'strict' in this.options) ?
    7. this.options.strict :
    8. (model.schema.options && model.schema.options.strict),
    9. strictQuery: (this.options && this.options.strictQuery) ||
    10. (model.schema.options && model.schema.options.strictQuery)
    11. }, this);
    12. } catch (err) {
    13. // CastError, assign model
    14. if (typeof err.setModel === 'function') {
    15. err.setModel(model);
    16. }
    17. throw err;
    18. }
    19. };

    Query#catch([reject])

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

    Parameters:

    Returns:

    show code

    1. Query.prototype.catch = function(reject) {
    2. return this.exec().then(null, reject);
    3. };

    Query#center()

    DEPRECATED Alias for circle

    Deprecated. Use circle instead.


    Query#centerSphere([path], val)

    DEPRECATED Specifies a $centerSphere condition

    Parameters:

    Returns:

    See:

    Deprecated. Use circle instead.

    Example

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

    show code

    1. Query.prototype.centerSphere = function() {
    2. if (arguments[0] && arguments[0].constructor.name === 'Object') {
    3. arguments[0].spherical = true;
    4. }
    5. if (arguments[1] && arguments[1].constructor.name === 'Object') {
    6. arguments[1].spherical = true;
    7. }
    8. Query.base.circle.apply(this, arguments);
    9. };

    Query#circle([path], area)

    Specifies a $center or $centerSphere condition.

    Parameters:

    Returns:

    See:

    Example

    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#collation(value)

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

    Parameters:

    Returns:

    See:

    show code

    1. Query.prototype.collation = function(value) {
    2. if (this.options == null) {
    3. this.options = {};
    4. }
    5. this.options.collation = value;
    6. return this;
    7. };

    Query#comment(val)

    Specifies the comment option.

    Parameters:

    See:

    Example

    1. query.comment('login query')

    Note

    Cannot be used with distinct()


    Query#count([criteria], [callback])

    Specifying this query as a count query.

    Parameters:

    • [criteria] <Object> mongodb selector
    • [callback] <Function> optional params are (error, count)

    Returns:

    See:

    Passing a callback executes the query.

    This function triggers the following middleware

    • count()

    Example:

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

    show code

    1. Query.prototype.count = function(conditions, callback) {
    2. if (typeof conditions === 'function') {
    3. callback = conditions;
    4. conditions = undefined;
    5. }
    6. if (mquery.canMerge(conditions)) {
    7. this.merge(conditions);
    8. }
    9. this.op = 'count';
    10. if (!callback) {
    11. return this;
    12. }
    13. this._count(callback);
    14. return this;
    15. };

    Query#cursor([options])

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

    Parameters:

    Returns:

    See:

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

    Example

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

    Valid options

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

    show code

    1. Query.prototype.cursor = function cursor(opts) {
    2. this._applyPaths();
    3. this._fields = this._castFields(this._fields);
    4. this.setOptions({ fields: this._fieldsForExec() });
    5. if (opts) {
    6. this.setOptions(opts);
    7. }
    8. try {
    9. this.cast(this.model);
    10. } catch (err) {
    11. return (new QueryCursor(this, this.options))._markError(err);
    12. }
    13. return new QueryCursor(this, this.options);
    14. };
    15. // the rest of these are basically to support older Mongoose syntax with mquery

    Query#deleteMany([filter], [callback])

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

    Parameters:

    • [filter] <Object, Query> mongodb selector
    • [callback] <Function> optional params are (error, writeOpResult)

    Returns:

    See:

    This function does not trigger any middleware

    Example

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

    show code

    1. Query.prototype.deleteMany = function(filter, callback) {
    2. if (typeof filter === 'function') {
    3. callback = filter;
    4. filter = null;
    5. }
    6. filter = utils.toObject(filter, { retainKeyOrder: true });
    7. try {
    8. this.cast(this.model, filter);
    9. this.merge(filter);
    10. } catch (err) {
    11. this.error(err);
    12. }
    13. prepareDiscriminatorCriteria(this);
    14. if (!callback) {
    15. return Query.base.deleteMany.call(this);
    16. }
    17. return this._deleteMany.call(this, callback);
    18. };

    Query#deleteOne([filter], [callback])

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

    Parameters:

    • [filter] <Object, Query> mongodb selector
    • [callback] <Function> optional params are (error, writeOpResult)

    Returns:

    See:

    This function does not trigger any middleware.

    Example

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

    show code

    1. Query.prototype.deleteOne = function(filter, callback) {
    2. if (typeof filter === 'function') {
    3. callback = filter;
    4. filter = null;
    5. }
    6. filter = utils.toObject(filter, { retainKeyOrder: true });
    7. try {
    8. this.cast(this.model, filter);
    9. this.merge(filter);
    10. } catch (err) {
    11. this.error(err);
    12. }
    13. prepareDiscriminatorCriteria(this);
    14. if (!callback) {
    15. return Query.base.deleteOne.call(this);
    16. }
    17. return this._deleteOne.call(this, callback);
    18. };

    Query#distinct([field], [criteria], [callback])

    Declares or executes a distict() operation.

    Parameters:

    Returns:

    See:

    Passing a callback executes the query.

    This function does not trigger any middleware.

    Example

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

    show code

    1. Query.prototype.distinct = function(field, conditions, callback) {
    2. if (!callback) {
    3. if (typeof conditions === 'function') {
    4. callback = conditions;
    5. conditions = undefined;
    6. } else if (typeof field === 'function') {
    7. callback = field;
    8. field = undefined;
    9. conditions = undefined;
    10. }
    11. }
    12. conditions = utils.toObject(conditions);
    13. if (mquery.canMerge(conditions)) {
    14. this.merge(conditions);
    15. }
    16. try {
    17. this.cast(this.model);
    18. } catch (err) {
    19. if (!callback) {
    20. throw err;
    21. }
    22. callback(err);
    23. return this;
    24. }
    25. return Query.base.distinct.call(this, {}, field, callback);
    26. };

    Query#elemMatch(path, criteria)

    Specifies an $elemMatch condition

    Parameters:

    Returns:

    See:

    Example

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

    Query#equals(val)

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

    Parameters:

    Returns:

    Example

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

    Query#error(err)

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

    Parameters:

    • err <Error, null> if set, exec() will fail fast before sending the query to MongoDB

    Example:

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

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

    Example:

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

    show code

    1. Query.prototype.error = function error(err) {
    2. if (arguments.length === 0) {
    3. return this._error;
    4. }
    5. this._error = err;
    6. return this;
    7. };

    Query#exec([operation], [callback])

    Executes the query

    Parameters:

    Returns:

    Examples:

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

    show code

    1. Query.prototype.exec = function exec(op, callback) {
    2. var Promise = PromiseProvider.get();
    3. var _this = this;
    4. if (typeof op === 'function') {
    5. callback = op;
    6. op = null;
    7. } else if (typeof op === 'string') {
    8. this.op = op;
    9. }
    10. var _results;
    11. var promise = new Promise.ES6(function(resolve, reject) {
    12. if (!_this.op) {
    13. resolve();
    14. return;
    15. }
    16. _this[_this.op].call(_this, function(error, res) {
    17. if (error) {
    18. reject(error);
    19. return;
    20. }
    21. _results = arguments;
    22. resolve(res);
    23. });
    24. });
    25. if (callback) {
    26. promise.then(
    27. function() {
    28. callback.apply(null, _results);
    29. return null;
    30. },
    31. function(error) {
    32. callback(error, null);
    33. }).
    34. catch(function(error) {
    35. // If we made it here, we must have an error in the callback re:
    36. // gh-4500, so we need to emit.
    37. setImmediate(function() {
    38. _this.model.emit('error', error);
    39. });
    40. });
    41. }
    42. return promise;
    43. };

    Query#exists([path], val)

    Specifies an $exists condition

    Parameters:

    Returns:

    See:

    Example

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

    Query#find([filter], [callback])

    Finds documents.

    Parameters:

    Returns:

    When no callback is passed, the query is not executed. When the query is executed, the result will be an array of documents.

    Example

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

    show code

    1. Query.prototype.find = function(conditions, callback) {
    2. if (typeof conditions === 'function') {
    3. callback = conditions;
    4. conditions = {};
    5. }
    6. conditions = utils.toObject(conditions);
    7. if (mquery.canMerge(conditions)) {
    8. this.merge(conditions);
    9. prepareDiscriminatorCriteria(this);
    10. } else if (conditions != null) {
    11. this.error(new ObjectParameterError(conditions, 'filter', 'find'));
    12. }
    13. // if we don't have a callback, then just return the query object
    14. if (!callback) {
    15. return Query.base.find.call(this);
    16. }
    17. this._find(callback);
    18. return this;
    19. };

    Query#findOne([filter], [projection], [options], [callback])

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

    Parameters:

    Returns:

    See:

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

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

    This function triggers the following middleware

    • findOne()

    Example

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

    show code

    1. Query.prototype.findOne = function(conditions, projection, options, callback) {
    2. if (typeof conditions === 'function') {
    3. callback = conditions;
    4. conditions = null;
    5. projection = null;
    6. options = null;
    7. } else if (typeof projection === 'function') {
    8. callback = projection;
    9. options = null;
    10. projection = null;
    11. } else if (typeof options === 'function') {
    12. callback = options;
    13. options = null;
    14. }
    15. // make sure we don't send in the whole Document to merge()
    16. conditions = utils.toObject(conditions);
    17. this.op = 'findOne';
    18. if (options) {
    19. this.setOptions(options);
    20. }
    21. if (projection) {
    22. this.select(projection);
    23. }
    24. if (mquery.canMerge(conditions)) {
    25. this.merge(conditions);
    26. prepareDiscriminatorCriteria(this);
    27. try {
    28. this.cast(this.model);
    29. this.error(null);
    30. } catch (err) {
    31. this.error(err);
    32. }
    33. } else if (conditions != null) {
    34. this.error(new ObjectParameterError(conditions, 'filter', 'findOne'));
    35. }
    36. if (!callback) {
    37. // already merged in the conditions, don't need to send them in.
    38. return Query.base.findOne.call(this);
    39. }
    40. this._findOne(callback);
    41. return this;
    42. };

    Query#findOneAndRemove([conditions], [options], [options.passRawResult], [options.strict], [callback])

    Issues a mongodb findAndModify remove command.

    Parameters:

    Returns:

    See:

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

    This function triggers the following middleware

    • findOneAndRemove()

    Available options

    Callback Signature

    1. function(error, doc, result) {
    2. // error: any errors that occurred
    3. // doc: the document before updates are applied if `new: false`, or after updates if `new = true`
    4. // result: [raw result from the MongoDB driver](http://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#findAndModify)
    5. }

    Examples

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

    Query#findOneAndUpdate([query], [doc], [options], [options.passRawResult], [options.strict], [options.multipleCastError], [callback])

    Issues a mongodb findAndModify update command.

    Parameters:

    Returns:

    See:

    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.

    This function triggers the following middleware

    • findOneAndUpdate()

    Available options

    • new: bool - if true, return the modified document rather than the original. defaults to false (changed in 4.0)
    • upsert: bool - creates the object if it doesn’t exist. defaults to false.
    • fields: {Object|String} - Field selection. Equivalent to .select(fields).findOneAndUpdate()
    • sort: if multiple docs are found by the conditions, sets the sort order to choose which doc to update
    • maxTimeMS: puts a time limit on the query - requires mongodb >= 2.6.0
    • runValidators: if true, runs update validators on this command. Update validators validate the update operation against the model’s schema.
    • setDefaultsOnInsert: 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.
    • passRawResult: if true, passes the raw result from the MongoDB driver as the third callback parameter
    • 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.
    • runSettersOnQuery: bool - if true, run all setters defined on the associated model’s schema for all fields defined in the query and the update.

    Callback Signature

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

    Examples

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

    Query#geometry(object)

    Specifies a $geometry condition

    Parameters:

    • object <Object> Must contain a type property which is a String and a coordinates property which is an Array. See the examples.

    Returns:

    See:

    Example

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

    NOTE:

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

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


    Query#getQuery()

    Returns the current query conditions as a JSON object.

    Returns:

    • <Object> current query conditions

    Example:

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

    show code

    1. Query.prototype.getQuery = function() {
    2. return this._conditions;
    3. };

    Query#getUpdate()

    Returns the current update operations as a JSON object.

    Returns:

    • <Object> current update operations

    Example:

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

    show code

    1. Query.prototype.getUpdate = function() {
    2. return this._update;
    3. };

    Query#gt([path], val)

    Specifies a $gt query condition.

    Parameters:

    See:

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

    Example

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

    Query#gte([path], val)

    Specifies a $gte query condition.

    Parameters:

    See:

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


    Query#hint(val)

    Sets query hints.

    Parameters:

    Returns:

    See:

    Example

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

    Note

    Cannot be used with distinct()


    Query#in([path], val)

    Specifies an $in query condition.

    Parameters:

    See:

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


    Query#intersects([arg])

    Declares an intersects query for geometry().

    Parameters:

    Returns:

    See:

    Example

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

    NOTE:

    MUST be used after where().

    NOTE:

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


    Query#lean(bool)

    Sets the lean option.

    Parameters:

    Returns:

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

    Example:

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

    This is a great option in high-performance read-only scenarios, especially when combined with stream.

    show code

    1. Query.prototype.lean = function(v) {
    2. this._mongooseOptions.lean = arguments.length ? v : true;
    3. return this;
    4. };

    Query#limit(val)

    Specifies the maximum number of documents the query will return.

    Parameters:

    Example

    1. query.limit(20)

    Note

    Cannot be used with distinct()


    Query#lt([path], val)

    Specifies a $lt query condition.

    Parameters:

    See:

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


    Query#lte([path], val)

    Specifies a $lte query condition.

    Parameters:

    See:

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


    Query#maxDistance([path], val)

    Specifies a $maxDistance query condition.

    Parameters:

    See:

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


    Query#maxscan()

    DEPRECATED Alias of maxScan

    See:


    Query#maxScan(val)

    Specifies the maxScan option.

    Parameters:

    See:

    Example

    1. query.maxScan(100)

    Note

    Cannot be used with distinct()


    Query#merge(source)

    Merges another Query or conditions object into this one.

    Parameters:

    Returns:

    When a Query is passed, conditions, field selection and options are merged.

    show code

    1. Query.prototype.merge = function(source) {
    2. if (!source) {
    3. return this;
    4. }
    5. var opts = { retainKeyOrder: this.options.retainKeyOrder, overwrite: true };
    6. if (source instanceof Query) {
    7. // if source has a feature, apply it to ourselves
    8. if (source._conditions) {
    9. utils.merge(this._conditions, source._conditions, opts);
    10. }
    11. if (source._fields) {
    12. this._fields || (this._fields = {});
    13. utils.merge(this._fields, source._fields, opts);
    14. }
    15. if (source.options) {
    16. this.options || (this.options = {});
    17. utils.merge(this.options, source.options, opts);
    18. }
    19. if (source._update) {
    20. this._update || (this._update = {});
    21. utils.mergeClone(this._update, source._update);
    22. }
    23. if (source._distinct) {
    24. this._distinct = source._distinct;
    25. }
    26. return this;
    27. }
    28. // plain object
    29. utils.merge(this._conditions, source, opts);
    30. return this;
    31. };

    Query#merge(source)

    Merges another Query or conditions object into this one.

    Parameters:

    Returns:

    When a Query is passed, conditions, field selection and options are merged.

    New in 3.7.0


    Query#mod([path], val)

    Specifies a $mod condition, filters documents for documents whose
    path property is a number that is equal to remainder modulo divisor.

    Parameters:

    • [path] <String>
    • val <Array> must be of length 2, first element is divisor, 2nd element is remainder.

    Returns:

    See:

    Example

    1. // All find products whose inventory is odd
    2. Product.find().mod('inventory', [2, 1]);
    3. Product.find().where('inventory').mod([2, 1]);
    4. // This syntax is a little strange, but supported.
    5. Product.find().where('inventory').mod(2, 1);

    Query#mongooseOptions(options)

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

    Parameters:

    • options <Object> if specified, overwrites the current options

    show code

    1. Query.prototype.mongooseOptions = function(v) {
    2. if (arguments.length > 0) {
    3. this._mongooseOptions = v;
    4. }
    5. return this._mongooseOptions;
    6. };

    Query#ne([path], val)

    Specifies a $ne query condition.

    Parameters:

    See:

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


    Query#near([path], val)

    Specifies a $near or $nearSphere condition

    Parameters:

    Returns:

    See:

    These operators return documents sorted by distance.

    Example

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

    Query#nearSphere()

    DEPRECATED Specifies a $nearSphere condition

    See:

    Example

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

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

    Example

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

    show code

    1. Query.prototype.nearSphere = function() {
    2. this._mongooseOptions.nearSphere = true;
    3. this.near.apply(this, arguments);
    4. return this;
    5. };

    Query#nin([path], val)

    Specifies an $nin query condition.

    Parameters:

    See:

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


    Query#nor(array)

    Specifies arguments for a $nor condition.

    Parameters:

    • array <Array> array of conditions

    Returns:

    See:

    Example

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

    Query#or(array)

    Specifies arguments for an $or condition.

    Parameters:

    • array <Array> array of conditions

    Returns:

    See:

    Example

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

    Query#polygon([path], [coordinatePairs...])

    Specifies a $polygon condition

    Parameters:

    Returns:

    See:

    Example

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

    Query#populate(path, [select], [model], [match], [options])

    Specifies paths which should be populated with other documents.

    Parameters:

    • path <Object, String> either the path to populate or an object specifying all parameters
    • [select] <Object, String> Field selection for the population query
    • [model] <Model> The model you wish to use for population. If not specified, populate will look up the model by the name in the Schema’s ref field.
    • [match] <Object> Conditions for the population query
    • [options] <Object> Options for the population query (sort, etc)

    Returns:

    See:

    Example:

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

    Paths are populated after the query executes and a response is received. A separate query is then executed for each path specified for population. After a response for each query has also been returned, the results are passed to the callback.

    show code

    1. Query.prototype.populate = function() {
    2. if (arguments.length === 0) {
    3. return this;
    4. }
    5. var i;
    6. var res = utils.populate.apply(null, arguments);
    7. // Propagate readPreference from parent query, unless one already specified
    8. if (this.options && this.options.readPreference != null) {
    9. for (i = 0; i < res.length; ++i) {
    10. if (!res[i].options || res[i].options.readPreference == null) {
    11. res[i].options = res[i].options || {};
    12. res[i].options.readPreference = this.options.readPreference;
    13. }
    14. }
    15. }
    16. var opts = this._mongooseOptions;
    17. if (!utils.isObject(opts.populate)) {
    18. opts.populate = {};
    19. }
    20. var pop = opts.populate;
    21. for (i = 0; i < res.length; ++i) {
    22. var path = res[i].path;
    23. if (pop[path] && pop[path].populate && res[i].populate) {
    24. res[i].populate = pop[path].populate.concat(res[i].populate);
    25. }
    26. pop[res[i].path] = res[i];
    27. }
    28. return this;
    29. };

    Query([options], [model], [conditions], [collection])

    Query constructor used for building queries.

    Parameters:

    Example:

    1. var query = new Query();
    2. query.setOptions({ lean : true });
    3. query.collection(model.collection);
    4. query.where('age').gte(21).exec(callback);

    show code

    1. function Query(conditions, options, model, collection) {
    2. // this stuff is for dealing with custom queries created by #toConstructor
    3. if (!this._mongooseOptions) {
    4. this._mongooseOptions = {};
    5. }
    6. // this is the case where we have a CustomQuery, we need to check if we got
    7. // options passed in, and if we did, merge them in
    8. if (options) {
    9. var keys = Object.keys(options);
    10. for (var i = 0; i < keys.length; ++i) {
    11. var k = keys[i];
    12. this._mongooseOptions[k] = options[k];
    13. }
    14. }
    15. if (collection) {
    16. this.mongooseCollection = collection;
    17. }
    18. if (model) {
    19. this.model = model;
    20. this.schema = model.schema;
    21. }
    22. // this is needed because map reduce returns a model that can be queried, but
    23. // all of the queries on said model should be lean
    24. if (this.model && this.model._mapreduce) {
    25. this.lean();
    26. }
    27. // inherit mquery
    28. mquery.call(this, this.mongooseCollection, options);
    29. if (conditions) {
    30. this.find(conditions);
    31. }
    32. this.options = this.options || {};
    33. if (this.schema != null && this.schema.options.collation != null) {
    34. this.options.collation = this.schema.options.collation;
    35. }
    36. if (this.schema) {
    37. var kareemOptions = {
    38. useErrorHandlers: true,
    39. numCallbackParams: 1,
    40. nullResultByDefault: true
    41. };
    42. this._count = this.model.hooks.createWrapper('count',
    43. Query.prototype._count, this, kareemOptions);
    44. this._execUpdate = this.model.hooks.createWrapper('update',
    45. Query.prototype._execUpdate, this, kareemOptions);
    46. this._find = this.model.hooks.createWrapper('find',
    47. Query.prototype._find, this, kareemOptions);
    48. this._findOne = this.model.hooks.createWrapper('findOne',
    49. Query.prototype._findOne, this, kareemOptions);
    50. this._findOneAndRemove = this.model.hooks.createWrapper('findOneAndRemove',
    51. Query.prototype._findOneAndRemove, this, kareemOptions);
    52. this._findOneAndUpdate = this.model.hooks.createWrapper('findOneAndUpdate',
    53. Query.prototype._findOneAndUpdate, this, kareemOptions);
    54. this._replaceOne = this.model.hooks.createWrapper('replaceOne',
    55. Query.prototype._replaceOne, this, kareemOptions);
    56. this._updateMany = this.model.hooks.createWrapper('updateMany',
    57. Query.prototype._updateMany, this, kareemOptions);
    58. this._updateOne = this.model.hooks.createWrapper('updateOne',
    59. Query.prototype._updateOne, this, kareemOptions);
    60. }
    61. }

    Query#read(pref, [tags])

    Determines the MongoDB nodes from which to read.

    Parameters:

    • pref <String> one of the listed preference options or aliases
    • [tags] <Array> optional tags for this query

    Returns:

    See:

    Preferences:

    1. primary - (default) Read from primary only. Operations will produce an error if primary is unavailable. Cannot be combined with tags.
    2. secondary Read from secondary if available, otherwise error.
    3. primaryPreferred Read from primary if available, otherwise a secondary.
    4. secondaryPreferred Read from a secondary if available, otherwise read from the primary.
    5. nearest All operations read from among the nearest candidates, but unlike other modes, this option will include both the primary and all secondaries in the random selection.

    Aliases

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

    Example:

    1. new Query().read('primary')
    2. new Query().read('p') // same as primary
    3. new Query().read('primaryPreferred')
    4. new Query().read('pp') // same as primaryPreferred
    5. new Query().read('secondary')
    6. new Query().read('s') // same as secondary
    7. new Query().read('secondaryPreferred')
    8. new Query().read('sp') // same as secondaryPreferred
    9. new Query().read('nearest')
    10. new Query().read('n') // same as nearest
    11. // read from secondaries with matching tags
    12. new Query().read('s', [{ dc:'sf', s: 1 },{ dc:'ma', s: 2 }])

    Read more about how to use read preferrences here and here.


    Query#regex([path], val)

    Specifies a $regex query condition.

    Parameters:

    See:

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


    Query#remove([filter], [callback])

    Declare and/or execute this query as a remove() operation.

    Parameters:

    • [filter] <Object, Query> mongodb selector
    • [callback] <Function> optional params are (error, writeOpResult)

    Returns:

    See:

    This function does not trigger any middleware

    Example

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

    Note

    The operation is only executed when a callback is passed. To force execution without a callback, you must first call remove() and then execute it by using the exec() method.

    1. // not executed
    2. var query = Model.find().remove({ name: 'Anne Murray' })
    3. // executed
    4. query.remove({ name: 'Anne Murray' }, callback)
    5. query.remove({ name: 'Anne Murray' }).remove(callback)
    6. // executed without a callback
    7. query.exec()
    8. // summary
    9. query.remove(conds, fn); // executes
    10. query.remove(conds)
    11. query.remove(fn) // executes
    12. query.remove()

    show code

    1. Query.prototype.remove = function(filter, callback) {
    2. if (typeof filter === 'function') {
    3. callback = filter;
    4. filter = null;
    5. }
    6. filter = utils.toObject(filter, { retainKeyOrder: true });
    7. try {
    8. this.cast(this.model, filter);
    9. this.merge(filter);
    10. } catch (err) {
    11. this.error(err);
    12. }
    13. prepareDiscriminatorCriteria(this);
    14. if (!callback) {
    15. return Query.base.remove.call(this);
    16. }
    17. return this._remove(callback);
    18. };

    Query#replaceOne([criteria], [doc], [options], [callback])

    Declare and/or execute this query as a replaceOne() operation. Same as
    update(), except MongoDB will replace the existing document and will
    not accept any atomic operators ($set, etc.)

    Parameters:

    • [criteria] <Object>
    • [doc] <Object> the update command
    • [options] <Object>
    • [callback] <Function> optional params are (error, writeOpResult)

    Returns:

    See:

    Note replaceOne will not fire update middleware. Use pre('replaceOne')
    and post('replaceOne') instead.

    This function triggers the following middleware

    • replaceOne()

    show code

    1. Query.prototype.replaceOne = function(conditions, doc, options, callback) {
    2. if (typeof options === 'function') {
    3. // .update(conditions, doc, callback)
    4. callback = options;
    5. options = null;
    6. } else if (typeof doc === 'function') {
    7. // .update(doc, callback);
    8. callback = doc;
    9. doc = conditions;
    10. conditions = {};
    11. options = null;
    12. } else if (typeof conditions === 'function') {
    13. // .update(callback)
    14. callback = conditions;
    15. conditions = undefined;
    16. doc = undefined;
    17. options = undefined;
    18. } else if (typeof conditions === 'object' && !doc && !options && !callback) {
    19. // .update(doc)
    20. doc = conditions;
    21. conditions = undefined;
    22. options = undefined;
    23. callback = undefined;
    24. }
    25. this.setOptions({ overwrite: true });
    26. return _update(this, 'replaceOne', conditions, doc, options, callback);
    27. };

    Query#select(arg)

    Specifies which document fields to include or exclude (also known as the query “projection”)

    Parameters:

    Returns:

    See:

    When using string syntax, prefixing a path with - will flag that path as excluded. When a path does not have the - prefix, it is included. Lastly, if a path is prefixed with +, it forces inclusion of the path, which is useful for paths excluded at the schema level.

    A projection must be either inclusive or exclusive. In other words, you must
    either list the fields to include (which excludes all others), or list the fields
    to exclude (which implies all other fields are included). The _id field is the only exception because MongoDB includes it by default.

    Example

    1. // include a and b, exclude other fields
    2. query.select('a b');
    3. // exclude c and d, include other fields
    4. query.select('-c -d');
    5. // or you may use object notation, useful when
    6. // you have keys already prefixed with a "-"
    7. query.select({ a: 1, b: 1 });
    8. query.select({ c: 0, d: 0 });
    9. // force inclusion of field excluded at schema level
    10. query.select('+path')

    Query#selected()

    Determines if field selection has been made.

    Returns:


    Query#selectedExclusively()

    Determines if exclusive field selection has been made.

    Returns:

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

    Query#selectedInclusively()

    Determines if inclusive field selection has been made.

    Returns:

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

    Query#setOptions(options)

    Sets query options. Some options only make sense for certain operations.

    Parameters:

    Options:

    The following options are only for find():
    - tailable
    - sort%7D%7D)
    - limit
    - skip
    - maxscan
    - batchSize
    - comment
    - snapshot
    - readPreference
    - hint

    The following options are only for update(), updateOne(), updateMany(), replaceOne(), findOneAndUpdate(), and findByIdAndUpdate():
    - upsert
    - writeConcern

    The following options are only for find(), findOne(), findById(), findOneAndUpdate(), and findByIdAndUpdate():
    - lean

    The following options are only for all operations except update(), updateOne(), updateMany(), remove(), deleteOne(), and deleteMany():
    - maxTimeMS

    The following options are for all operations

    show code

    1. Query.prototype.setOptions = function(options, overwrite) {
    2. // overwrite is only for internal use
    3. if (overwrite) {
    4. // ensure that _mongooseOptions & options are two different objects
    5. this._mongooseOptions = (options && utils.clone(options)) || {};
    6. this.options = options || {};
    7. if ('populate' in options) {
    8. this.populate(this._mongooseOptions);
    9. }
    10. return this;
    11. }
    12. if (options == null) {
    13. return this;
    14. }
    15. if (Array.isArray(options.populate)) {
    16. var populate = options.populate;
    17. delete options.populate;
    18. var _numPopulate = populate.length;
    19. for (var i = 0; i < _numPopulate; ++i) {
    20. this.populate(populate[i]);
    21. }
    22. }
    23. return Query.base.setOptions.call(this, options);
    24. };

    Query#size([path], val)

    Specifies a $size query condition.

    Parameters:

    See:

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

    Example

    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#skip(val)

    Specifies the number of documents to skip.

    Parameters:

    See:

    Example

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

    Note

    Cannot be used with distinct()


    Query#slaveOk(v)

    DEPRECATED Sets the slaveOk option.

    Parameters:

    Returns:

    See:

    Deprecated in MongoDB 2.2 in favor of read preferences.

    Example:

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

    Query#slice([path], val)

    Specifies a $slice projection for an array.

    Parameters:

    • [path] <String>
    • val <Number> number/range of elements to slice

    Returns:

    See:

    Example

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

    Query#slice([path], [val])

    Specifies a path for use with chaining.

    Parameters:

    Returns:

    Example

    1. // instead of writing:
    2. User.find({age: {$gte: 21, $lte: 65}}, callback);
    3. // we can instead write:
    4. User.where('age').gte(21).lte(65);
    5. // passing query conditions is permitted
    6. User.find().where({ name: 'vonderful' })
    7. // chaining
    8. User
    9. .where('age').gte(21).lte(65)
    10. .where('name', /^vonderful/i)
    11. .where('friends').slice(10)
    12. .exec(callback)

    Query#snapshot()

    Specifies this query as a snapshot query.

    Returns:

    See:

    Example

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

    Note

    Cannot be used with distinct()


    Query#sort(arg)

    Sets the sort order

    Parameters:

    Returns:

    See:

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

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

    Example

    1. // sort by "field" ascending and "test" descending
    2. query.sort({ field: 'asc', test: -1 });
    3. // equivalent
    4. query.sort('field -test');

    Note

    Cannot be used with distinct()

    show code

    1. Query.prototype.sort = function(arg) {
    2. if (arguments.length > 1) {
    3. throw new Error('sort() only takes 1 Argument');
    4. }
    5. return Query.base.sort.call(this, arg);
    6. };

    Query#stream([options])

    Returns a Node.js 0.8 style read stream interface.

    Parameters:

    Returns:

    See:

    Example

    1. // follows the nodejs 0.8 stream api
    2. Thing.find({ name: /^hello/ }).stream().pipe(res)
    3. // manual streaming
    4. var stream = Thing.find({ name: /^hello/ }).stream();
    5. stream.on('data', function (doc) {
    6. // do something with the mongoose document
    7. }).on('error', function (err) {
    8. // handle the error
    9. }).on('close', function () {
    10. // the stream is closed
    11. });

    Valid options

    • transform: optional function which accepts a mongoose document. The return value of the function will be emitted on data.

    Example

    1. // JSON.stringify all documents before emitting
    2. var stream = Thing.find().stream({ transform: JSON.stringify });
    3. stream.pipe(writeStream);

    show code

    1. Query.prototype.stream = function stream(opts) {
    2. this._applyPaths();
    3. this._fields = this._castFields(this._fields);
    4. this._castConditions();
    5. return new QueryStream(this, opts);
    6. };
    7. Query.prototype.stream = util.deprecate(Query.prototype.stream, 'Mongoose: ' +
    8. 'Query.prototype.stream() is deprecated in mongoose >= 4.5.0, ' +
    9. 'use Query.prototype.cursor() instead');

    Query#tailable(bool, [opts], [opts.numberOfRetries], [opts.tailableRetryInterval])

    Sets the tailable option (for use with capped collections).

    Parameters:

    • bool <Boolean> defaults to true
    • [opts] <Object> options to set
    • [opts.numberOfRetries] <Number> if cursor is exhausted, retry this many times before giving up
    • [opts.tailableRetryInterval] <Number> if cursor is exhausted, wait this many milliseconds before retrying

    See:

    Example

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

    Note

    Cannot be used with distinct()

    show code

    1. Query.prototype.tailable = function(val, opts) {
    2. // we need to support the tailable({ awaitdata : true }) as well as the
    3. // tailable(true, {awaitdata :true}) syntax that mquery does not support
    4. if (val && val.constructor.name === 'Object') {
    5. opts = val;
    6. val = true;
    7. }
    8. if (val === undefined) {
    9. val = true;
    10. }
    11. if (opts && typeof opts === 'object') {
    12. for (var key in opts) {
    13. if (key === 'awaitdata') {
    14. // For backwards compatibility
    15. this.options[key] = !!opts[key];
    16. } else {
    17. this.options[key] = opts[key];
    18. }
    19. }
    20. }
    21. return Query.base.tailable.call(this, val);
    22. };

    Query#then([resolve], [reject])

    Executes the query returning a Promise which will be
    resolved with either the doc(s) or rejected with the error.

    Parameters:

    Returns:

    show code

    1. Query.prototype.then = function(resolve, reject) {
    2. return this.exec().then(resolve, reject);
    3. };

    Query#toConstructor()

    Converts this query to a customized, reusable query constructor with all arguments and options retained.

    Returns:

    • <Query> subclass-of-Query

    Example

    1. // Create a query for adventure movies and read from the primary
    2. // node in the replica-set unless it is down, in which case we'll
    3. // read from a secondary node.
    4. var query = Movie.find({ tags: 'adventure' }).read('primaryPreferred');
    5. // create a custom Query constructor based off these settings
    6. var Adventure = query.toConstructor();
    7. // Adventure is now a subclass of mongoose.Query and works the same way but with the
    8. // default query parameters and options set.
    9. Adventure().exec(callback)
    10. // further narrow down our query results while still using the previous settings
    11. Adventure().where({ name: /^Life/ }).exec(callback);
    12. // since Adventure is a stand-alone constructor we can also add our own
    13. // helper methods and getters without impacting global queries
    14. Adventure.prototype.startsWith = function (prefix) {
    15. this.where({ name: new RegExp('^' + prefix) })
    16. return this;
    17. }
    18. Object.defineProperty(Adventure.prototype, 'highlyRated', {
    19. get: function () {
    20. this.where({ rating: { $gt: 4.5 }});
    21. return this;
    22. }
    23. })
    24. Adventure().highlyRated.startsWith('Life').exec(callback)

    New in 3.7.3

    show code

    1. Query.prototype.toConstructor = function toConstructor() {
    2. var model = this.model;
    3. var coll = this.mongooseCollection;
    4. var CustomQuery = function(criteria, options) {
    5. if (!(this instanceof CustomQuery)) {
    6. return new CustomQuery(criteria, options);
    7. }
    8. this._mongooseOptions = utils.clone(p._mongooseOptions);
    9. Query.call(this, criteria, options || null, model, coll);
    10. };
    11. util.inherits(CustomQuery, Query);
    12. // set inherited defaults
    13. var p = CustomQuery.prototype;
    14. p.options = {};
    15. p.setOptions(this.options);
    16. p.op = this.op;
    17. p._conditions = utils.clone(this._conditions, { retainKeyOrder: true });
    18. p._fields = utils.clone(this._fields);
    19. p._update = utils.clone(this._update, {
    20. flattenDecimals: false,
    21. retainKeyOrder: true
    22. });
    23. p._path = this._path;
    24. p._distinct = this._distinct;
    25. p._collection = this._collection;
    26. p._mongooseOptions = this._mongooseOptions;
    27. return CustomQuery;
    28. };

    Query#update([criteria], [doc], [options], [options.multipleCastError], [callback])

    Declare and/or execute this query as an update() operation.

    Parameters:

    • [criteria] <Object>
    • [doc] <Object> the update command
    • [options] <Object>
    • [options.multipleCastError] <Boolean> by default, mongoose only returns the first error that occurred in casting the query. Turn on this option to aggregate all the cast errors.
    • [callback] <Function> optional, params are (error, writeOpResult)

    Returns:

    See:

    All paths passed that are not $atomic operations will become $set ops.

    This function triggers the following middleware

    • update()

    Example

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

    Valid options:

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

    Note

    Passing an empty object {} as the doc will result in a no-op unless the overwrite option is passed. Without the overwrite option set, the update operation will be ignored and the callback executed without sending the command to MongoDB so as to prevent accidently overwritting documents in the collection.

    Note

    The operation is only executed when a callback is passed. To force execution without a callback, we must first call update() and then execute it by using the exec() method.

    1. var q = Model.where({ _id: id });
    2. q.update({ $set: { name: 'bob' }}).update(); // not executed
    3. q.update({ $set: { name: 'bob' }}).exec(); // executed
    4. // keys that are not $atomic ops become $set.
    5. // this executes the same command as the previous example.
    6. q.update({ name: 'bob' }).exec();
    7. // overwriting with empty docs
    8. var q = Model.where({ _id: id }).setOptions({ overwrite: true })
    9. q.update({ }, callback); // executes
    10. // multi update with overwrite to empty doc
    11. var q = Model.where({ _id: id });
    12. q.setOptions({ multi: true, overwrite: true })
    13. q.update({ });
    14. q.update(callback); // executed
    15. // multi updates
    16. Model.where()
    17. .update({ name: /^match/ }, { $set: { arr: [] }}, { multi: true }, callback)
    18. // more multi updates
    19. Model.where()
    20. .setOptions({ multi: true })
    21. .update({ $set: { arr: [] }}, callback)
    22. // single update by default
    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()

    show code

    1. Query.prototype.update = function(conditions, doc, options, callback) {
    2. if (typeof options === 'function') {
    3. // .update(conditions, doc, callback)
    4. callback = options;
    5. options = null;
    6. } else if (typeof doc === 'function') {
    7. // .update(doc, callback);
    8. callback = doc;
    9. doc = conditions;
    10. conditions = {};
    11. options = null;
    12. } else if (typeof conditions === 'function') {
    13. // .update(callback)
    14. callback = conditions;
    15. conditions = undefined;
    16. doc = undefined;
    17. options = undefined;
    18. } else if (typeof conditions === 'object' && !doc && !options && !callback) {
    19. // .update(doc)
    20. doc = conditions;
    21. conditions = undefined;
    22. options = undefined;
    23. callback = undefined;
    24. }
    25. return _update(this, 'update', conditions, doc, options, callback);
    26. };

    Query#updateMany([criteria], [doc], [options], [callback])

    Declare and/or execute this query as an updateMany() operation. 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.

    Parameters:

    • [criteria] <Object>
    • [doc] <Object> the update command
    • [options] <Object>
    • [callback] <Function> optional params are (error, writeOpResult)

    Returns:

    See:

    Note updateMany will not fire update middleware. Use pre('updateMany')
    and post('updateMany') instead.

    This function triggers the following middleware

    • updateMany()

    show code

    1. Query.prototype.updateMany = function(conditions, doc, options, callback) {
    2. if (typeof options === 'function') {
    3. // .update(conditions, doc, callback)
    4. callback = options;
    5. options = null;
    6. } else if (typeof doc === 'function') {
    7. // .update(doc, callback);
    8. callback = doc;
    9. doc = conditions;
    10. conditions = {};
    11. options = null;
    12. } else if (typeof conditions === 'function') {
    13. // .update(callback)
    14. callback = conditions;
    15. conditions = undefined;
    16. doc = undefined;
    17. options = undefined;
    18. } else if (typeof conditions === 'object' && !doc && !options && !callback) {
    19. // .update(doc)
    20. doc = conditions;
    21. conditions = undefined;
    22. options = undefined;
    23. callback = undefined;
    24. }
    25. return _update(this, 'updateMany', conditions, doc, options, callback);
    26. };

    Query#updateOne([criteria], [doc], [options], [callback])

    Declare and/or execute this query as an updateOne() operation. Same as
    update(), except MongoDB will update only the first document that
    matches criteria regardless of the value of the multi option.

    Parameters:

    Returns:

    See:

    Note updateOne will not fire update middleware. Use pre('updateOne')
    and post('updateOne') instead.

    This function triggers the following middleware

    • updateOne()

    show code

    1. Query.prototype.updateOne = function(conditions, doc, options, callback) {
    2. if (typeof options === 'function') {
    3. // .update(conditions, doc, callback)
    4. callback = options;
    5. options = null;
    6. } else if (typeof doc === 'function') {
    7. // .update(doc, callback);
    8. callback = doc;
    9. doc = conditions;
    10. conditions = {};
    11. options = null;
    12. } else if (typeof conditions === 'function') {
    13. // .update(callback)
    14. callback = conditions;
    15. conditions = undefined;
    16. doc = undefined;
    17. options = undefined;
    18. } else if (typeof conditions === 'object' && !doc && !options && !callback) {
    19. // .update(doc)
    20. doc = conditions;
    21. conditions = undefined;
    22. options = undefined;
    23. callback = undefined;
    24. }
    25. return _update(this, 'updateOne', conditions, doc, options, callback);
    26. };

    Query#within()

    Defines a $within or $geoWithin argument for geo-spatial queries.

    Returns:

    See:

    Example

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

    MUST be used after where().

    NOTE:

    As of Mongoose 3.7, $geoWithin is always used for queries. To change this behavior, see Query.use$geoWithin.

    NOTE:

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


    Query._ensurePath(method)

    Makes sure _path is set.

    Parameters:


    Query._fieldsForExec()

    Returns fields selection for this query.

    Returns:


    Query._updateForExec()

    Return an update document with corrected $set operations.


    Query#use$geoWithin

    Flag to opt out of using $geoWithin.

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

    MongoDB 2.4 deprecated the use of $within, replacing it with $geoWithin. Mongoose uses $geoWithin by default (which is 100% backward compatible with $within). If you are running an older version of MongoDB, set this flag to false so your within() queries continue to work.

    show code

    1. Query.use$geoWithin = mquery.use$geoWithin;

    See:


  • promise_provider.js

    ()

    Helper for multiplexing promise implementations

    show code

    1. var Promise = {
    2. _promise: MPromise
    3. };

    Promise.get()

    Get the current promise constructor

    show code

    1. Promise.get = function() {
    2. return Promise._promise;
    3. };

    Promise.reset()

    Resets to using mpromise

    show code

    1. Promise.reset = function() {
    2. Promise._promise = MPromise;
    3. };
    4. module.exports = Promise;

    Promise.set()

    Set the current promise constructor

    show code

    1. Promise.set = function(lib) {
    2. if (lib === MPromise) {
    3. return Promise.reset();
    4. }
    5. Promise._promise = require('./ES6Promise');
    6. Promise._promise.use(lib);
    7. require('mquery').Promise = Promise._promise.ES6;
    8. };

  • schema.js

    Schema#add(obj, prefix)

    Adds key path / schema type pairs to this schema.

    Parameters:

    Example:

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

    show code

    1. Schema.prototype.add = function add(obj, prefix) {
    2. prefix = prefix || '';
    3. var keys = Object.keys(obj);
    4. for (var i = 0; i < keys.length; ++i) {
    5. var key = keys[i];
    6. if (obj[key] == null) {
    7. throw new TypeError('Invalid value for schema path `' + prefix + key + '`');
    8. }
    9. if (Array.isArray(obj[key]) && obj[key].length === 1 && obj[key][0] == null) {
    10. throw new TypeError('Invalid value for schema Array path `' + prefix + key + '`');
    11. }
    12. if (utils.isObject(obj[key]) &&
    13. (!obj[key].constructor || utils.getFunctionName(obj[key].constructor) === 'Object') &&
    14. (!obj[key][this.options.typeKey] || (this.options.typeKey === 'type' && obj[key].type.type))) {
    15. if (Object.keys(obj[key]).length) {
    16. // nested object { last: { name: String }}
    17. this.nested[prefix + key] = true;
    18. this.add(obj[key], prefix + key + '.');
    19. } else {
    20. if (prefix) {
    21. this.nested[prefix.substr(0, prefix.length - 1)] = true;
    22. }
    23. this.path(prefix + key, obj[key]); // mixed type
    24. }
    25. } else {
    26. if (prefix) {
    27. this.nested[prefix.substr(0, prefix.length - 1)] = true;
    28. }
    29. this.path(prefix + key, obj[key]);
    30. }
    31. }
    32. };

    Schema#clone()

    Returns a deep copy of the schema

    Returns:

    show code

    1. Schema.prototype.clone = function() {
    2. var s = new Schema(this.paths, this.options);
    3. // Clone the call queue
    4. var cloneOpts = { retainKeyOrder: true };
    5. s.callQueue = this.callQueue.map(function(f) { return f; });
    6. s.methods = utils.clone(this.methods, cloneOpts);
    7. s.statics = utils.clone(this.statics, cloneOpts);
    8. s.query = utils.clone(this.query, cloneOpts);
    9. s.plugins = Array.prototype.slice.call(this.plugins);
    10. s._indexes = utils.clone(this._indexes, cloneOpts);
    11. s.s.hooks = this.s.hooks.clone();
    12. return s;
    13. };

    Schema#defaultOptions(options)

    Returns default options for this schema, merged with options.

    Parameters:

    Returns:

    show code

    1. Schema.prototype.defaultOptions = function(options) {
    2. if (options && options.safe === false) {
    3. options.safe = {w: 0};
    4. }
    5. if (options && options.safe && options.safe.w === 0) {
    6. // if you turn off safe writes, then versioning goes off as well
    7. options.versionKey = false;
    8. }
    9. this._userProvidedOptions = utils.clone(options, {
    10. retainKeyOrder: true
    11. });
    12. options = utils.options({
    13. strict: true,
    14. bufferCommands: true,
    15. capped: false, // { size, max, autoIndexId }
    16. versionKey: '__v',
    17. discriminatorKey: '__t',
    18. minimize: true,
    19. autoIndex: null,
    20. shardKey: null,
    21. read: null,
    22. validateBeforeSave: true,
    23. // the following are only applied at construction time
    24. noId: false, // deprecated, use { _id: false }
    25. _id: true,
    26. noVirtualId: false, // deprecated, use { id: false }
    27. id: true,
    28. typeKey: 'type',
    29. retainKeyOrder: false
    30. }, options);
    31. if (options.read) {
    32. options.read = readPref(options.read);
    33. }
    34. return options;
    35. };

    Schema#eachPath(fn)

    Iterates the schemas paths similar to Array#forEach.

    Parameters:

    Returns:

    The callback is passed the pathname and schemaType as arguments on each iteration.

    show code

    1. Schema.prototype.eachPath = function(fn) {
    2. var keys = Object.keys(this.paths),
    3. len = keys.length;
    4. for (var i = 0; i < len; ++i) {
    5. fn(keys[i], this.paths[keys[i]]);
    6. }
    7. return this;
    8. };

    Schema#get(key)

    Gets a schema option.

    Parameters:

    show code

    1. Schema.prototype.get = function(key) {
    2. return this.options[key];
    3. };

    Schema#hasMixedParent(path)

    Returns true iff this path is a child of a mixed schema.

    Parameters:

    Returns:

    show code

    1. Schema.prototype.hasMixedParent = function(path) {
    2. var subpaths = path.split(/\./g);
    3. path = '';
    4. for (var i = 0; i < subpaths.length; ++i) {
    5. path = i > 0 ? path + '.' + subpaths[i] : subpaths[i];
    6. if (path in this.paths &&
    7. this.paths[path] instanceof MongooseTypes.Mixed) {
    8. return true;
    9. }
    10. }
    11. return false;
    12. };

    Schema#index(fields, [options], [options.expires=null])

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

    Parameters:

    Example

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

    show code

    1. Schema.prototype.index = function(fields, options) {
    2. options || (options = {});
    3. if (options.expires) {
    4. utils.expires(options);
    5. }
    6. this._indexes.push([fields, options]);
    7. return this;
    8. };

    Schema#indexedPaths()

    Returns indexes from fields and schema-level indexes (cached).

    Returns:

    show code

    1. Schema.prototype.indexedPaths = function indexedPaths() {
    2. if (this._indexedpaths) {
    3. return this._indexedpaths;
    4. }
    5. this._indexedpaths = this.indexes();
    6. return this._indexedpaths;
    7. };

    Schema#indexes()

    Returns a list of indexes that this schema declares, via schema.index()
    or by index: true in a path’s options.

    show code

    1. Schema.prototype.indexes = function() {
    2. 'use strict';
    3. var indexes = [];
    4. var schemaStack = [];
    5. var collectIndexes = function(schema, prefix) {
    6. // Ignore infinitely nested schemas, if we've already seen this schema
    7. // along this path there must be a cycle
    8. if (schemaStack.indexOf(schema) !== -1) {
    9. return;
    10. }
    11. schemaStack.push(schema);
    12. prefix = prefix || '';
    13. var key, path, index, field, isObject, options, type;
    14. var keys = Object.keys(schema.paths);
    15. for (var i = 0; i < keys.length; ++i) {
    16. key = keys[i];
    17. path = schema.paths[key];
    18. if ((path instanceof MongooseTypes.DocumentArray) || path.$isSingleNested) {
    19. if (path.options.excludeIndexes !== true) {
    20. collectIndexes(path.schema, prefix + key + '.');
    21. }
    22. } else {
    23. index = path._index || (path.caster && path.caster._index);
    24. if (index !== false && index !== null && index !== undefined) {
    25. field = {};
    26. isObject = utils.isObject(index);
    27. options = isObject ? index : {};
    28. type = typeof index === 'string' ? index :
    29. isObject ? index.type :
    30. false;
    31. if (type && ~Schema.indexTypes.indexOf(type)) {
    32. field[prefix + key] = type;
    33. } else if (options.text) {
    34. field[prefix + key] = 'text';
    35. delete options.text;
    36. } else {
    37. field[prefix + key] = 1;
    38. }
    39. delete options.type;
    40. if (!('background' in options)) {
    41. options.background = true;
    42. }
    43. indexes.push([field, options]);
    44. }
    45. }
    46. }
    47. schemaStack.pop();
    48. if (prefix) {
    49. fixSubIndexPaths(schema, prefix);
    50. } else {
    51. schema._indexes.forEach(function(index) {
    52. if (!('background' in index[1])) {
    53. index[1].background = true;
    54. }
    55. });
    56. indexes = indexes.concat(schema._indexes);
    57. }
    58. };
    59. collectIndexes(this);
    60. return indexes;

    Schema#loadClass(model)

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

    Parameters:

    show code

    1. Schema.prototype.loadClass = function(model, virtualsOnly) {
    2. if (model === Object.prototype ||
    3. model === Function.prototype ||
    4. model.prototype.hasOwnProperty('$isMongooseModelPrototype')) {
    5. return this;
    6. }
    7. this.loadClass(Object.getPrototypeOf(model));
    8. // Add static methods
    9. if (!virtualsOnly) {
    10. Object.getOwnPropertyNames(model).forEach(function(name) {
    11. if (name.match(/^(length|name|prototype)$/)) {
    12. return;
    13. }
    14. var method = Object.getOwnPropertyDescriptor(model, name);
    15. if (typeof method.value === 'function') {
    16. this.static(name, method.value);
    17. }
    18. }, this);
    19. }
    20. // Add methods and virtuals
    21. Object.getOwnPropertyNames(model.prototype).forEach(function(name) {
    22. if (name.match(/^(constructor)$/)) {
    23. return;
    24. }
    25. var method = Object.getOwnPropertyDescriptor(model.prototype, name);
    26. if (!virtualsOnly) {
    27. if (typeof method.value === 'function') {
    28. this.method(name, method.value);
    29. }
    30. }
    31. if (typeof method.get === 'function') {
    32. this.virtual(name).get(method.get);
    33. }
    34. if (typeof method.set === 'function') {
    35. this.virtual(name).set(method.set);
    36. }
    37. }, this);
    38. return this;
    39. };

    Schema#method(method, [fn])

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

    Parameters:

    Example

    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

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

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

    show code

    1. Schema.prototype.method = function(name, fn) {
    2. if (typeof name !== 'string') {
    3. for (var i in name) {
    4. this.methods[i] = name[i];
    5. }
    6. } else {
    7. this.methods[name] = fn;
    8. }
    9. return this;
    10. };

    Schema#path(path, constructor)

    Gets/sets schema paths.

    Parameters:

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

    Example

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

    show code

    1. Schema.prototype.path = function(path, obj) {
    2. if (obj === undefined) {
    3. if (this.paths[path]) {
    4. return this.paths[path];
    5. }
    6. if (this.subpaths[path]) {
    7. return this.subpaths[path];
    8. }
    9. if (this.singleNestedPaths[path]) {
    10. return this.singleNestedPaths[path];
    11. }
    12. // subpaths?
    13. return /\.\d+\.?.*$/.test(path)
    14. ? getPositionalPath(this, path)
    15. : undefined;
    16. }
    17. // some path names conflict with document methods
    18. if (reserved[path]) {
    19. throw new Error('`' + path + '` may not be used as a schema pathname');
    20. }
    21. if (warnings[path]) {
    22. console.log('WARN: ' + warnings[path]);
    23. }
    24. // update the tree
    25. var subpaths = path.split(/\./),
    26. last = subpaths.pop(),
    27. branch = this.tree;
    28. subpaths.forEach(function(sub, i) {
    29. if (!branch[sub]) {
    30. branch[sub] = {};
    31. }
    32. if (typeof branch[sub] !== 'object') {
    33. var msg = 'Cannot set nested path `' + path + '`. '
    34. + 'Parent path `'
    35. + subpaths.slice(0, i).concat([sub]).join('.')
    36. + '` already set to type ' + branch[sub].name
    37. + '.';
    38. throw new Error(msg);
    39. }
    40. branch = branch[sub];
    41. });
    42. branch[last] = utils.clone(obj);
    43. this.paths[path] = Schema.interpretAsType(path, obj, this.options);
    44. if (this.paths[path].$isSingleNested) {
    45. for (var key in this.paths[path].schema.paths) {
    46. this.singleNestedPaths[path + '.' + key] =
    47. this.paths[path].schema.paths[key];
    48. }
    49. for (key in this.paths[path].schema.singleNestedPaths) {
    50. this.singleNestedPaths[path + '.' + key] =
    51. this.paths[path].schema.singleNestedPaths[key];
    52. }
    53. this.childSchemas.push({
    54. schema: this.paths[path].schema,
    55. model: this.paths[path].caster
    56. });
    57. } else if (this.paths[path].$isMongooseDocumentArray) {
    58. this.childSchemas.push({
    59. schema: this.paths[path].schema,
    60. model: this.paths[path].casterConstructor
    61. });
    62. }
    63. return this;
    64. };

    Schema#pathType(path)

    Returns the pathType of path for this schema.

    Parameters:

    Returns:

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

    show code

    1. Schema.prototype.pathType = function(path) {
    2. if (path in this.paths) {
    3. return 'real';
    4. }
    5. if (path in this.virtuals) {
    6. return 'virtual';
    7. }
    8. if (path in this.nested) {
    9. return 'nested';
    10. }
    11. if (path in this.subpaths) {
    12. return 'real';
    13. }
    14. if (path in this.singleNestedPaths) {
    15. return 'real';
    16. }
    17. if (/\.\d+\.|\.\d+$/.test(path)) {
    18. return getPositionalPathType(this, path);
    19. }
    20. return 'adhocOrUndefined';
    21. };

    Schema#plugin(plugin, [opts])

    Registers a plugin for this schema.

    Parameters:

    See:

    show code

    1. Schema.prototype.plugin = function(fn, opts) {
    2. if (typeof fn !== 'function') {
    3. throw new Error('First param to `schema.plugin()` must be a function, ' +
    4. 'got "' + (typeof fn) + '"');
    5. }
    6. if (opts &&
    7. opts.deduplicate) {
    8. for (var i = 0; i < this.plugins.length; ++i) {
    9. if (this.plugins[i].fn === fn) {
    10. return this;
    11. }
    12. }
    13. }
    14. this.plugins.push({ fn: fn, opts: opts });
    15. fn(this, opts);
    16. return this;
    17. };

    Schema#post(method, fn)

    Defines a post hook for the document

    Parameters:

    See:

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

    show code

    1. Schema.prototype.post = function(method, fn) {
    2. if (IS_KAREEM_HOOK[method]) {
    3. this.s.hooks.post.apply(this.s.hooks, arguments);
    4. return this;
    5. }
    6. // assuming that all callbacks with arity < 2 are synchronous post hooks
    7. if (fn.length < 2) {
    8. return this.queue('on', [arguments[0], function(doc) {
    9. return fn.call(doc, doc);
    10. }]);
    11. }
    12. if (fn.length === 3) {
    13. this.s.hooks.post(method + ':error', fn);
    14. return this;
    15. }
    16. return this.queue('post', [arguments[0], function(next) {
    17. // wrap original function so that the callback goes last,
    18. // for compatibility with old code that is using synchronous post hooks
    19. var _this = this;
    20. var args = Array.prototype.slice.call(arguments, 1);
    21. fn.call(this, this, function(err) {
    22. return next.apply(_this, [err].concat(args));
    23. });
    24. }]);
    25. };

    Schema#pre(method, callback)

    Defines a pre hook for the document.

    Parameters:

    See:

    Example

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

    show code

    1. Schema.prototype.pre = function() {
    2. var name = arguments[0];
    3. if (IS_KAREEM_HOOK[name]) {
    4. this.s.hooks.pre.apply(this.s.hooks, arguments);
    5. return this;
    6. }
    7. return this.queue('pre', arguments);
    8. };

    Schema#queue(name, args)

    Adds a method call to the queue.

    Parameters:

    • name <String> name of the document method to call later
    • args <Array> arguments to pass to the method

    show code

    1. Schema.prototype.queue = function(name, args) {
    2. this.callQueue.push([name, args]);
    3. return this;
    4. };

    Schema#remove(path)

    Removes the given path (or [paths]).

    Parameters:

    show code

    1. Schema.prototype.remove = function(path) {
    2. if (typeof path === 'string') {
    3. path = [path];
    4. }
    5. if (Array.isArray(path)) {
    6. path.forEach(function(name) {
    7. if (this.path(name)) {
    8. delete this.paths[name];
    9. var pieces = name.split('.');
    10. var last = pieces.pop();
    11. var branch = this.tree;
    12. for (var i = 0; i < pieces.length; ++i) {
    13. branch = branch[pieces[i]];
    14. }
    15. delete branch[last];
    16. }
    17. }, this);
    18. }
    19. };

    Schema#requiredPaths(invalidate)

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

    Parameters:

    • invalidate <Boolean> refresh the cache

    Returns:

    show code

    1. Schema.prototype.requiredPaths = function requiredPaths(invalidate) {
    2. if (this._requiredpaths && !invalidate) {
    3. return this._requiredpaths;
    4. }
    5. var paths = Object.keys(this.paths),
    6. i = paths.length,
    7. ret = [];
    8. while (i--) {
    9. var path = paths[i];
    10. if (this.paths[path].isRequired) {
    11. ret.push(path);
    12. }
    13. }
    14. this._requiredpaths = ret;
    15. return this._requiredpaths;
    16. };

    Schema(definition, [options])

    Schema constructor.

    Parameters:

    Inherits:

    Events:

    • init: Emitted after the schema is compiled into a Model.

    Example:

    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. // setting schema options
    5. new Schema({ name: String }, { _id: false, autoIndex: false })

    Options:

    Note:

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

    show code

    1. function Schema(obj, options) {
    2. if (!(this instanceof Schema)) {
    3. return new Schema(obj, options);
    4. }
    5. this.obj = obj;
    6. this.paths = {};
    7. this.aliases = {};
    8. this.subpaths = {};
    9. this.virtuals = {};
    10. this.singleNestedPaths = {};
    11. this.nested = {};
    12. this.inherits = {};
    13. this.callQueue = [];
    14. this._indexes = [];
    15. this.methods = {};
    16. this.statics = {};
    17. this.tree = {};
    18. this.query = {};
    19. this.childSchemas = [];
    20. this.plugins = [];
    21. this.s = {
    22. hooks: new Kareem(),
    23. kareemHooks: IS_KAREEM_HOOK
    24. };
    25. this.options = this.defaultOptions(options);
    26. // build paths
    27. if (obj) {
    28. this.add(obj);
    29. }
    30. // check if _id's value is a subdocument (gh-2276)
    31. var _idSubDoc = obj && obj._id && utils.isObject(obj._id);
    32. // ensure the documents get an auto _id unless disabled
    33. var auto_id = !this.paths['_id'] &&
    34. (!this.options.noId && this.options._id) && !_idSubDoc;
    35. if (auto_id) {
    36. var _obj = {_id: {auto: true}};
    37. _obj._id[this.options.typeKey] = Schema.ObjectId;
    38. this.add(_obj);
    39. }
    40. for (var i = 0; i < this._defaultMiddleware.length; ++i) {
    41. var m = this._defaultMiddleware[i];
    42. this[m.kind](m.hook, !!m.isAsync, m.fn);
    43. }
    44. if (this.options.timestamps) {
    45. this.setupTimestamp(this.options.timestamps);
    46. }
    47. // Assign virtual properties based on alias option
    48. aliasFields(this);
    49. }

    Schema#set(key, [value])

    Sets/gets a schema option.

    Parameters:

    • key <String> option name
    • [value] <Object> if not passed, the current option value is returned

    See:

    Example

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

    show code

    1. Schema.prototype.set = function(key, value, _tags) {
    2. if (arguments.length === 1) {
    3. return this.options[key];
    4. }
    5. switch (key) {
    6. case 'read':
    7. this.options[key] = readPref(value, _tags);
    8. break;
    9. case 'safe':
    10. this.options[key] = value === false
    11. ? {w: 0}
    12. : value;
    13. break;
    14. case 'timestamps':
    15. this.setupTimestamp(value);
    16. this.options[key] = value;
    17. break;
    18. default:
    19. this.options[key] = value;
    20. }
    21. return this;
    22. };

    Schema#setupTimestamp(timestamps)

    Setup updatedAt and createdAt timestamps to documents if enabled

    Parameters:

    show code

    1. Schema.prototype.setupTimestamp = function(timestamps) {
    2. if (timestamps) {
    3. var createdAt = handleTimestampOption(timestamps, 'createdAt');
    4. var updatedAt = handleTimestampOption(timestamps, 'updatedAt');
    5. var schemaAdditions = {};
    6. if (updatedAt && !this.paths[updatedAt]) {
    7. schemaAdditions[updatedAt] = Date;
    8. }
    9. if (createdAt && !this.paths[createdAt]) {
    10. schemaAdditions[createdAt] = Date;
    11. }
    12. this.add(schemaAdditions);
    13. this.pre('save', function(next) {
    14. var defaultTimestamp = new Date();
    15. var auto_id = this._id && this._id.auto;
    16. if (createdAt != null && !this.get(createdAt) && this.isSelected(createdAt)) {
    17. this.set(createdAt, auto_id ? this._id.getTimestamp() : defaultTimestamp);
    18. }
    19. if (updatedAt != null && (this.isNew || this.isModified())) {
    20. var ts = defaultTimestamp;
    21. if (this.isNew) {
    22. if (createdAt != null) {
    23. ts = this.get(createdAt);
    24. } else if (auto_id) {
    25. ts = this._id.getTimestamp();
    26. }
    27. }
    28. this.set(updatedAt, ts);
    29. }
    30. next();
    31. });
    32. var genUpdates = function(currentUpdate, overwrite) {
    33. var now = new Date();
    34. var updates = {};
    35. var _updates = updates;
    36. if (overwrite) {
    37. if (currentUpdate && currentUpdate.$set) {
    38. currentUpdate = currentUpdate.$set;
    39. updates.$set = {};
    40. _updates = updates.$set;
    41. }
    42. if (updatedAt != null && !currentUpdate[updatedAt]) {
    43. _updates[updatedAt] = now;
    44. }
    45. if (createdAt != null && !currentUpdate[createdAt]) {
    46. _updates[createdAt] = now;
    47. }
    48. return updates;
    49. }
    50. updates = { $set: {} };
    51. currentUpdate = currentUpdate || {};
    52. if (updatedAt != null &&
    53. (!currentUpdate.$currentDate || !currentUpdate.$currentDate[updatedAt])) {
    54. updates.$set[updatedAt] = now;
    55. }
    56. if (createdAt != null) {
    57. if (currentUpdate[createdAt]) {
    58. delete currentUpdate[createdAt];
    59. }
    60. if (currentUpdate.$set && currentUpdate.$set[createdAt]) {
    61. delete currentUpdate.$set[createdAt];
    62. }
    63. updates.$setOnInsert = {};
    64. updates.$setOnInsert[createdAt] = now;
    65. }
    66. return updates;
    67. };
    68. this.methods.initializeTimestamps = function() {
    69. if (!this.get(createdAt)) {
    70. this.set(createdAt, new Date());
    71. }
    72. if (!this.get(updatedAt)) {
    73. this.set(updatedAt, new Date());
    74. }
    75. return this;
    76. };
    77. this.pre('findOneAndUpdate', function(next) {
    78. var overwrite = this.options.overwrite;
    79. this.findOneAndUpdate({}, genUpdates(this.getUpdate(), overwrite), {
    80. overwrite: overwrite
    81. });
    82. applyTimestampsToChildren(this);
    83. next();
    84. });
    85. this.pre('update', function(next) {
    86. var overwrite = this.options.overwrite;
    87. this.update({}, genUpdates(this.getUpdate(), overwrite), {
    88. overwrite: overwrite
    89. });
    90. applyTimestampsToChildren(this);
    91. next();
    92. });
    93. }
    94. };

    Schema#static(name, [fn])

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

    Parameters:

    Example

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

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

    show code

    1. Schema.prototype.static = function(name, fn) {
    2. if (typeof name !== 'string') {
    3. for (var i in name) {
    4. this.statics[i] = name[i];
    5. }
    6. } else {
    7. this.statics[name] = fn;
    8. }
    9. return this;
    10. };

    Schema#virtual(name, [options])

    Creates a virtual type with the given name.

    Parameters:

    Returns:

    show code

    1. Schema.prototype.virtual = function(name, options) {
    2. if (options && options.ref) {
    3. if (!options.localField) {
    4. throw new Error('Reference virtuals require `localField` option');
    5. }
    6. if (!options.foreignField) {
    7. throw new Error('Reference virtuals require `foreignField` option');
    8. }
    9. this.pre('init', function(next, obj) {
    10. if (mpath.has(name, obj)) {
    11. var _v = mpath.get(name, obj);
    12. if (!this.$$populatedVirtuals) {
    13. this.$$populatedVirtuals = {};
    14. }
    15. if (options.justOne) {
    16. this.$$populatedVirtuals[name] = Array.isArray(_v) ?
    17. _v[0] :
    18. _v;
    19. } else {
    20. this.$$populatedVirtuals[name] = Array.isArray(_v) ?
    21. _v :
    22. _v == null ? [] : [_v];
    23. }
    24. mpath.unset(name, obj);
    25. }
    26. if (this.ownerDocument) {
    27. next();
    28. return this;
    29. } else {
    30. next();
    31. }
    32. });
    33. var virtual = this.virtual(name);
    34. virtual.options = options;
    35. return virtual.
    36. get(function() {
    37. if (!this.$$populatedVirtuals) {
    38. this.$$populatedVirtuals = {};
    39. }
    40. if (name in this.$$populatedVirtuals) {
    41. return this.$$populatedVirtuals[name];
    42. }
    43. return null;
    44. }).
    45. set(function(_v) {
    46. if (!this.$$populatedVirtuals) {
    47. this.$$populatedVirtuals = {};
    48. }
    49. if (options.justOne) {
    50. this.$$populatedVirtuals[name] = Array.isArray(_v) ?
    51. _v[0] :
    52. _v;
    53. if (typeof this.$$populatedVirtuals[name] !== 'object') {
    54. this.$$populatedVirtuals[name] = null;
    55. }
    56. } else {
    57. this.$$populatedVirtuals[name] = Array.isArray(_v) ?
    58. _v :
    59. _v == null ? [] : [_v];
    60. this.$$populatedVirtuals[name] = this.$$populatedVirtuals[name].filter(function(doc) {
    61. return doc && typeof doc === 'object';
    62. });
    63. }
    64. });
    65. }
    66. var virtuals = this.virtuals;
    67. var parts = name.split('.');
    68. if (this.pathType(name) === 'real') {
    69. throw new Error('Virtual path "' + name + '"' +
    70. ' conflicts with a real path in the schema');
    71. }
    72. virtuals[name] = parts.reduce(function(mem, part, i) {
    73. mem[part] || (mem[part] = (i === parts.length - 1)
    74. ? new VirtualType(options, name)
    75. : {});
    76. return mem[part];
    77. }, this.tree);
    78. return virtuals[name];
    79. };

    Schema#virtualpath(name)

    Returns the virtual type with the given name.

    Parameters:

    Returns:

    show code

    1. Schema.prototype.virtualpath = function(name) {
    2. return this.virtuals[name];
    3. };

    Schema.indexTypes()

    The allowed index types

    show code

    1. var indexTypes = '2d 2dsphere hashed text'.split(' ');
    2. Object.defineProperty(Schema, 'indexTypes', {
    3. get: function() {
    4. return indexTypes;
    5. },
    6. set: function() {
    7. throw new Error('Cannot overwrite Schema.indexTypes');
    8. }
    9. });

    Schema.interpretAsType(path, obj)

    Converts type arguments into Mongoose Types.

    show code

    1. Schema.interpretAsType = function(path, obj, options) {
    2. if (obj instanceof SchemaType) {
    3. return obj;
    4. }
    5. if (obj.constructor) {
    6. var constructorName = utils.getFunctionName(obj.constructor);
    7. if (constructorName !== 'Object') {
    8. var oldObj = obj;
    9. obj = {};
    10. obj[options.typeKey] = oldObj;
    11. }
    12. }
    13. // Get the type making sure to allow keys named "type"
    14. // and default to mixed if not specified.
    15. // { type: { type: String, default: 'freshcut' } }
    16. var type = obj[options.typeKey] && (options.typeKey !== 'type' || !obj.type.type)
    17. ? obj[options.typeKey]
    18. : {};
    19. if (utils.getFunctionName(type.constructor) === 'Object' || type === 'mixed') {
    20. return new MongooseTypes.Mixed(path, obj);
    21. }
    22. if (Array.isArray(type) || Array === type || type === 'array') {
    23. // if it was specified through { type } look for `cast`
    24. var cast = (Array === type || type === 'array')
    25. ? obj.cast
    26. : type[0];
    27. if (cast && cast.instanceOfSchema) {
    28. return new MongooseTypes.DocumentArray(path, cast, obj);
    29. }
    30. if (cast &&
    31. cast[options.typeKey] &&
    32. cast[options.typeKey].instanceOfSchema) {
    33. return new MongooseTypes.DocumentArray(path, cast[options.typeKey], cast);
    34. }
    35. if (Array.isArray(cast)) {
    36. return new MongooseTypes.Array(path, Schema.interpretAsType(path, cast, options), obj);
    37. }
    38. if (typeof cast === 'string') {
    39. cast = MongooseTypes[cast.charAt(0).toUpperCase() + cast.substring(1)];
    40. } else if (cast && (!cast[options.typeKey] || (options.typeKey === 'type' && cast.type.type))
    41. && utils.getFunctionName(cast.constructor) === 'Object') {
    42. if (Object.keys(cast).length) {
    43. // The `minimize` and `typeKey` options propagate to child schemas
    44. // declared inline, like `{ arr: [{ val: { $type: String } }] }`.
    45. // See gh-3560
    46. var childSchemaOptions = {minimize: options.minimize};
    47. if (options.typeKey) {
    48. childSchemaOptions.typeKey = options.typeKey;
    49. }
    50. //propagate 'strict' option to child schema
    51. if (options.hasOwnProperty('strict')) {
    52. childSchemaOptions.strict = options.strict;
    53. }
    54. //propagate 'runSettersOnQuery' option to child schema
    55. if (options.hasOwnProperty('runSettersOnQuery')) {
    56. childSchemaOptions.runSettersOnQuery = options.runSettersOnQuery;
    57. }
    58. var childSchema = new Schema(cast, childSchemaOptions);
    59. childSchema.$implicitlyCreated = true;
    60. return new MongooseTypes.DocumentArray(path, childSchema, obj);
    61. } else {
    62. // Special case: empty object becomes mixed
    63. return new MongooseTypes.Array(path, MongooseTypes.Mixed, obj);
    64. }
    65. }
    66. if (cast) {
    67. type = cast[options.typeKey] && (options.typeKey !== 'type' || !cast.type.type)
    68. ? cast[options.typeKey]
    69. : cast;
    70. name = typeof type === 'string'
    71. ? type
    72. : type.schemaName || utils.getFunctionName(type);
    73. if (!(name in MongooseTypes)) {
    74. throw new TypeError('Undefined type `' + name + '` at array `' + path +
    75. '`');
    76. }
    77. }
    78. return new MongooseTypes.Array(path, cast || MongooseTypes.Mixed, obj, options);
    79. }
    80. if (type && type.instanceOfSchema) {
    81. return new MongooseTypes.Embedded(type, path, obj);
    82. }
    83. var name;
    84. if (Buffer.isBuffer(type)) {
    85. name = 'Buffer';
    86. } else {
    87. name = typeof type === 'string'
    88. ? type
    89. // If not string, `type` is a function. Outside of IE, function.name
    90. // gives you the function name. In IE, you need to compute it
    91. : type.schemaName || utils.getFunctionName(type);
    92. }
    93. if (name) {
    94. name = name.charAt(0).toUpperCase() + name.substring(1);
    95. }
    96. if (undefined == MongooseTypes[name]) {
    97. throw new TypeError('Undefined type `' + name + '` at `' + path +
    98. '`
    99. Did you try nesting Schemas? ' +
    100. 'You can only nest using refs or arrays.');
    101. }
    102. obj = utils.clone(obj, { retainKeyOrder: true });
    103. if (!('runSettersOnQuery' in obj)) {
    104. obj.runSettersOnQuery = options.runSettersOnQuery;
    105. }
    106. return new MongooseTypes[name](path, obj);
    107. };

    Parameters:


    Schema.reserved

    Reserved document keys.

    show code

    1. Schema.reserved = Object.create(null);
    2. var reserved = Schema.reserved;
    3. // Core object
    4. reserved['prototype'] =
    5. // EventEmitter
    6. reserved.emit =
    7. reserved.on =
    8. reserved.once =
    9. reserved.listeners =
    10. reserved.removeListener =
    11. // document properties and functions
    12. reserved.collection =
    13. reserved.db =
    14. reserved.errors =
    15. reserved.init =
    16. reserved.isModified =
    17. reserved.isNew =
    18. reserved.get =
    19. reserved.modelName =
    20. reserved.save =
    21. reserved.schema =
    22. reserved.toObject =
    23. reserved.validate =
    24. reserved.remove =
    25. // hooks.js
    26. reserved._pres = reserved._posts = 1;

    Keys in this object are names that are rejected in schema declarations b/c they conflict with mongoose functionality. Using these key name will throw an error.

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

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

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

    Schema.Types

    The various built-in Mongoose Schema Types.

    show code

    1. Schema.Types = MongooseTypes = require('./schema/index');

    Example:

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

    Types:

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

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

    Schema#_defaultMiddleware

    Default middleware attached to a schema. Cannot be changed.

    This field is used to make sure discriminators don’t get multiple copies of
    built-in middleware. Declared as a constant because changing this at runtime
    may lead to instability with Model.prototype.discriminator().

    show code

    1. Object.defineProperty(Schema.prototype, '_defaultMiddleware', {
    2. configurable: false,
    3. enumerable: false,
    4. writable: false,
    5. value: [
    6. {
    7. kind: 'pre',
    8. hook: 'remove',
    9. isAsync: true,
    10. fn: function(next, done) {
    11. if (this.ownerDocument) {
    12. done();
    13. next();
    14. return;
    15. }
    16. var subdocs = this.$__getAllSubdocs();
    17. if (!subdocs.length) {
    18. done();
    19. next();
    20. return;
    21. }
    22. each(subdocs, function(subdoc, cb) {
    23. subdoc.remove({ noop: true }, function(err) {
    24. cb(err);
    25. });
    26. }, function(error) {
    27. if (error) {
    28. done(error);
    29. return;
    30. }
    31. next();
    32. done();
    33. });
    34. }
    35. }
    36. ]
    37. });

    Schema#childSchemas

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

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

    show code

    1. Object.defineProperty(Schema.prototype, 'childSchemas', {
    2. configurable: false,
    3. enumerable: true,
    4. writable: true
    5. });

    Schema#obj

    The original object passed to the schema constructor

    Example:

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

    show code

    1. Schema.prototype.obj;

    Schema#paths

    Schema as flat paths

    Example:

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

    show code

    1. Schema.prototype.paths;

    Schema#tree

    Schema as a tree

    Example:

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

    show code

    1. Schema.prototype.tree;

  • document_provider.web.js

    module.exports()

    Returns the Document constructor for the current context

    show code

    1. module.exports = function() {
    2. return BrowserDocument;
    3. };

  • collection.js

    Collection#addQueue(name, args)

    Queues a method for later execution when its
    database connection opens.

    Parameters:

    • name <String> name of the method to queue
    • args <Array> arguments to pass to the method when executed

    show code

    1. Collection.prototype.addQueue = function(name, args) {
    2. this.queue.push([name, args]);
    3. return this;
    4. };

    Collection(name, conn, opts)

    Abstract Collection constructor

    Parameters:

    • name <String> name of the collection
    • conn <Connection> A MongooseConnection instance
    • opts <Object> optional collection options

    This is the base class that drivers inherit from and implement.

    show code

    1. function Collection(name, conn, opts) {
    2. if (opts === void 0) {
    3. opts = {};
    4. }
    5. if (opts.capped === void 0) {
    6. opts.capped = {};
    7. }
    8. opts.bufferCommands = undefined === opts.bufferCommands
    9. ? true
    10. : opts.bufferCommands;
    11. if (typeof opts.capped === 'number') {
    12. opts.capped = {size: opts.capped};
    13. }
    14. this.opts = opts;
    15. this.name = name;
    16. this.collectionName = name;
    17. this.conn = conn;
    18. this.queue = [];
    19. this.buffer = this.opts.bufferCommands;
    20. this.emitter = new EventEmitter();
    21. if (STATES.connected === this.conn.readyState) {
    22. this.onOpen();
    23. }
    24. }

    Collection#createIndex()

    Abstract method that drivers must implement.

    show code

    1. Collection.prototype.createIndex = function() {
    2. throw new Error('Collection#ensureIndex unimplemented by driver');
    3. };

    Collection#doQueue()

    Executes all queued methods and clears the queue.

    show code

    1. Collection.prototype.doQueue = function() {
    2. for (var i = 0, l = this.queue.length; i < l; i++) {
    3. if (typeof this.queue[i][0] === 'function') {
    4. this.queue[i][0].apply(this, this.queue[i][1]);
    5. } else {
    6. this[this.queue[i][0]].apply(this, this.queue[i][1]);
    7. }
    8. }
    9. this.queue = [];
    10. var _this = this;
    11. process.nextTick(function() {
    12. _this.emitter.emit('queue');
    13. });
    14. return this;
    15. };

    Collection#ensureIndex()

    Abstract method that drivers must implement.

    show code

    1. Collection.prototype.ensureIndex = function() {
    2. throw new Error('Collection#ensureIndex unimplemented by driver');
    3. };

    Collection#find()

    Abstract method that drivers must implement.

    show code

    1. Collection.prototype.find = function() {
    2. throw new Error('Collection#find unimplemented by driver');
    3. };

    Collection#findAndModify()

    Abstract method that drivers must implement.

    show code

    1. Collection.prototype.findAndModify = function() {
    2. throw new Error('Collection#findAndModify unimplemented by driver');
    3. };

    Collection#findOne()

    Abstract method that drivers must implement.

    show code

    1. Collection.prototype.findOne = function() {
    2. throw new Error('Collection#findOne unimplemented by driver');
    3. };

    Collection#getIndexes()

    Abstract method that drivers must implement.

    show code

    1. Collection.prototype.getIndexes = function() {
    2. throw new Error('Collection#getIndexes unimplemented by driver');
    3. };

    Collection#insert()

    Abstract method that drivers must implement.

    show code

    1. Collection.prototype.insert = function() {
    2. throw new Error('Collection#insert unimplemented by driver');
    3. };

    Collection#mapReduce()

    Abstract method that drivers must implement.

    show code

    1. Collection.prototype.mapReduce = function() {
    2. throw new Error('Collection#mapReduce unimplemented by driver');
    3. };

    Collection#onClose()

    Called when the database disconnects

    show code

    1. Collection.prototype.onClose = function(force) {
    2. if (this.opts.bufferCommands && !force) {
    3. this.buffer = true;
    4. }
    5. };

    Collection#onOpen()

    Called when the database connects

    show code

    1. Collection.prototype.onOpen = function() {
    2. this.buffer = false;
    3. var _this = this;
    4. setImmediate(function() {
    5. _this.doQueue();
    6. });
    7. };

    Collection#save()

    Abstract method that drivers must implement.

    show code

    1. Collection.prototype.save = function() {
    2. throw new Error('Collection#save unimplemented by driver');
    3. };

    Collection#update()

    Abstract method that drivers must implement.

    show code

    1. Collection.prototype.update = function() {
    2. throw new Error('Collection#update unimplemented by driver');
    3. };

    Collection#collectionName

    The collection name

    show code

    1. Collection.prototype.collectionName;

    Collection#conn

    The Connection instance

    show code

    1. Collection.prototype.conn;

    Collection#name

    The collection name

    show code

    1. Collection.prototype.name;