@datanimbus/mongoose 6.13.10

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