mongoose.js 53 KB

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