index.js 43 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160
  1. 'use strict';
  2. /*!
  3. * Module dependencies.
  4. */
  5. if (global.MONGOOSE_DRIVER_PATH) {
  6. const deprecationWarning = 'The `MONGOOSE_DRIVER_PATH` global property is ' +
  7. 'deprecated. Use `mongoose.driver.set()` instead.';
  8. const setDriver = require('util').deprecate(function() {
  9. require('./driver').set(require(global.MONGOOSE_DRIVER_PATH));
  10. }, deprecationWarning);
  11. setDriver();
  12. } else {
  13. require('./driver').set(require('./drivers/node-mongodb-native'));
  14. }
  15. const Document = require('./document');
  16. const EventEmitter = require('events').EventEmitter;
  17. const Schema = require('./schema');
  18. const SchemaType = require('./schematype');
  19. const SchemaTypes = require('./schema/index');
  20. const VirtualType = require('./virtualtype');
  21. const STATES = require('./connectionstate');
  22. const VALID_OPTIONS = require('./validoptions');
  23. const Types = require('./types');
  24. const Query = require('./query');
  25. const Model = require('./model');
  26. const applyPlugins = require('./helpers/schema/applyPlugins');
  27. const driver = require('./driver');
  28. const get = require('./helpers/get');
  29. const promiseOrCallback = require('./helpers/promiseOrCallback');
  30. const legacyPluralize = require('mongoose-legacy-pluralize');
  31. const utils = require('./utils');
  32. const pkg = require('../package.json');
  33. const cast = require('./cast');
  34. const removeSubdocs = require('./plugins/removeSubdocs');
  35. const saveSubdocs = require('./plugins/saveSubdocs');
  36. const trackTransaction = require('./plugins/trackTransaction');
  37. const validateBeforeSave = require('./plugins/validateBeforeSave');
  38. const Aggregate = require('./aggregate');
  39. const PromiseProvider = require('./promise_provider');
  40. const shardingPlugin = require('./plugins/sharding');
  41. const defaultMongooseSymbol = Symbol.for('mongoose:default');
  42. require('./helpers/printJestWarning');
  43. /**
  44. * Mongoose constructor.
  45. *
  46. * The exports object of the `mongoose` module is an instance of this class.
  47. * Most apps will only use this one instance.
  48. *
  49. * ####Example:
  50. * const mongoose = require('mongoose');
  51. * mongoose instanceof mongoose.Mongoose; // true
  52. *
  53. * // Create a new Mongoose instance with its own `connect()`, `set()`, `model()`, etc.
  54. * const m = new mongoose.Mongoose();
  55. *
  56. * @api public
  57. * @param {Object} options see [`Mongoose#set()` docs](/docs/api/mongoose.html#mongoose_Mongoose-set)
  58. */
  59. function Mongoose(options) {
  60. this.connections = [];
  61. this.models = {};
  62. this.modelSchemas = {};
  63. this.events = new EventEmitter();
  64. // default global options
  65. this.options = Object.assign({
  66. pluralization: true,
  67. autoIndex: true,
  68. useCreateIndex: false
  69. }, options);
  70. const conn = this.createConnection(); // default connection
  71. conn.models = this.models;
  72. if (this.options.pluralization) {
  73. this._pluralize = legacyPluralize;
  74. }
  75. // If a user creates their own Mongoose instance, give them a separate copy
  76. // of the `Schema` constructor so they get separate custom types. (gh-6933)
  77. if (!options || !options[defaultMongooseSymbol]) {
  78. const _this = this;
  79. this.Schema = function() {
  80. this.base = _this;
  81. return Schema.apply(this, arguments);
  82. };
  83. this.Schema.prototype = Object.create(Schema.prototype);
  84. Object.assign(this.Schema, Schema);
  85. this.Schema.base = this;
  86. this.Schema.Types = Object.assign({}, Schema.Types);
  87. } else {
  88. // Hack to work around babel's strange behavior with
  89. // `import mongoose, { Schema } from 'mongoose'`. Because `Schema` is not
  90. // an own property of a Mongoose global, Schema will be undefined. See gh-5648
  91. for (const key of ['Schema', 'model']) {
  92. this[key] = Mongoose.prototype[key];
  93. }
  94. }
  95. this.Schema.prototype.base = this;
  96. Object.defineProperty(this, 'plugins', {
  97. configurable: false,
  98. enumerable: true,
  99. writable: false,
  100. value: [
  101. [saveSubdocs, { deduplicate: true }],
  102. [validateBeforeSave, { deduplicate: true }],
  103. [shardingPlugin, { deduplicate: true }],
  104. [removeSubdocs, { deduplicate: true }],
  105. [trackTransaction, { deduplicate: true }]
  106. ]
  107. });
  108. }
  109. Mongoose.prototype.cast = cast;
  110. /**
  111. * Expose connection states for user-land
  112. *
  113. * @memberOf Mongoose
  114. * @property STATES
  115. * @api public
  116. */
  117. Mongoose.prototype.STATES = STATES;
  118. /**
  119. * Object with `get()` and `set()` containing the underlying driver this Mongoose instance
  120. * uses to communicate with the database. A driver is a Mongoose-specific interface that defines functions
  121. * like `find()`.
  122. *
  123. * @memberOf Mongoose
  124. * @property driver
  125. * @api public
  126. */
  127. Mongoose.prototype.driver = driver;
  128. /**
  129. * Sets mongoose options
  130. *
  131. * ####Example:
  132. *
  133. * mongoose.set('test', value) // sets the 'test' option to `value`
  134. *
  135. * mongoose.set('debug', true) // enable logging collection methods + arguments to the console/file
  136. *
  137. * mongoose.set('debug', function(collectionName, methodName, ...methodArgs) {}); // use custom function to log collection methods + arguments
  138. *
  139. * Currently supported options are:
  140. * - 'debug': If `true`, prints the operations mongoose sends to MongoDB to the console. If a writable stream is passed, it will log to that stream, without colorization. If a callback function is passed, it will receive the collection name, the method name, then all arugments passed to the method. For example, if you wanted to replicate the default logging, you could output from the callback `Mongoose: ${collectionName}.${methodName}(${methodArgs.join(', ')})`.
  141. * - 'returnOriginal': If `false`, changes the default `returnOriginal` option to `findOneAndUpdate()`, `findByIdAndUpdate`, and `findOneAndReplace()` to false. This is equivalent to setting the `new` option to `true` for `findOneAndX()` calls by default. Read our [`findOneAndUpdate()` tutorial](/docs/tutorials/findoneandupdate.html) for more information.
  142. * - 'bufferCommands': enable/disable mongoose's buffering mechanism for all connections and models
  143. * - 'useCreateIndex': false by default. Set to `true` to make Mongoose's default index build use `createIndex()` instead of `ensureIndex()` to avoid deprecation warnings from the MongoDB driver.
  144. * - 'useFindAndModify': true by default. Set to `false` to make `findOneAndUpdate()` and `findOneAndRemove()` use native `findOneAndUpdate()` rather than `findAndModify()`.
  145. * - 'useNewUrlParser': false by default. Set to `true` to make all connections set the `useNewUrlParser` option by default
  146. * - 'useUnifiedTopology': false by default. Set to `true` to make all connections set the `useUnifiedTopology` option by default
  147. * - 'cloneSchemas': false by default. Set to `true` to `clone()` all schemas before compiling into a model.
  148. * - 'applyPluginsToDiscriminators': false by default. Set to true to apply global plugins to discriminator schemas. This typically isn't necessary because plugins are applied to the base schema and discriminators copy all middleware, methods, statics, and properties from the base schema.
  149. * - 'applyPluginsToChildSchemas': true by default. Set to false to skip applying global plugins to child schemas
  150. * - 'objectIdGetter': true by default. Mongoose adds a getter to MongoDB ObjectId's called `_id` that returns `this` for convenience with populate. Set this to false to remove the getter.
  151. * - 'runValidators': false by default. Set to true to enable [update validators](/docs/validation.html#update-validators) for all validators by default.
  152. * - 'toObject': `{ transform: true, flattenDecimals: true }` by default. Overwrites default objects to [`toObject()`](/docs/api.html#document_Document-toObject)
  153. * - 'toJSON': `{ transform: true, flattenDecimals: true }` by default. Overwrites default objects to [`toJSON()`](/docs/api.html#document_Document-toJSON), for determining how Mongoose documents get serialized by `JSON.stringify()`
  154. * - 'strict': true by default, may be `false`, `true`, or `'throw'`. Sets the default strict mode for schemas.
  155. * - 'strictQuery': false by default, may be `false`, `true`, or `'throw'`. Sets the default [strictQuery](/docs/guide.html#strictQuery) mode for schemas.
  156. * - 'selectPopulatedPaths': true by default. Set to false to opt out of Mongoose adding all fields that you `populate()` to your `select()`. The schema-level option `selectPopulatedPaths` overwrites this one.
  157. * - 'typePojoToMixed': true by default, may be `false` or `true`. Sets the default typePojoToMixed for schemas.
  158. * - 'maxTimeMS': If set, attaches [maxTimeMS](https://docs.mongodb.com/manual/reference/operator/meta/maxTimeMS/) to every query
  159. * - 'autoIndex': true by default. Set to false to disable automatic index creation for all models associated with this Mongoose instance.
  160. * - 'autoCreate': Set to `true` to make Mongoose call [`Model.createCollection()`](/docs/api/model.html#model_Model.createCollection) automatically when you create a model with `mongoose.model()` or `conn.model()`. This is useful for testing transactions, change streams, and other features that require the collection to exist.
  161. * - 'overwriteModels': Set to `true` to default to overwriting models with the same name when calling `mongoose.model()`, as opposed to throwing an `OverwriteModelError`.
  162. *
  163. * @param {String} key
  164. * @param {String|Function|Boolean} value
  165. * @api public
  166. */
  167. Mongoose.prototype.set = function(key, value) {
  168. const _mongoose = this instanceof Mongoose ? this : mongoose;
  169. if (VALID_OPTIONS.indexOf(key) === -1) throw new Error(`\`${key}\` is an invalid option.`);
  170. if (arguments.length === 1) {
  171. return _mongoose.options[key];
  172. }
  173. _mongoose.options[key] = value;
  174. if (key === 'objectIdGetter') {
  175. if (value) {
  176. Object.defineProperty(mongoose.Types.ObjectId.prototype, '_id', {
  177. enumerable: false,
  178. configurable: true,
  179. get: function() {
  180. return this;
  181. }
  182. });
  183. } else {
  184. delete mongoose.Types.ObjectId.prototype._id;
  185. }
  186. }
  187. return _mongoose;
  188. };
  189. /**
  190. * Gets mongoose options
  191. *
  192. * ####Example:
  193. *
  194. * mongoose.get('test') // returns the 'test' value
  195. *
  196. * @param {String} key
  197. * @method get
  198. * @api public
  199. */
  200. Mongoose.prototype.get = Mongoose.prototype.set;
  201. /**
  202. * Creates a Connection instance.
  203. *
  204. * Each `connection` instance maps to a single database. This method is helpful when managing multiple db connections.
  205. *
  206. *
  207. * _Options passed take precedence over options included in connection strings._
  208. *
  209. * ####Example:
  210. *
  211. * // with mongodb:// URI
  212. * db = mongoose.createConnection('mongodb://user:pass@localhost:port/database');
  213. *
  214. * // and options
  215. * const opts = { db: { native_parser: true }}
  216. * db = mongoose.createConnection('mongodb://user:pass@localhost:port/database', opts);
  217. *
  218. * // replica sets
  219. * db = mongoose.createConnection('mongodb://user:pass@localhost:port,anotherhost:port,yetanother:port/database');
  220. *
  221. * // and options
  222. * const opts = { replset: { strategy: 'ping', rs_name: 'testSet' }}
  223. * db = mongoose.createConnection('mongodb://user:pass@localhost:port,anotherhost:port,yetanother:port/database', opts);
  224. *
  225. * // and options
  226. * const opts = { server: { auto_reconnect: false }, user: 'username', pass: 'mypassword' }
  227. * db = mongoose.createConnection('localhost', 'database', port, opts)
  228. *
  229. * // initialize now, connect later
  230. * db = mongoose.createConnection();
  231. * db.openUri('localhost', 'database', port, [opts]);
  232. *
  233. * @param {String} [uri] a mongodb:// URI
  234. * @param {Object} [options] passed down to the [MongoDB driver's `connect()` function](http://mongodb.github.io/node-mongodb-native/3.0/api/MongoClient.html), except for 4 mongoose-specific options explained below.
  235. * @param {Boolean} [options.bufferCommands=true] Mongoose specific option. Set to false to [disable buffering](http://mongoosejs.com/docs/faq.html#callback_never_executes) on all models associated with this connection.
  236. * @param {String} [options.dbName] The name of the database you want to use. If not provided, Mongoose uses the database name from connection string.
  237. * @param {String} [options.user] username for authentication, equivalent to `options.auth.user`. Maintained for backwards compatibility.
  238. * @param {String} [options.pass] password for authentication, equivalent to `options.auth.password`. Maintained for backwards compatibility.
  239. * @param {Boolean} [options.autoIndex=true] Mongoose-specific option. Set to false to disable automatic index creation for all models associated with this connection.
  240. * @param {Boolean} [options.useNewUrlParser=false] False by default. Set to `true` to make all connections set the `useNewUrlParser` option by default.
  241. * @param {Boolean} [options.useUnifiedTopology=false] False by default. Set to `true` to make all connections set the `useUnifiedTopology` option by default.
  242. * @param {Boolean} [options.useCreateIndex=true] Mongoose-specific option. If `true`, this connection will use [`createIndex()` instead of `ensureIndex()`](/docs/deprecations.html#ensureindex) for automatic index builds via [`Model.init()`](/docs/api.html#model_Model.init).
  243. * @param {Boolean} [options.useFindAndModify=true] True by default. Set to `false` to make `findOneAndUpdate()` and `findOneAndRemove()` use native `findOneAndUpdate()` rather than `findAndModify()`.
  244. * @param {Number} [options.reconnectTries=30] If you're connected to a single server or mongos proxy (as opposed to a replica set), the MongoDB driver will try to reconnect every `reconnectInterval` milliseconds for `reconnectTries` times, and give up afterward. When the driver gives up, the mongoose connection emits a `reconnectFailed` event. This option does nothing for replica set connections.
  245. * @param {Number} [options.reconnectInterval=1000] See `reconnectTries` option above.
  246. * @param {Class} [options.promiseLibrary] Sets the [underlying driver's promise library](http://mongodb.github.io/node-mongodb-native/3.1/api/MongoClient.html).
  247. * @param {Number} [options.poolSize=5] The maximum number of sockets the MongoDB driver will keep open for this connection. By default, `poolSize` is 5. Keep in mind that, as of MongoDB 3.4, MongoDB only allows one operation per socket at a time, so you may want to increase this if you find you have a few slow queries that are blocking faster queries from proceeding. See [Slow Trains in MongoDB and Node.js](http://thecodebarbarian.com/slow-trains-in-mongodb-and-nodejs).
  248. * @param {Number} [options.bufferMaxEntries] This option does nothing if `useUnifiedTopology` is set. The MongoDB driver also has its own buffering mechanism that kicks in when the driver is disconnected. Set this option to 0 and set `bufferCommands` to `false` on your schemas if you want your database operations to fail immediately when the driver is not connected, as opposed to waiting for reconnection.
  249. * @param {Number} [options.connectTimeoutMS=30000] How long the MongoDB driver will wait before killing a socket due to inactivity _during initial connection_. Defaults to 30000. This option is passed transparently to [Node.js' `socket#setTimeout()` function](https://nodejs.org/api/net.html#net_socket_settimeout_timeout_callback).
  250. * @param {Number} [options.socketTimeoutMS=30000] How long the MongoDB driver will wait before killing a socket due to inactivity _after initial connection_. A socket may be inactive because of either no activity or a long-running operation. This is set to `30000` by default, you should set this to 2-3x your longest running operation if you expect some of your database operations to run longer than 20 seconds. This option is passed to [Node.js `socket#setTimeout()` function](https://nodejs.org/api/net.html#net_socket_settimeout_timeout_callback) after the MongoDB driver successfully completes.
  251. * @param {Number} [options.family=0] Passed transparently to [Node.js' `dns.lookup()`](https://nodejs.org/api/dns.html#dns_dns_lookup_hostname_options_callback) function. May be either `0`, `4`, or `6`. `4` means use IPv4 only, `6` means use IPv6 only, `0` means try both.
  252. * @return {Connection} the created Connection object. Connections are thenable, so you can do `await mongoose.createConnection()`
  253. * @api public
  254. */
  255. Mongoose.prototype.createConnection = function(uri, options, callback) {
  256. const _mongoose = this instanceof Mongoose ? this : mongoose;
  257. const conn = new Connection(_mongoose);
  258. if (typeof options === 'function') {
  259. callback = options;
  260. options = null;
  261. }
  262. _mongoose.connections.push(conn);
  263. _mongoose.events.emit('createConnection', conn);
  264. if (arguments.length > 0) {
  265. return conn.openUri(uri, options, callback);
  266. }
  267. return conn;
  268. };
  269. /**
  270. * Opens the default mongoose connection.
  271. *
  272. * ####Example:
  273. *
  274. * mongoose.connect('mongodb://user:pass@localhost:port/database');
  275. *
  276. * // replica sets
  277. * const uri = 'mongodb://user:pass@localhost:port,anotherhost:port,yetanother:port/mydatabase';
  278. * mongoose.connect(uri);
  279. *
  280. * // with options
  281. * mongoose.connect(uri, options);
  282. *
  283. * // optional callback that gets fired when initial connection completed
  284. * const uri = 'mongodb://nonexistent.domain:27000';
  285. * mongoose.connect(uri, function(error) {
  286. * // if error is truthy, the initial connection failed.
  287. * })
  288. *
  289. * @param {String} uri(s)
  290. * @param {Object} [options] passed down to the [MongoDB driver's `connect()` function](http://mongodb.github.io/node-mongodb-native/3.0/api/MongoClient.html), except for 4 mongoose-specific options explained below.
  291. * @param {Boolean} [options.bufferCommands=true] Mongoose specific option. Set to false to [disable buffering](http://mongoosejs.com/docs/faq.html#callback_never_executes) on all models associated with this connection.
  292. * @param {Number} [options.bufferTimeoutMS=true] Mongoose specific option. If `bufferCommands` is true, Mongoose will throw an error after `bufferTimeoutMS` if the operation is still buffered.
  293. * @param {String} [options.dbName] The name of the database we want to use. If not provided, use database name from connection string.
  294. * @param {String} [options.user] username for authentication, equivalent to `options.auth.user`. Maintained for backwards compatibility.
  295. * @param {String} [options.pass] password for authentication, equivalent to `options.auth.password`. Maintained for backwards compatibility.
  296. * @param {Number} [options.poolSize=5] The maximum number of sockets the MongoDB driver will keep open for this connection. By default, `poolSize` is 5. Keep in mind that, as of MongoDB 3.4, MongoDB only allows one operation per socket at a time, so you may want to increase this if you find you have a few slow queries that are blocking faster queries from proceeding. See [Slow Trains in MongoDB and Node.js](http://thecodebarbarian.com/slow-trains-in-mongodb-and-nodejs).
  297. * @param {Boolean} [options.useUnifiedTopology=false] False by default. Set to `true` to opt in to the MongoDB driver's replica set and sharded cluster monitoring engine.
  298. * @param {Number} [options.serverSelectionTimeoutMS] If `useUnifiedTopology = true`, the MongoDB driver will try to find a server to send any given operation to, and keep retrying for `serverSelectionTimeoutMS` milliseconds before erroring out. If not set, the MongoDB driver defaults to using `30000` (30 seconds).
  299. * @param {Number} [options.heartbeatFrequencyMS] If `useUnifiedTopology = true`, the MongoDB driver sends a heartbeat every `heartbeatFrequencyMS` to check on the status of the connection. A heartbeat is subject to `serverSelectionTimeoutMS`, so the MongoDB driver will retry failed heartbeats for up to 30 seconds by default. Mongoose only emits a `'disconnected'` event after a heartbeat has failed, so you may want to decrease this setting to reduce the time between when your server goes down and when Mongoose emits `'disconnected'`. We recommend you do **not** set this setting below 1000, too many heartbeats can lead to performance degradation.
  300. * @param {Boolean} [options.autoIndex=true] Mongoose-specific option. Set to false to disable automatic index creation for all models associated with this connection.
  301. * @param {Boolean} [options.useNewUrlParser=false] False by default. Set to `true` to opt in to the MongoDB driver's new URL parser logic.
  302. * @param {Boolean} [options.useCreateIndex=true] Mongoose-specific option. If `true`, this connection will use [`createIndex()` instead of `ensureIndex()`](/docs/deprecations.html#ensureindex) for automatic index builds via [`Model.init()`](/docs/api.html#model_Model.init).
  303. * @param {Boolean} [options.useFindAndModify=true] True by default. Set to `false` to make `findOneAndUpdate()` and `findOneAndRemove()` use native `findOneAndUpdate()` rather than `findAndModify()`.
  304. * @param {Number} [options.reconnectTries=30] If you're connected to a single server or mongos proxy (as opposed to a replica set), the MongoDB driver will try to reconnect every `reconnectInterval` milliseconds for `reconnectTries` times, and give up afterward. When the driver gives up, the mongoose connection emits a `reconnectFailed` event. This option does nothing for replica set connections.
  305. * @param {Number} [options.reconnectInterval=1000] See `reconnectTries` option above.
  306. * @param {Class} [options.promiseLibrary] Sets the [underlying driver's promise library](http://mongodb.github.io/node-mongodb-native/3.1/api/MongoClient.html).
  307. * @param {Number} [options.bufferMaxEntries] This option does nothing if `useUnifiedTopology` is set. The MongoDB driver also has its own buffering mechanism that kicks in when the driver is disconnected. Set this option to 0 and set `bufferCommands` to `false` on your schemas if you want your database operations to fail immediately when the driver is not connected, as opposed to waiting for reconnection.
  308. * @param {Number} [options.connectTimeoutMS=30000] How long the MongoDB driver will wait before killing a socket due to inactivity _during initial connection_. Defaults to 30000. This option is passed transparently to [Node.js' `socket#setTimeout()` function](https://nodejs.org/api/net.html#net_socket_settimeout_timeout_callback).
  309. * @param {Number} [options.socketTimeoutMS=30000] How long the MongoDB driver will wait before killing a socket due to inactivity _after initial connection_. A socket may be inactive because of either no activity or a long-running operation. This is set to `30000` by default, you should set this to 2-3x your longest running operation if you expect some of your database operations to run longer than 20 seconds. This option is passed to [Node.js `socket#setTimeout()` function](https://nodejs.org/api/net.html#net_socket_settimeout_timeout_callback) after the MongoDB driver successfully completes.
  310. * @param {Number} [options.family=0] Passed transparently to [Node.js' `dns.lookup()`](https://nodejs.org/api/dns.html#dns_dns_lookup_hostname_options_callback) function. May be either `0`, `4`, or `6`. `4` means use IPv4 only, `6` means use IPv6 only, `0` means try both.
  311. * @param {Boolean} [options.autoCreate=false] Set to `true` to make Mongoose automatically call `createCollection()` on every model created on this connection.
  312. * @param {Function} [callback]
  313. * @see Mongoose#createConnection #index_Mongoose-createConnection
  314. * @api public
  315. * @return {Promise} resolves to `this` if connection succeeded
  316. */
  317. Mongoose.prototype.connect = function(uri, options, callback) {
  318. const _mongoose = this instanceof Mongoose ? this : mongoose;
  319. const conn = _mongoose.connection;
  320. return _mongoose._promiseOrCallback(callback, cb => {
  321. conn.openUri(uri, options, err => {
  322. if (err != null) {
  323. return cb(err);
  324. }
  325. return cb(null, _mongoose);
  326. });
  327. });
  328. };
  329. /**
  330. * Runs `.close()` on all connections in parallel.
  331. *
  332. * @param {Function} [callback] called after all connection close, or when first error occurred.
  333. * @return {Promise} resolves when all connections are closed, or rejects with the first error that occurred.
  334. * @api public
  335. */
  336. Mongoose.prototype.disconnect = function(callback) {
  337. const _mongoose = this instanceof Mongoose ? this : mongoose;
  338. return _mongoose._promiseOrCallback(callback, cb => {
  339. let remaining = _mongoose.connections.length;
  340. if (remaining <= 0) {
  341. return cb(null);
  342. }
  343. _mongoose.connections.forEach(conn => {
  344. conn.close(function(error) {
  345. if (error) {
  346. return cb(error);
  347. }
  348. if (!--remaining) {
  349. cb(null);
  350. }
  351. });
  352. });
  353. });
  354. };
  355. /**
  356. * _Requires MongoDB >= 3.6.0._ Starts a [MongoDB session](https://docs.mongodb.com/manual/release-notes/3.6/#client-sessions)
  357. * for benefits like causal consistency, [retryable writes](https://docs.mongodb.com/manual/core/retryable-writes/),
  358. * and [transactions](http://thecodebarbarian.com/a-node-js-perspective-on-mongodb-4-transactions.html).
  359. *
  360. * Calling `mongoose.startSession()` is equivalent to calling `mongoose.connection.startSession()`.
  361. * Sessions are scoped to a connection, so calling `mongoose.startSession()`
  362. * starts a session on the [default mongoose connection](/docs/api.html#mongoose_Mongoose-connection).
  363. *
  364. * @param {Object} [options] see the [mongodb driver options](http://mongodb.github.io/node-mongodb-native/3.0/api/MongoClient.html#startSession)
  365. * @param {Boolean} [options.causalConsistency=true] set to false to disable causal consistency
  366. * @param {Function} [callback]
  367. * @return {Promise<ClientSession>} promise that resolves to a MongoDB driver `ClientSession`
  368. * @api public
  369. */
  370. Mongoose.prototype.startSession = function() {
  371. const _mongoose = this instanceof Mongoose ? this : mongoose;
  372. return _mongoose.connection.startSession.apply(_mongoose.connection, arguments);
  373. };
  374. /**
  375. * Getter/setter around function for pluralizing collection names.
  376. *
  377. * @param {Function|null} [fn] overwrites the function used to pluralize collection names
  378. * @return {Function|null} the current function used to pluralize collection names, defaults to the legacy function from `mongoose-legacy-pluralize`.
  379. * @api public
  380. */
  381. Mongoose.prototype.pluralize = function(fn) {
  382. const _mongoose = this instanceof Mongoose ? this : mongoose;
  383. if (arguments.length > 0) {
  384. _mongoose._pluralize = fn;
  385. }
  386. return _mongoose._pluralize;
  387. };
  388. /**
  389. * Defines a model or retrieves it.
  390. *
  391. * Models defined on the `mongoose` instance are available to all connection
  392. * created by the same `mongoose` instance.
  393. *
  394. * If you call `mongoose.model()` with twice the same name but a different schema,
  395. * you will get an `OverwriteModelError`. If you call `mongoose.model()` with
  396. * the same name and same schema, you'll get the same schema back.
  397. *
  398. * ####Example:
  399. *
  400. * const mongoose = require('mongoose');
  401. *
  402. * // define an Actor model with this mongoose instance
  403. * const schema = new Schema({ name: String });
  404. * mongoose.model('Actor', schema);
  405. *
  406. * // create a new connection
  407. * const conn = mongoose.createConnection(..);
  408. *
  409. * // create Actor model
  410. * const Actor = conn.model('Actor', schema);
  411. * conn.model('Actor') === Actor; // true
  412. * conn.model('Actor', schema) === Actor; // true, same schema
  413. * conn.model('Actor', schema, 'actors') === Actor; // true, same schema and collection name
  414. *
  415. * // This throws an `OverwriteModelError` because the schema is different.
  416. * conn.model('Actor', new Schema({ name: String }));
  417. *
  418. * _When no `collection` argument is passed, Mongoose uses the model name. If you don't like this behavior, either pass a collection name, use `mongoose.pluralize()`, or set your schemas collection name option._
  419. *
  420. * ####Example:
  421. *
  422. * const schema = new Schema({ name: String }, { collection: 'actor' });
  423. *
  424. * // or
  425. *
  426. * schema.set('collection', 'actor');
  427. *
  428. * // or
  429. *
  430. * const collectionName = 'actor'
  431. * const M = mongoose.model('Actor', schema, collectionName)
  432. *
  433. * @param {String|Function} name model name or class extending Model
  434. * @param {Schema} [schema] the schema to use.
  435. * @param {String} [collection] name (optional, inferred from model name)
  436. * @param {Boolean|Object} [skipInit] whether to skip initialization (defaults to false). If an object, treated as options.
  437. * @return {Model} The model associated with `name`. Mongoose will create the model if it doesn't already exist.
  438. * @api public
  439. */
  440. Mongoose.prototype.model = function(name, schema, collection, skipInit) {
  441. const _mongoose = this instanceof Mongoose ? this : mongoose;
  442. let model;
  443. if (typeof name === 'function') {
  444. model = name;
  445. name = model.name;
  446. if (!(model.prototype instanceof Model)) {
  447. throw new _mongoose.Error('The provided class ' + name + ' must extend Model');
  448. }
  449. }
  450. if (typeof schema === 'string') {
  451. collection = schema;
  452. schema = false;
  453. }
  454. if (utils.isObject(schema) && !(schema instanceof Schema)) {
  455. schema = new Schema(schema);
  456. }
  457. if (schema && !(schema instanceof Schema)) {
  458. throw new Error('The 2nd parameter to `mongoose.model()` should be a ' +
  459. 'schema or a POJO');
  460. }
  461. if (typeof collection === 'boolean') {
  462. skipInit = collection;
  463. collection = null;
  464. }
  465. // handle internal options from connection.model()
  466. let options;
  467. if (skipInit && utils.isObject(skipInit)) {
  468. options = skipInit;
  469. skipInit = true;
  470. } else {
  471. options = {};
  472. }
  473. // look up schema for the collection.
  474. if (!_mongoose.modelSchemas[name]) {
  475. if (schema) {
  476. // cache it so we only apply plugins once
  477. _mongoose.modelSchemas[name] = schema;
  478. } else {
  479. throw new mongoose.Error.MissingSchemaError(name);
  480. }
  481. }
  482. const originalSchema = schema;
  483. if (schema) {
  484. if (_mongoose.get('cloneSchemas')) {
  485. schema = schema.clone();
  486. }
  487. _mongoose._applyPlugins(schema);
  488. }
  489. let sub;
  490. // connection.model() may be passing a different schema for
  491. // an existing model name. in this case don't read from cache.
  492. const overwriteModels = _mongoose.options.hasOwnProperty('overwriteModels') ?
  493. _mongoose.options.overwriteModels :
  494. options.overwriteModels;
  495. if (_mongoose.models[name] && options.cache !== false && overwriteModels !== true) {
  496. if (originalSchema &&
  497. originalSchema.instanceOfSchema &&
  498. originalSchema !== _mongoose.models[name].schema) {
  499. throw new _mongoose.Error.OverwriteModelError(name);
  500. }
  501. if (collection && collection !== _mongoose.models[name].collection.name) {
  502. // subclass current model with alternate collection
  503. model = _mongoose.models[name];
  504. schema = model.prototype.schema;
  505. sub = model.__subclass(_mongoose.connection, schema, collection);
  506. // do not cache the sub model
  507. return sub;
  508. }
  509. return _mongoose.models[name];
  510. }
  511. // ensure a schema exists
  512. if (!schema) {
  513. schema = this.modelSchemas[name];
  514. if (!schema) {
  515. throw new mongoose.Error.MissingSchemaError(name);
  516. }
  517. }
  518. // Apply relevant "global" options to the schema
  519. if (!('pluralization' in schema.options)) {
  520. schema.options.pluralization = _mongoose.options.pluralization;
  521. }
  522. if (!collection) {
  523. collection = schema.get('collection') ||
  524. utils.toCollectionName(name, _mongoose.pluralize());
  525. }
  526. const connection = options.connection || _mongoose.connection;
  527. model = _mongoose.Model.compile(model || name, schema, collection, connection, _mongoose);
  528. if (!skipInit) {
  529. // Errors handled internally, so safe to ignore error
  530. model.init(function $modelInitNoop() {});
  531. }
  532. connection.emit('model', model);
  533. if (options.cache === false) {
  534. return model;
  535. }
  536. _mongoose.models[name] = model;
  537. return _mongoose.models[name];
  538. };
  539. /**
  540. * Removes the model named `name` from the default connection, if it exists.
  541. * You can use this function to clean up any models you created in your tests to
  542. * prevent OverwriteModelErrors.
  543. *
  544. * Equivalent to `mongoose.connection.deleteModel(name)`.
  545. *
  546. * ####Example:
  547. *
  548. * mongoose.model('User', new Schema({ name: String }));
  549. * console.log(mongoose.model('User')); // Model object
  550. * mongoose.deleteModel('User');
  551. * console.log(mongoose.model('User')); // undefined
  552. *
  553. * // Usually useful in a Mocha `afterEach()` hook
  554. * afterEach(function() {
  555. * mongoose.deleteModel(/.+/); // Delete every model
  556. * });
  557. *
  558. * @api public
  559. * @param {String|RegExp} name if string, the name of the model to remove. If regexp, removes all models whose name matches the regexp.
  560. * @return {Mongoose} this
  561. */
  562. Mongoose.prototype.deleteModel = function(name) {
  563. const _mongoose = this instanceof Mongoose ? this : mongoose;
  564. _mongoose.connection.deleteModel(name);
  565. return _mongoose;
  566. };
  567. /**
  568. * Returns an array of model names created on this instance of Mongoose.
  569. *
  570. * ####Note:
  571. *
  572. * _Does not include names of models created using `connection.model()`._
  573. *
  574. * @api public
  575. * @return {Array}
  576. */
  577. Mongoose.prototype.modelNames = function() {
  578. const _mongoose = this instanceof Mongoose ? this : mongoose;
  579. const names = Object.keys(_mongoose.models);
  580. return names;
  581. };
  582. /**
  583. * Applies global plugins to `schema`.
  584. *
  585. * @param {Schema} schema
  586. * @api private
  587. */
  588. Mongoose.prototype._applyPlugins = function(schema, options) {
  589. const _mongoose = this instanceof Mongoose ? this : mongoose;
  590. options = options || {};
  591. options.applyPluginsToDiscriminators = get(_mongoose,
  592. 'options.applyPluginsToDiscriminators', false);
  593. options.applyPluginsToChildSchemas = get(_mongoose,
  594. 'options.applyPluginsToChildSchemas', true);
  595. applyPlugins(schema, _mongoose.plugins, options, '$globalPluginsApplied');
  596. };
  597. /**
  598. * Declares a global plugin executed on all Schemas.
  599. *
  600. * Equivalent to calling `.plugin(fn)` on each Schema you create.
  601. *
  602. * @param {Function} fn plugin callback
  603. * @param {Object} [opts] optional options
  604. * @return {Mongoose} this
  605. * @see plugins ./plugins.html
  606. * @api public
  607. */
  608. Mongoose.prototype.plugin = function(fn, opts) {
  609. const _mongoose = this instanceof Mongoose ? this : mongoose;
  610. _mongoose.plugins.push([fn, opts]);
  611. return _mongoose;
  612. };
  613. /**
  614. * The Mongoose module's default connection. Equivalent to `mongoose.connections[0]`, see [`connections`](#mongoose_Mongoose-connections).
  615. *
  616. * ####Example:
  617. *
  618. * const mongoose = require('mongoose');
  619. * mongoose.connect(...);
  620. * mongoose.connection.on('error', cb);
  621. *
  622. * This is the connection used by default for every model created using [mongoose.model](#index_Mongoose-model).
  623. *
  624. * To create a new connection, use [`createConnection()`](#mongoose_Mongoose-createConnection).
  625. *
  626. * @memberOf Mongoose
  627. * @instance
  628. * @property {Connection} connection
  629. * @api public
  630. */
  631. Mongoose.prototype.__defineGetter__('connection', function() {
  632. return this.connections[0];
  633. });
  634. Mongoose.prototype.__defineSetter__('connection', function(v) {
  635. if (v instanceof Connection) {
  636. this.connections[0] = v;
  637. this.models = v.models;
  638. }
  639. });
  640. /**
  641. * An array containing all [connections](connections.html) associated with this
  642. * Mongoose instance. By default, there is 1 connection. Calling
  643. * [`createConnection()`](#mongoose_Mongoose-createConnection) adds a connection
  644. * to this array.
  645. *
  646. * ####Example:
  647. *
  648. * const mongoose = require('mongoose');
  649. * mongoose.connections.length; // 1, just the default connection
  650. * mongoose.connections[0] === mongoose.connection; // true
  651. *
  652. * mongoose.createConnection('mongodb://localhost:27017/test');
  653. * mongoose.connections.length; // 2
  654. *
  655. * @memberOf Mongoose
  656. * @instance
  657. * @property {Array} connections
  658. * @api public
  659. */
  660. Mongoose.prototype.connections;
  661. /*!
  662. * Connection
  663. */
  664. const Connection = driver.get().getConnection();
  665. /*!
  666. * Collection
  667. */
  668. const Collection = driver.get().Collection;
  669. /**
  670. * The Mongoose Aggregate constructor
  671. *
  672. * @method Aggregate
  673. * @api public
  674. */
  675. Mongoose.prototype.Aggregate = Aggregate;
  676. /**
  677. * The Mongoose Collection constructor
  678. *
  679. * @method Collection
  680. * @api public
  681. */
  682. Mongoose.prototype.Collection = Collection;
  683. /**
  684. * The Mongoose [Connection](#connection_Connection) constructor
  685. *
  686. * @memberOf Mongoose
  687. * @instance
  688. * @method Connection
  689. * @api public
  690. */
  691. Mongoose.prototype.Connection = Connection;
  692. /**
  693. * The Mongoose version
  694. *
  695. * #### Example
  696. *
  697. * console.log(mongoose.version); // '5.x.x'
  698. *
  699. * @property version
  700. * @api public
  701. */
  702. Mongoose.prototype.version = pkg.version;
  703. /**
  704. * The Mongoose constructor
  705. *
  706. * The exports of the mongoose module is an instance of this class.
  707. *
  708. * ####Example:
  709. *
  710. * const mongoose = require('mongoose');
  711. * const mongoose2 = new mongoose.Mongoose();
  712. *
  713. * @method Mongoose
  714. * @api public
  715. */
  716. Mongoose.prototype.Mongoose = Mongoose;
  717. /**
  718. * The Mongoose [Schema](#schema_Schema) constructor
  719. *
  720. * ####Example:
  721. *
  722. * const mongoose = require('mongoose');
  723. * const Schema = mongoose.Schema;
  724. * const CatSchema = new Schema(..);
  725. *
  726. * @method Schema
  727. * @api public
  728. */
  729. Mongoose.prototype.Schema = Schema;
  730. /**
  731. * The Mongoose [SchemaType](#schematype_SchemaType) constructor
  732. *
  733. * @method SchemaType
  734. * @api public
  735. */
  736. Mongoose.prototype.SchemaType = SchemaType;
  737. /**
  738. * The various Mongoose SchemaTypes.
  739. *
  740. * ####Note:
  741. *
  742. * _Alias of mongoose.Schema.Types for backwards compatibility._
  743. *
  744. * @property SchemaTypes
  745. * @see Schema.SchemaTypes #schema_Schema.Types
  746. * @api public
  747. */
  748. Mongoose.prototype.SchemaTypes = Schema.Types;
  749. /**
  750. * The Mongoose [VirtualType](#virtualtype_VirtualType) constructor
  751. *
  752. * @method VirtualType
  753. * @api public
  754. */
  755. Mongoose.prototype.VirtualType = VirtualType;
  756. /**
  757. * The various Mongoose Types.
  758. *
  759. * ####Example:
  760. *
  761. * const mongoose = require('mongoose');
  762. * const array = mongoose.Types.Array;
  763. *
  764. * ####Types:
  765. *
  766. * - [Array](/docs/schematypes.html#arrays)
  767. * - [Buffer](/docs/schematypes.html#buffers)
  768. * - [Embedded](/docs/schematypes.html#schemas)
  769. * - [DocumentArray](/docs/api/documentarraypath.html)
  770. * - [Decimal128](/docs/api.html#mongoose_Mongoose-Decimal128)
  771. * - [ObjectId](/docs/schematypes.html#objectids)
  772. * - [Map](/docs/schematypes.html#maps)
  773. * - [Subdocument](/docs/schematypes.html#schemas)
  774. *
  775. * Using this exposed access to the `ObjectId` type, we can construct ids on demand.
  776. *
  777. * const ObjectId = mongoose.Types.ObjectId;
  778. * const id1 = new ObjectId;
  779. *
  780. * @property Types
  781. * @api public
  782. */
  783. Mongoose.prototype.Types = Types;
  784. /**
  785. * The Mongoose [Query](#query_Query) constructor.
  786. *
  787. * @method Query
  788. * @api public
  789. */
  790. Mongoose.prototype.Query = Query;
  791. /**
  792. * The Mongoose [Promise](#promise_Promise) constructor.
  793. *
  794. * @memberOf Mongoose
  795. * @instance
  796. * @property Promise
  797. * @api public
  798. */
  799. Object.defineProperty(Mongoose.prototype, 'Promise', {
  800. get: function() {
  801. return PromiseProvider.get();
  802. },
  803. set: function(lib) {
  804. PromiseProvider.set(lib);
  805. }
  806. });
  807. /**
  808. * Storage layer for mongoose promises
  809. *
  810. * @method PromiseProvider
  811. * @api public
  812. */
  813. Mongoose.prototype.PromiseProvider = PromiseProvider;
  814. /**
  815. * The Mongoose [Model](#model_Model) constructor.
  816. *
  817. * @method Model
  818. * @api public
  819. */
  820. Mongoose.prototype.Model = Model;
  821. /**
  822. * The Mongoose [Document](/api/document.html) constructor.
  823. *
  824. * @method Document
  825. * @api public
  826. */
  827. Mongoose.prototype.Document = Document;
  828. /**
  829. * The Mongoose DocumentProvider constructor. Mongoose users should not have to
  830. * use this directly
  831. *
  832. * @method DocumentProvider
  833. * @api public
  834. */
  835. Mongoose.prototype.DocumentProvider = require('./document_provider');
  836. /**
  837. * The Mongoose ObjectId [SchemaType](/docs/schematypes.html). Used for
  838. * declaring paths in your schema that should be
  839. * [MongoDB ObjectIds](https://docs.mongodb.com/manual/reference/method/ObjectId/).
  840. * Do not use this to create a new ObjectId instance, use `mongoose.Types.ObjectId`
  841. * instead.
  842. *
  843. * ####Example:
  844. *
  845. * const childSchema = new Schema({ parentId: mongoose.ObjectId });
  846. *
  847. * @property ObjectId
  848. * @api public
  849. */
  850. Mongoose.prototype.ObjectId = SchemaTypes.ObjectId;
  851. /**
  852. * Returns true if Mongoose can cast the given value to an ObjectId, or
  853. * false otherwise.
  854. *
  855. * ####Example:
  856. *
  857. * mongoose.isValidObjectId(new mongoose.Types.ObjectId()); // true
  858. * mongoose.isValidObjectId('0123456789ab'); // true
  859. * mongoose.isValidObjectId(6); // false
  860. *
  861. * @method isValidObjectId
  862. * @api public
  863. */
  864. Mongoose.prototype.isValidObjectId = function(v) {
  865. if (v == null) {
  866. return true;
  867. }
  868. const base = this || mongoose;
  869. const ObjectId = base.driver.get().ObjectId;
  870. if (v instanceof ObjectId) {
  871. return true;
  872. }
  873. if (v._id != null) {
  874. if (v._id instanceof ObjectId) {
  875. return true;
  876. }
  877. if (v._id.toString instanceof Function) {
  878. v = v._id.toString();
  879. if (typeof v === 'string' && v.length === 12) {
  880. return true;
  881. }
  882. if (typeof v === 'string' && v.length === 24 && /^[a-f0-9]*$/.test(v)) {
  883. return true;
  884. }
  885. return false;
  886. }
  887. }
  888. if (v.toString instanceof Function) {
  889. v = v.toString();
  890. }
  891. if (typeof v === 'string' && v.length === 12) {
  892. return true;
  893. }
  894. if (typeof v === 'string' && v.length === 24 && /^[a-f0-9]*$/.test(v)) {
  895. return true;
  896. }
  897. return false;
  898. };
  899. /**
  900. * The Mongoose Decimal128 [SchemaType](/docs/schematypes.html). Used for
  901. * declaring paths in your schema that should be
  902. * [128-bit decimal floating points](http://thecodebarbarian.com/a-nodejs-perspective-on-mongodb-34-decimal.html).
  903. * Do not use this to create a new Decimal128 instance, use `mongoose.Types.Decimal128`
  904. * instead.
  905. *
  906. * ####Example:
  907. *
  908. * const vehicleSchema = new Schema({ fuelLevel: mongoose.Decimal128 });
  909. *
  910. * @property Decimal128
  911. * @api public
  912. */
  913. Mongoose.prototype.Decimal128 = SchemaTypes.Decimal128;
  914. /**
  915. * The Mongoose Mixed [SchemaType](/docs/schematypes.html). Used for
  916. * declaring paths in your schema that Mongoose's change tracking, casting,
  917. * and validation should ignore.
  918. *
  919. * ####Example:
  920. *
  921. * const schema = new Schema({ arbitrary: mongoose.Mixed });
  922. *
  923. * @property Mixed
  924. * @api public
  925. */
  926. Mongoose.prototype.Mixed = SchemaTypes.Mixed;
  927. /**
  928. * The Mongoose Date [SchemaType](/docs/schematypes.html).
  929. *
  930. * ####Example:
  931. *
  932. * const schema = new Schema({ test: Date });
  933. * schema.path('test') instanceof mongoose.Date; // true
  934. *
  935. * @property Date
  936. * @api public
  937. */
  938. Mongoose.prototype.Date = SchemaTypes.Date;
  939. /**
  940. * The Mongoose Number [SchemaType](/docs/schematypes.html). Used for
  941. * declaring paths in your schema that Mongoose should cast to numbers.
  942. *
  943. * ####Example:
  944. *
  945. * const schema = new Schema({ num: mongoose.Number });
  946. * // Equivalent to:
  947. * const schema = new Schema({ num: 'number' });
  948. *
  949. * @property Number
  950. * @api public
  951. */
  952. Mongoose.prototype.Number = SchemaTypes.Number;
  953. /**
  954. * The [MongooseError](#error_MongooseError) constructor.
  955. *
  956. * @method Error
  957. * @api public
  958. */
  959. Mongoose.prototype.Error = require('./error/index');
  960. /**
  961. * Mongoose uses this function to get the current time when setting
  962. * [timestamps](/docs/guide.html#timestamps). You may stub out this function
  963. * using a tool like [Sinon](https://www.npmjs.com/package/sinon) for testing.
  964. *
  965. * @method now
  966. * @returns Date the current time
  967. * @api public
  968. */
  969. Mongoose.prototype.now = function now() { return new Date(); };
  970. /**
  971. * The Mongoose CastError constructor
  972. *
  973. * @method CastError
  974. * @param {String} type The name of the type
  975. * @param {Any} value The value that failed to cast
  976. * @param {String} path The path `a.b.c` in the doc where this cast error occurred
  977. * @param {Error} [reason] The original error that was thrown
  978. * @api public
  979. */
  980. Mongoose.prototype.CastError = require('./error/cast');
  981. /**
  982. * The constructor used for schematype options
  983. *
  984. * @method SchemaTypeOptions
  985. * @api public
  986. */
  987. Mongoose.prototype.SchemaTypeOptions = require('./options/SchemaTypeOptions');
  988. /**
  989. * The [node-mongodb-native](https://github.com/mongodb/node-mongodb-native) driver Mongoose uses.
  990. *
  991. * @property mongo
  992. * @api public
  993. */
  994. Mongoose.prototype.mongo = require('mongodb');
  995. /**
  996. * The [mquery](https://github.com/aheckmann/mquery) query builder Mongoose uses.
  997. *
  998. * @property mquery
  999. * @api public
  1000. */
  1001. Mongoose.prototype.mquery = require('mquery');
  1002. /*!
  1003. * ignore
  1004. */
  1005. Mongoose.prototype._promiseOrCallback = function(callback, fn, ee) {
  1006. return promiseOrCallback(callback, fn, ee, this.Promise);
  1007. };
  1008. /*!
  1009. * The exports object is an instance of Mongoose.
  1010. *
  1011. * @api public
  1012. */
  1013. const mongoose = module.exports = exports = new Mongoose({
  1014. [defaultMongooseSymbol]: true
  1015. });