index.js 46 KB

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