Ohm-Management - Projektarbeit B-ME
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

index.js 28KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956
  1. 'use strict';
  2. /*!
  3. * Module dependencies.
  4. */
  5. if (global.MONGOOSE_DRIVER_PATH) {
  6. require('./driver').set(require(global.MONGOOSE_DRIVER_PATH));
  7. } else {
  8. require('./driver').set(require('./drivers/node-mongodb-native'));
  9. }
  10. const Schema = require('./schema');
  11. const SchemaType = require('./schematype');
  12. const SchemaTypes = require('./schema/index');
  13. const VirtualType = require('./virtualtype');
  14. const STATES = require('./connectionstate');
  15. const Types = require('./types');
  16. const Query = require('./query');
  17. const Model = require('./model');
  18. const Document = require('./document');
  19. const legacyPluralize = require('mongoose-legacy-pluralize');
  20. const utils = require('./utils');
  21. const pkg = require('../package.json');
  22. const removeSubdocs = require('./plugins/removeSubdocs');
  23. const saveSubdocs = require('./plugins/saveSubdocs');
  24. const validateBeforeSave = require('./plugins/validateBeforeSave');
  25. const Aggregate = require('./aggregate');
  26. const PromiseProvider = require('./promise_provider');
  27. const shardingPlugin = require('./plugins/sharding');
  28. const defaultMongooseSymbol = Symbol.for('mongoose:default');
  29. require('./helpers/printJestWarning');
  30. /**
  31. * Mongoose constructor.
  32. *
  33. * The exports object of the `mongoose` module is an instance of this class.
  34. * Most apps will only use this one instance.
  35. *
  36. * @api public
  37. */
  38. function Mongoose(options) {
  39. this.connections = [];
  40. this.models = {};
  41. this.modelSchemas = {};
  42. // default global options
  43. this.options = {
  44. pluralization: true
  45. };
  46. const conn = this.createConnection(); // default connection
  47. conn.models = this.models;
  48. this._pluralize = legacyPluralize;
  49. // If a user creates their own Mongoose instance, give them a separate copy
  50. // of the `Schema` constructor so they get separate custom types. (gh-6933)
  51. if (!options || !options[defaultMongooseSymbol]) {
  52. const _this = this;
  53. this.Schema = function() {
  54. this.base = _this;
  55. return Schema.apply(this, arguments);
  56. };
  57. this.Schema.prototype = Object.create(Schema.prototype);
  58. Object.assign(this.Schema, Schema);
  59. this.Schema.base = this;
  60. this.Schema.Types = Object.assign({}, Schema.Types);
  61. } else {
  62. // Hack to work around babel's strange behavior with
  63. // `import mongoose, { Schema } from 'mongoose'`. Because `Schema` is not
  64. // an own property of a Mongoose global, Schema will be undefined. See gh-5648
  65. for (const key of ['Schema', 'model']) {
  66. this[key] = Mongoose.prototype[key];
  67. }
  68. }
  69. this.Schema.prototype.base = this;
  70. Object.defineProperty(this, 'plugins', {
  71. configurable: false,
  72. enumerable: true,
  73. writable: false,
  74. value: [
  75. [saveSubdocs, { deduplicate: true }],
  76. [validateBeforeSave, { deduplicate: true }],
  77. [shardingPlugin, { deduplicate: true }],
  78. [removeSubdocs, { deduplicate: true }]
  79. ]
  80. });
  81. }
  82. /**
  83. * Expose connection states for user-land
  84. *
  85. * @memberOf Mongoose
  86. * @property STATES
  87. * @api public
  88. */
  89. Mongoose.prototype.STATES = STATES;
  90. /**
  91. * Sets mongoose options
  92. *
  93. * ####Example:
  94. *
  95. * mongoose.set('test', value) // sets the 'test' option to `value`
  96. *
  97. * mongoose.set('debug', true) // enable logging collection methods + arguments to the console
  98. *
  99. * mongoose.set('debug', function(collectionName, methodName, arg1, arg2...) {}); // use custom function to log collection methods + arguments
  100. *
  101. * Currently supported options are:
  102. * - 'debug': prints the operations mongoose sends to MongoDB to the console
  103. * - 'bufferCommands': enable/disable mongoose's buffering mechanism for all connections and models
  104. * - 'useCreateIndex': false by default. Set to `true` to make Mongoose's default index build use `createIndex()` instead of `ensureIndex()` to avoid deprecation warnings from the MongoDB driver.
  105. * - 'useFindAndModify': true by default. Set to `false` to make `findOneAndUpdate()` and `findOneAndRemove()` use native `findOneAndUpdate()` rather than `findAndModify()`.
  106. * - 'useNewUrlParser': false by default. Set to `true` to make all connections set the `useNewUrlParser` option by default
  107. * - 'cloneSchemas': false by default. Set to `true` to `clone()` all schemas before compiling into a model.
  108. * - '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.
  109. * - '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.
  110. * - 'runValidators': false by default. Set to true to enable [update validators](/docs/validation.html#update-validators) for all validators by default.
  111. * - 'toObject': `{ transform: true, flattenDecimals: true }` by default. Overwrites default objects to [`toObject()`](/docs/api.html#document_Document-toObject)
  112. * - '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()`
  113. * - 'strict': true by default, may be `false`, `true`, or `'throw'`. Sets the default strict mode for schemas.
  114. * - '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.
  115. *
  116. * @param {String} key
  117. * @param {String|Function|Boolean} value
  118. * @api public
  119. */
  120. Mongoose.prototype.set = function(key, value) {
  121. if (arguments.length === 1) {
  122. return this.options[key];
  123. }
  124. this.options[key] = value;
  125. if (key === 'objectIdGetter') {
  126. if (value) {
  127. Object.defineProperty(mongoose.Types.ObjectId.prototype, '_id', {
  128. enumerable: false,
  129. configurable: true,
  130. get: function() {
  131. return this;
  132. }
  133. });
  134. } else {
  135. delete mongoose.Types.ObjectId.prototype._id;
  136. }
  137. }
  138. return this;
  139. };
  140. /**
  141. * Gets mongoose options
  142. *
  143. * ####Example:
  144. *
  145. * mongoose.get('test') // returns the 'test' value
  146. *
  147. * @param {String} key
  148. * @method get
  149. * @api public
  150. */
  151. Mongoose.prototype.get = Mongoose.prototype.set;
  152. /**
  153. * Creates a Connection instance.
  154. *
  155. * Each `connection` instance maps to a single database. This method is helpful when mangaging multiple db connections.
  156. *
  157. *
  158. * _Options passed take precedence over options included in connection strings._
  159. *
  160. * ####Example:
  161. *
  162. * // with mongodb:// URI
  163. * db = mongoose.createConnection('mongodb://user:pass@localhost:port/database');
  164. *
  165. * // and options
  166. * var opts = { db: { native_parser: true }}
  167. * db = mongoose.createConnection('mongodb://user:pass@localhost:port/database', opts);
  168. *
  169. * // replica sets
  170. * db = mongoose.createConnection('mongodb://user:pass@localhost:port,anotherhost:port,yetanother:port/database');
  171. *
  172. * // and options
  173. * var opts = { replset: { strategy: 'ping', rs_name: 'testSet' }}
  174. * db = mongoose.createConnection('mongodb://user:pass@localhost:port,anotherhost:port,yetanother:port/database', opts);
  175. *
  176. * // and options
  177. * var opts = { server: { auto_reconnect: false }, user: 'username', pass: 'mypassword' }
  178. * db = mongoose.createConnection('localhost', 'database', port, opts)
  179. *
  180. * // initialize now, connect later
  181. * db = mongoose.createConnection();
  182. * db.openUri('localhost', 'database', port, [opts]);
  183. *
  184. * @param {String} [uri] a mongodb:// URI
  185. * @param {Object} [options] passed down to the [MongoDB driver's `connect()` function](http://mongodb.github.io/node-mongodb-native/3.0/api/MongoClient.html), except for 4 mongoose-specific options explained below.
  186. * @param {String} [options.user] username for authentication, equivalent to `options.auth.user`. Maintained for backwards compatibility.
  187. * @param {String} [options.pass] password for authentication, equivalent to `options.auth.password`. Maintained for backwards compatibility.
  188. * @param {Boolean} [options.autoIndex=true] Mongoose-specific option. Set to false to disable automatic index creation for all models associated with this connection.
  189. * @param {Boolean} [options.bufferCommands=true] Mongoose specific option. Set to false to [disable buffering](http://mongoosejs.com/docs/faq.html#callback_never_executes) on all models associated with this connection.
  190. * @return {Connection} the created Connection object. Connections are thenable, so you can do `await mongoose.createConnection()`
  191. * @api public
  192. */
  193. Mongoose.prototype.createConnection = function(uri, options, callback) {
  194. const conn = new Connection(this);
  195. if (typeof options === 'function') {
  196. callback = options;
  197. options = null;
  198. }
  199. this.connections.push(conn);
  200. if (arguments.length > 0) {
  201. return conn.openUri(uri, options, callback);
  202. }
  203. return conn;
  204. };
  205. /**
  206. * Opens the default mongoose connection.
  207. *
  208. * ####Example:
  209. *
  210. * mongoose.connect('mongodb://user:pass@localhost:port/database');
  211. *
  212. * // replica sets
  213. * var uri = 'mongodb://user:pass@localhost:port,anotherhost:port,yetanother:port/mydatabase';
  214. * mongoose.connect(uri);
  215. *
  216. * // with options
  217. * mongoose.connect(uri, options);
  218. *
  219. * // optional callback that gets fired when initial connection completed
  220. * var uri = 'mongodb://nonexistent.domain:27000';
  221. * mongoose.connect(uri, function(error) {
  222. * // if error is truthy, the initial connection failed.
  223. * })
  224. *
  225. * @param {String} uri(s)
  226. * @param {Object} [options] passed down to the [MongoDB driver's `connect()` function](http://mongodb.github.io/node-mongodb-native/3.0/api/MongoClient.html), except for 4 mongoose-specific options explained below.
  227. * @param {String} [options.dbName] The name of the database we want to use. If not provided, use database name from connection string.
  228. * @param {String} [options.user] username for authentication, equivalent to `options.auth.user`. Maintained for backwards compatibility.
  229. * @param {String} [options.pass] password for authentication, equivalent to `options.auth.password`. Maintained for backwards compatibility.
  230. * @param {Boolean} [options.autoIndex=true] Mongoose-specific option. Set to false to disable automatic index creation for all models associated with this connection.
  231. * @param {Boolean} [options.bufferCommands=true] Mongoose specific option. Set to false to [disable buffering](http://mongoosejs.com/docs/faq.html#callback_never_executes) on all models associated with this connection.
  232. * @param {Boolean} [options.useCreateIndex=true] Mongoose-specific option. If `true`, this connection will use [`createIndex()` instead of `ensureIndex()`](/docs/deprecations.html#-ensureindex-) for automatic index builds via [`Model.init()`](/docs/api.html#model_Model.init).
  233. * @param {Boolean} [options.useFindAndModify=true] True by default. Set to `false` to make `findOneAndUpdate()` and `findOneAndRemove()` use native `findOneAndUpdate()` rather than `findAndModify()`.
  234. * @param {Boolean} [options.useNewUrlParser=false] False by default. Set to `true` to make all connections set the `useNewUrlParser` option by default.
  235. * @param {Function} [callback]
  236. * @see Mongoose#createConnection #index_Mongoose-createConnection
  237. * @api public
  238. * @return {Promise} resolves to `this` if connection succeeded
  239. */
  240. Mongoose.prototype.connect = function() {
  241. const _mongoose = this instanceof Mongoose ? this : mongoose;
  242. const conn = _mongoose.connection;
  243. return conn.openUri(arguments[0], arguments[1], arguments[2]).then(() => _mongoose);
  244. };
  245. /**
  246. * Runs `.close()` on all connections in parallel.
  247. *
  248. * @param {Function} [callback] called after all connection close, or when first error occurred.
  249. * @return {Promise} resolves when all connections are closed, or rejects with the first error that occurred.
  250. * @api public
  251. */
  252. Mongoose.prototype.disconnect = function(callback) {
  253. return utils.promiseOrCallback(callback, cb => {
  254. let remaining = this.connections.length;
  255. if (remaining <= 0) {
  256. return cb(null);
  257. }
  258. this.connections.forEach(conn => {
  259. conn.close(function(error) {
  260. if (error) {
  261. return cb(error);
  262. }
  263. if (!--remaining) {
  264. cb(null);
  265. }
  266. });
  267. });
  268. });
  269. };
  270. /**
  271. * _Requires MongoDB >= 3.6.0._ Starts a [MongoDB session](https://docs.mongodb.com/manual/release-notes/3.6/#client-sessions)
  272. * for benefits like causal consistency, [retryable writes](https://docs.mongodb.com/manual/core/retryable-writes/),
  273. * and [transactions](http://thecodebarbarian.com/a-node-js-perspective-on-mongodb-4-transactions.html).
  274. *
  275. * Calling `mongoose.startSession()` is equivalent to calling `mongoose.connection.startSession()`.
  276. * Sessions are scoped to a connection, so calling `mongoose.startSession()`
  277. * starts a session on the [default mongoose connection](/docs/api.html#mongoose_Mongoose-connection).
  278. *
  279. * @param {Object} [options] see the [mongodb driver options](http://mongodb.github.io/node-mongodb-native/3.0/api/MongoClient.html#startSession)
  280. * @param {Boolean} [options.causalConsistency=true] set to false to disable causal consistency
  281. * @param {Function} [callback]
  282. * @return {Promise<ClientSession>} promise that resolves to a MongoDB driver `ClientSession`
  283. * @api public
  284. */
  285. Mongoose.prototype.startSession = function() {
  286. return this.connection.startSession.apply(this.connection, arguments);
  287. };
  288. /**
  289. * Getter/setter around function for pluralizing collection names.
  290. *
  291. * @param {Function|null} [fn] overwrites the function used to pluralize collection names
  292. * @return {Function|null} the current function used to pluralize collection names, defaults to the legacy function from `mongoose-legacy-pluralize`.
  293. * @api public
  294. */
  295. Mongoose.prototype.pluralize = function(fn) {
  296. if (arguments.length > 0) {
  297. this._pluralize = fn;
  298. }
  299. return this._pluralize;
  300. };
  301. /**
  302. * Defines a model or retrieves it.
  303. *
  304. * Models defined on the `mongoose` instance are available to all connection
  305. * created by the same `mongoose` instance.
  306. *
  307. * If you call `mongoose.model()` with twice the same name but a different schema,
  308. * you will get an `OverwriteModelError`. If you call `mongoose.model()` with
  309. * the same name and same schema, you'll get the same schema back.
  310. *
  311. * ####Example:
  312. *
  313. * var mongoose = require('mongoose');
  314. *
  315. * // define an Actor model with this mongoose instance
  316. * const Schema = new Schema({ name: String });
  317. * mongoose.model('Actor', schema);
  318. *
  319. * // create a new connection
  320. * var conn = mongoose.createConnection(..);
  321. *
  322. * // create Actor model
  323. * var Actor = conn.model('Actor', schema);
  324. * conn.model('Actor') === Actor; // true
  325. * conn.model('Actor', schema) === Actor; // true, same schema
  326. * conn.model('Actor', schema, 'actors') === Actor; // true, same schema and collection name
  327. *
  328. * // This throws an `OverwriteModelError` because the schema is different.
  329. * conn.model('Actor', new Schema({ name: String }));
  330. *
  331. * _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._
  332. *
  333. * ####Example:
  334. *
  335. * var schema = new Schema({ name: String }, { collection: 'actor' });
  336. *
  337. * // or
  338. *
  339. * schema.set('collection', 'actor');
  340. *
  341. * // or
  342. *
  343. * var collectionName = 'actor'
  344. * var M = mongoose.model('Actor', schema, collectionName)
  345. *
  346. * @param {String|Function} name model name or class extending Model
  347. * @param {Schema} [schema] the schema to use.
  348. * @param {String} [collection] name (optional, inferred from model name)
  349. * @param {Boolean} [skipInit] whether to skip initialization (defaults to false)
  350. * @return {Model} The model associated with `name`. Mongoose will create the model if it doesn't already exist.
  351. * @api public
  352. */
  353. Mongoose.prototype.model = function(name, schema, collection, skipInit) {
  354. const _mongoose = this instanceof Mongoose ? this : mongoose;
  355. let model;
  356. if (typeof name === 'function') {
  357. model = name;
  358. name = model.name;
  359. if (!(model.prototype instanceof Model)) {
  360. throw new _mongoose.Error('The provided class ' + name + ' must extend Model');
  361. }
  362. }
  363. if (typeof schema === 'string') {
  364. collection = schema;
  365. schema = false;
  366. }
  367. if (utils.isObject(schema) && !(schema.instanceOfSchema)) {
  368. schema = new Schema(schema);
  369. }
  370. if (schema && !schema.instanceOfSchema) {
  371. throw new Error('The 2nd parameter to `mongoose.model()` should be a ' +
  372. 'schema or a POJO');
  373. }
  374. if (typeof collection === 'boolean') {
  375. skipInit = collection;
  376. collection = null;
  377. }
  378. // handle internal options from connection.model()
  379. let options;
  380. if (skipInit && utils.isObject(skipInit)) {
  381. options = skipInit;
  382. skipInit = true;
  383. } else {
  384. options = {};
  385. }
  386. // look up schema for the collection.
  387. if (!_mongoose.modelSchemas[name]) {
  388. if (schema) {
  389. // cache it so we only apply plugins once
  390. _mongoose.modelSchemas[name] = schema;
  391. } else {
  392. throw new mongoose.Error.MissingSchemaError(name);
  393. }
  394. }
  395. const originalSchema = schema;
  396. if (schema) {
  397. if (_mongoose.get('cloneSchemas')) {
  398. schema = schema.clone();
  399. }
  400. _mongoose._applyPlugins(schema);
  401. }
  402. let sub;
  403. // connection.model() may be passing a different schema for
  404. // an existing model name. in this case don't read from cache.
  405. if (_mongoose.models[name] && options.cache !== false) {
  406. if (originalSchema &&
  407. originalSchema.instanceOfSchema &&
  408. originalSchema !== _mongoose.models[name].schema) {
  409. throw new _mongoose.Error.OverwriteModelError(name);
  410. }
  411. if (collection && collection !== _mongoose.models[name].collection.name) {
  412. // subclass current model with alternate collection
  413. model = _mongoose.models[name];
  414. schema = model.prototype.schema;
  415. sub = model.__subclass(_mongoose.connection, schema, collection);
  416. // do not cache the sub model
  417. return sub;
  418. }
  419. return _mongoose.models[name];
  420. }
  421. // ensure a schema exists
  422. if (!schema) {
  423. schema = this.modelSchemas[name];
  424. if (!schema) {
  425. throw new mongoose.Error.MissingSchemaError(name);
  426. }
  427. }
  428. // Apply relevant "global" options to the schema
  429. if (!('pluralization' in schema.options)) {
  430. schema.options.pluralization = _mongoose.options.pluralization;
  431. }
  432. if (!collection) {
  433. collection = schema.get('collection') ||
  434. utils.toCollectionName(name, _mongoose.pluralize());
  435. }
  436. const connection = options.connection || _mongoose.connection;
  437. model = _mongoose.Model.compile(model || name, schema, collection, connection, _mongoose);
  438. if (!skipInit) {
  439. // Errors handled internally, so safe to ignore error
  440. model.init(function $modelInitNoop() {});
  441. }
  442. if (options.cache === false) {
  443. return model;
  444. }
  445. _mongoose.models[name] = model;
  446. return _mongoose.models[name];
  447. };
  448. /**
  449. * Removes the model named `name` from the default connection, if it exists.
  450. * You can use this function to clean up any models you created in your tests to
  451. * prevent OverwriteModelErrors.
  452. *
  453. * Equivalent to `mongoose.connection.deleteModel(name)`.
  454. *
  455. * ####Example:
  456. *
  457. * mongoose.model('User', new Schema({ name: String }));
  458. * console.log(mongoose.model('User')); // Model object
  459. * mongoose.deleteModel('User');
  460. * console.log(mongoose.model('User')); // undefined
  461. *
  462. * // Usually useful in a Mocha `afterEach()` hook
  463. * afterEach(function() {
  464. * mongoose.deleteModel(/.+/); // Delete every model
  465. * });
  466. *
  467. * @api public
  468. * @param {String|RegExp} name if string, the name of the model to remove. If regexp, removes all models whose name matches the regexp.
  469. * @return {Mongoose} this
  470. */
  471. Mongoose.prototype.deleteModel = function(name) {
  472. this.connection.deleteModel(name);
  473. return this;
  474. };
  475. /**
  476. * Returns an array of model names created on this instance of Mongoose.
  477. *
  478. * ####Note:
  479. *
  480. * _Does not include names of models created using `connection.model()`._
  481. *
  482. * @api public
  483. * @return {Array}
  484. */
  485. Mongoose.prototype.modelNames = function() {
  486. const names = Object.keys(this.models);
  487. return names;
  488. };
  489. /**
  490. * Applies global plugins to `schema`.
  491. *
  492. * @param {Schema} schema
  493. * @api private
  494. */
  495. Mongoose.prototype._applyPlugins = function(schema, options) {
  496. if (schema.$globalPluginsApplied) {
  497. return;
  498. }
  499. let i;
  500. let len;
  501. if (!options || !options.skipTopLevel) {
  502. for (i = 0, len = this.plugins.length; i < len; ++i) {
  503. schema.plugin(this.plugins[i][0], this.plugins[i][1]);
  504. }
  505. schema.$globalPluginsApplied = true;
  506. }
  507. for (i = 0, len = schema.childSchemas.length; i < len; ++i) {
  508. this._applyPlugins(schema.childSchemas[i].schema);
  509. }
  510. };
  511. /**
  512. * Declares a global plugin executed on all Schemas.
  513. *
  514. * Equivalent to calling `.plugin(fn)` on each Schema you create.
  515. *
  516. * @param {Function} fn plugin callback
  517. * @param {Object} [opts] optional options
  518. * @return {Mongoose} this
  519. * @see plugins ./plugins.html
  520. * @api public
  521. */
  522. Mongoose.prototype.plugin = function(fn, opts) {
  523. this.plugins.push([fn, opts]);
  524. return this;
  525. };
  526. /**
  527. * The default connection of the mongoose module.
  528. *
  529. * ####Example:
  530. *
  531. * var mongoose = require('mongoose');
  532. * mongoose.connect(...);
  533. * mongoose.connection.on('error', cb);
  534. *
  535. * This is the connection used by default for every model created using [mongoose.model](#index_Mongoose-model).
  536. *
  537. * @memberOf Mongoose
  538. * @instance
  539. * @property connection
  540. * @return {Connection}
  541. * @api public
  542. */
  543. Mongoose.prototype.__defineGetter__('connection', function() {
  544. return this.connections[0];
  545. });
  546. Mongoose.prototype.__defineSetter__('connection', function(v) {
  547. if (v instanceof Connection) {
  548. this.connections[0] = v;
  549. this.models = v.models;
  550. }
  551. });
  552. /*!
  553. * Driver dependent APIs
  554. */
  555. const driver = global.MONGOOSE_DRIVER_PATH || './drivers/node-mongodb-native';
  556. /*!
  557. * Connection
  558. */
  559. const Connection = require(driver + '/connection');
  560. /*!
  561. * Collection
  562. */
  563. const Collection = require(driver + '/collection');
  564. /**
  565. * The Mongoose Aggregate constructor
  566. *
  567. * @method Aggregate
  568. * @api public
  569. */
  570. Mongoose.prototype.Aggregate = Aggregate;
  571. /**
  572. * The Mongoose Collection constructor
  573. *
  574. * @method Collection
  575. * @api public
  576. */
  577. Mongoose.prototype.Collection = Collection;
  578. /**
  579. * The Mongoose [Connection](#connection_Connection) constructor
  580. *
  581. * @memberOf Mongoose
  582. * @instance
  583. * @method Connection
  584. * @api public
  585. */
  586. Mongoose.prototype.Connection = Connection;
  587. /**
  588. * The Mongoose version
  589. *
  590. * #### Example
  591. *
  592. * console.log(mongoose.version); // '5.x.x'
  593. *
  594. * @property version
  595. * @api public
  596. */
  597. Mongoose.prototype.version = pkg.version;
  598. /**
  599. * The Mongoose constructor
  600. *
  601. * The exports of the mongoose module is an instance of this class.
  602. *
  603. * ####Example:
  604. *
  605. * var mongoose = require('mongoose');
  606. * var mongoose2 = new mongoose.Mongoose();
  607. *
  608. * @method Mongoose
  609. * @api public
  610. */
  611. Mongoose.prototype.Mongoose = Mongoose;
  612. /**
  613. * The Mongoose [Schema](#schema_Schema) constructor
  614. *
  615. * ####Example:
  616. *
  617. * var mongoose = require('mongoose');
  618. * var Schema = mongoose.Schema;
  619. * var CatSchema = new Schema(..);
  620. *
  621. * @method Schema
  622. * @api public
  623. */
  624. Mongoose.prototype.Schema = Schema;
  625. /**
  626. * The Mongoose [SchemaType](#schematype_SchemaType) constructor
  627. *
  628. * @method SchemaType
  629. * @api public
  630. */
  631. Mongoose.prototype.SchemaType = SchemaType;
  632. /**
  633. * The various Mongoose SchemaTypes.
  634. *
  635. * ####Note:
  636. *
  637. * _Alias of mongoose.Schema.Types for backwards compatibility._
  638. *
  639. * @property SchemaTypes
  640. * @see Schema.SchemaTypes #schema_Schema.Types
  641. * @api public
  642. */
  643. Mongoose.prototype.SchemaTypes = Schema.Types;
  644. /**
  645. * The Mongoose [VirtualType](#virtualtype_VirtualType) constructor
  646. *
  647. * @method VirtualType
  648. * @api public
  649. */
  650. Mongoose.prototype.VirtualType = VirtualType;
  651. /**
  652. * The various Mongoose Types.
  653. *
  654. * ####Example:
  655. *
  656. * var mongoose = require('mongoose');
  657. * var array = mongoose.Types.Array;
  658. *
  659. * ####Types:
  660. *
  661. * - [ObjectId](#types-objectid-js)
  662. * - [Buffer](#types-buffer-js)
  663. * - [SubDocument](#types-embedded-js)
  664. * - [Array](#types-array-js)
  665. * - [DocumentArray](#types-documentarray-js)
  666. *
  667. * Using this exposed access to the `ObjectId` type, we can construct ids on demand.
  668. *
  669. * var ObjectId = mongoose.Types.ObjectId;
  670. * var id1 = new ObjectId;
  671. *
  672. * @property Types
  673. * @api public
  674. */
  675. Mongoose.prototype.Types = Types;
  676. /**
  677. * The Mongoose [Query](#query_Query) constructor.
  678. *
  679. * @method Query
  680. * @api public
  681. */
  682. Mongoose.prototype.Query = Query;
  683. /**
  684. * The Mongoose [Promise](#promise_Promise) constructor.
  685. *
  686. * @memberOf Mongoose
  687. * @instance
  688. * @property Promise
  689. * @api public
  690. */
  691. Object.defineProperty(Mongoose.prototype, 'Promise', {
  692. get: function() {
  693. return PromiseProvider.get();
  694. },
  695. set: function(lib) {
  696. PromiseProvider.set(lib);
  697. }
  698. });
  699. /**
  700. * Storage layer for mongoose promises
  701. *
  702. * @method PromiseProvider
  703. * @api public
  704. */
  705. Mongoose.prototype.PromiseProvider = PromiseProvider;
  706. /**
  707. * The Mongoose [Model](#model_Model) constructor.
  708. *
  709. * @method Model
  710. * @api public
  711. */
  712. Mongoose.prototype.Model = Model;
  713. /**
  714. * The Mongoose [Document](#document-js) constructor.
  715. *
  716. * @method Document
  717. * @api public
  718. */
  719. Mongoose.prototype.Document = Document;
  720. /**
  721. * The Mongoose DocumentProvider constructor. Mongoose users should not have to
  722. * use this directly
  723. *
  724. * @method DocumentProvider
  725. * @api public
  726. */
  727. Mongoose.prototype.DocumentProvider = require('./document_provider');
  728. /**
  729. * The Mongoose ObjectId [SchemaType](/docs/schematypes.html). Used for
  730. * declaring paths in your schema that should be
  731. * [MongoDB ObjectIds](https://docs.mongodb.com/manual/reference/method/ObjectId/).
  732. * Do not use this to create a new ObjectId instance, use `mongoose.Types.ObjectId`
  733. * instead.
  734. *
  735. * ####Example:
  736. *
  737. * const childSchema = new Schema({ parentId: mongoose.ObjectId });
  738. *
  739. * @property ObjectId
  740. * @api public
  741. */
  742. Mongoose.prototype.ObjectId = SchemaTypes.ObjectId;
  743. /**
  744. * The Mongoose Decimal128 [SchemaType](/docs/schematypes.html). Used for
  745. * declaring paths in your schema that should be
  746. * [128-bit decimal floating points](http://thecodebarbarian.com/a-nodejs-perspective-on-mongodb-34-decimal.html).
  747. * Do not use this to create a new Decimal128 instance, use `mongoose.Types.Decimal128`
  748. * instead.
  749. *
  750. * ####Example:
  751. *
  752. * const vehicleSchema = new Schema({ fuelLevel: mongoose.Decimal128 });
  753. *
  754. * @property Decimal128
  755. * @api public
  756. */
  757. Mongoose.prototype.Decimal128 = SchemaTypes.Decimal128;
  758. /**
  759. * The Mongoose Mixed [SchemaType](/docs/schematypes.html). Used for
  760. * declaring paths in your schema that Mongoose's change tracking, casting,
  761. * and validation should ignore.
  762. *
  763. * ####Example:
  764. *
  765. * const schema = new Schema({ arbitrary: mongoose.Mixed });
  766. *
  767. * @property Mixed
  768. * @api public
  769. */
  770. Mongoose.prototype.Mixed = SchemaTypes.Mixed;
  771. /**
  772. * The Mongoose Number [SchemaType](/docs/schematypes.html). Used for
  773. * declaring paths in your schema that Mongoose should cast to numbers.
  774. *
  775. * ####Example:
  776. *
  777. * const schema = new Schema({ num: mongoose.Number });
  778. * // Equivalent to:
  779. * const schema = new Schema({ num: 'number' });
  780. *
  781. * @property Number
  782. * @api public
  783. */
  784. Mongoose.prototype.Number = SchemaTypes.Number;
  785. /**
  786. * The [MongooseError](#error_MongooseError) constructor.
  787. *
  788. * @method Error
  789. * @api public
  790. */
  791. Mongoose.prototype.Error = require('./error');
  792. /**
  793. * Mongoose uses this function to get the current time when setting
  794. * [timestamps](/docs/guide.html#timestamps). You may stub out this function
  795. * using a tool like [Sinon](https://www.npmjs.com/package/sinon) for testing.
  796. *
  797. * @method now
  798. * @returns Date the current time
  799. * @api public
  800. */
  801. Mongoose.prototype.now = function now() { return new Date(); };
  802. /**
  803. * The Mongoose CastError constructor
  804. *
  805. * @method CastError
  806. * @param {String} type The name of the type
  807. * @param {Any} value The value that failed to cast
  808. * @param {String} path The path `a.b.c` in the doc where this cast error occurred
  809. * @param {Error} [reason] The original error that was thrown
  810. * @api public
  811. */
  812. Mongoose.prototype.CastError = require('./error/cast');
  813. /**
  814. * The [node-mongodb-native](https://github.com/mongodb/node-mongodb-native) driver Mongoose uses.
  815. *
  816. * @property mongo
  817. * @api public
  818. */
  819. Mongoose.prototype.mongo = require('mongodb');
  820. /**
  821. * The [mquery](https://github.com/aheckmann/mquery) query builder Mongoose uses.
  822. *
  823. * @property mquery
  824. * @api public
  825. */
  826. Mongoose.prototype.mquery = require('mquery');
  827. /*!
  828. * The exports object is an instance of Mongoose.
  829. *
  830. * @api public
  831. */
  832. const mongoose = module.exports = exports = new Mongoose({
  833. [defaultMongooseSymbol]: true
  834. });