@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
@@ -0,0 +1,1574 @@
1
+ 'use strict';
2
+
3
+ /*!
4
+ * Module dependencies.
5
+ */
6
+
7
+ const ChangeStream = require('./cursor/ChangeStream');
8
+ const EventEmitter = require('events').EventEmitter;
9
+ const Schema = require('./schema');
10
+ const STATES = require('./connectionstate');
11
+ const MongooseError = require('./error/index');
12
+ const DisconnectedError = require('./error/disconnected');
13
+ const SyncIndexesError = require('./error/syncIndexes');
14
+ const PromiseProvider = require('./promise_provider');
15
+ const ServerSelectionError = require('./error/serverSelection');
16
+ const applyPlugins = require('./helpers/schema/applyPlugins');
17
+ const driver = require('./driver');
18
+ const promiseOrCallback = require('./helpers/promiseOrCallback');
19
+ const get = require('./helpers/get');
20
+ const immediate = require('./helpers/immediate');
21
+ const mongodb = require('mongodb');
22
+ const pkg = require('../package.json');
23
+ const utils = require('./utils');
24
+ const processConnectionOptions = require('./helpers/processConnectionOptions');
25
+
26
+ const arrayAtomicsSymbol = require('./helpers/symbols').arrayAtomicsSymbol;
27
+ const sessionNewDocuments = require('./helpers/symbols').sessionNewDocuments;
28
+
29
+ /**
30
+ * A list of authentication mechanisms that don't require a password for authentication.
31
+ * This is used by the authMechanismDoesNotRequirePassword method.
32
+ *
33
+ * @api private
34
+ */
35
+ const noPasswordAuthMechanisms = [
36
+ 'MONGODB-X509'
37
+ ];
38
+
39
+ /**
40
+ * Connection constructor
41
+ *
42
+ * For practical reasons, a Connection equals a Db.
43
+ *
44
+ * @param {Mongoose} base a mongoose instance
45
+ * @inherits NodeJS EventEmitter https://nodejs.org/api/events.html#class-eventemitter
46
+ * @event `connecting`: Emitted when `connection.openUri()` is executed on this connection.
47
+ * @event `connected`: Emitted when this connection successfully connects to the db. May be emitted _multiple_ times in `reconnected` scenarios.
48
+ * @event `open`: Emitted after we `connected` and `onOpen` is executed on all of this connection's models.
49
+ * @event `disconnecting`: Emitted when `connection.close()` was executed.
50
+ * @event `disconnected`: Emitted after getting disconnected from the db.
51
+ * @event `close`: Emitted after we `disconnected` and `onClose` executed on all of this connection's models.
52
+ * @event `reconnected`: Emitted after we `connected` and subsequently `disconnected`, followed by successfully another successful connection.
53
+ * @event `error`: Emitted when an error occurs on this connection.
54
+ * @event `fullsetup`: Emitted after the driver has connected to primary and all secondaries if specified in the connection string.
55
+ * @api public
56
+ */
57
+
58
+ function Connection(base) {
59
+ this.base = base;
60
+ this.collections = {};
61
+ this.models = {};
62
+ this.config = {};
63
+ this.replica = false;
64
+ this.options = null;
65
+ this.otherDbs = []; // FIXME: To be replaced with relatedDbs
66
+ this.relatedDbs = {}; // Hashmap of other dbs that share underlying connection
67
+ this.states = STATES;
68
+ this._readyState = STATES.disconnected;
69
+ this._closeCalled = false;
70
+ this._hasOpened = false;
71
+ this.plugins = [];
72
+ if (typeof base === 'undefined' || !base.connections.length) {
73
+ this.id = 0;
74
+ } else {
75
+ this.id = base.nextConnectionId;
76
+ }
77
+ this._queue = [];
78
+ }
79
+
80
+ /*!
81
+ * Inherit from EventEmitter
82
+ */
83
+
84
+ Object.setPrototypeOf(Connection.prototype, EventEmitter.prototype);
85
+
86
+ /**
87
+ * Connection ready state
88
+ *
89
+ * - 0 = disconnected
90
+ * - 1 = connected
91
+ * - 2 = connecting
92
+ * - 3 = disconnecting
93
+ *
94
+ * Each state change emits its associated event name.
95
+ *
96
+ * #### Example:
97
+ *
98
+ * conn.on('connected', callback);
99
+ * conn.on('disconnected', callback);
100
+ *
101
+ * @property readyState
102
+ * @memberOf Connection
103
+ * @instance
104
+ * @api public
105
+ */
106
+
107
+ Object.defineProperty(Connection.prototype, 'readyState', {
108
+ get: function() {
109
+ return this._readyState;
110
+ },
111
+ set: function(val) {
112
+ if (!(val in STATES)) {
113
+ throw new Error('Invalid connection state: ' + val);
114
+ }
115
+
116
+ if (this._readyState !== val) {
117
+ this._readyState = val;
118
+ // [legacy] loop over the otherDbs on this connection and change their state
119
+ for (const db of this.otherDbs) {
120
+ db.readyState = val;
121
+ }
122
+
123
+ if (STATES.connected === val) {
124
+ this._hasOpened = true;
125
+ }
126
+
127
+ this.emit(STATES[val]);
128
+ }
129
+ }
130
+ });
131
+
132
+ /**
133
+ * Gets the value of the option `key`. Equivalent to `conn.options[key]`
134
+ *
135
+ * #### Example:
136
+ *
137
+ * conn.get('test'); // returns the 'test' value
138
+ *
139
+ * @param {String} key
140
+ * @method get
141
+ * @api public
142
+ */
143
+
144
+ Connection.prototype.get = function(key) {
145
+ if (this.config.hasOwnProperty(key)) {
146
+ return this.config[key];
147
+ }
148
+
149
+ return get(this.options, key);
150
+ };
151
+
152
+ /**
153
+ * Sets the value of the option `key`. Equivalent to `conn.options[key] = val`
154
+ *
155
+ * Supported options include:
156
+ *
157
+ * - `maxTimeMS`: Set [`maxTimeMS`](/docs/api/query.html#query_Query-maxTimeMS) for all queries on this connection.
158
+ * - 'debug': If `true`, prints the operations mongoose sends to MongoDB to the console. If a writable stream is passed, it will log to that stream, without colorization. If a callback function is passed, it will receive the collection name, the method name, then all arugments passed to the method. For example, if you wanted to replicate the default logging, you could output from the callback `Mongoose: ${collectionName}.${methodName}(${methodArgs.join(', ')})`.
159
+ *
160
+ * #### Example:
161
+ *
162
+ * conn.set('test', 'foo');
163
+ * conn.get('test'); // 'foo'
164
+ * conn.options.test; // 'foo'
165
+ *
166
+ * @param {String} key
167
+ * @param {Any} val
168
+ * @method set
169
+ * @api public
170
+ */
171
+
172
+ Connection.prototype.set = function(key, val) {
173
+ if (this.config.hasOwnProperty(key)) {
174
+ this.config[key] = val;
175
+ return val;
176
+ }
177
+
178
+ this.options = this.options || {};
179
+ this.options[key] = val;
180
+ return val;
181
+ };
182
+
183
+ /**
184
+ * A hash of the collections associated with this connection
185
+ *
186
+ * @property collections
187
+ * @memberOf Connection
188
+ * @instance
189
+ * @api public
190
+ */
191
+
192
+ Connection.prototype.collections;
193
+
194
+ /**
195
+ * The name of the database this connection points to.
196
+ *
197
+ * #### Example:
198
+ *
199
+ * mongoose.createConnection('mongodb://127.0.0.1:27017/mydb').name; // "mydb"
200
+ *
201
+ * @property name
202
+ * @memberOf Connection
203
+ * @instance
204
+ * @api public
205
+ */
206
+
207
+ Connection.prototype.name;
208
+
209
+ /**
210
+ * A [POJO](https://masteringjs.io/tutorials/fundamentals/pojo) containing
211
+ * a map from model names to models. Contains all models that have been
212
+ * added to this connection using [`Connection#model()`](/docs/api/connection.html#connection_Connection-model).
213
+ *
214
+ * #### Example:
215
+ *
216
+ * const conn = mongoose.createConnection();
217
+ * const Test = conn.model('Test', mongoose.Schema({ name: String }));
218
+ *
219
+ * Object.keys(conn.models).length; // 1
220
+ * conn.models.Test === Test; // true
221
+ *
222
+ * @property models
223
+ * @memberOf Connection
224
+ * @instance
225
+ * @api public
226
+ */
227
+
228
+ Connection.prototype.models;
229
+
230
+ /**
231
+ * A number identifier for this connection. Used for debugging when
232
+ * you have [multiple connections](/docs/connections.html#multiple_connections).
233
+ *
234
+ * #### Example:
235
+ *
236
+ * // The default connection has `id = 0`
237
+ * mongoose.connection.id; // 0
238
+ *
239
+ * // If you create a new connection, Mongoose increments id
240
+ * const conn = mongoose.createConnection();
241
+ * conn.id; // 1
242
+ *
243
+ * @property id
244
+ * @memberOf Connection
245
+ * @instance
246
+ * @api public
247
+ */
248
+
249
+ Connection.prototype.id;
250
+
251
+ /**
252
+ * The plugins that will be applied to all models created on this connection.
253
+ *
254
+ * #### Example:
255
+ *
256
+ * const db = mongoose.createConnection('mongodb://127.0.0.1:27017/mydb');
257
+ * db.plugin(() => console.log('Applied'));
258
+ * db.plugins.length; // 1
259
+ *
260
+ * db.model('Test', new Schema({})); // Prints "Applied"
261
+ *
262
+ * @property plugins
263
+ * @memberOf Connection
264
+ * @instance
265
+ * @api public
266
+ */
267
+
268
+ Object.defineProperty(Connection.prototype, 'plugins', {
269
+ configurable: false,
270
+ enumerable: true,
271
+ writable: true
272
+ });
273
+
274
+ /**
275
+ * The host name portion of the URI. If multiple hosts, such as a replica set,
276
+ * this will contain the first host name in the URI
277
+ *
278
+ * #### Example:
279
+ *
280
+ * mongoose.createConnection('mongodb://127.0.0.1:27017/mydb').host; // "127.0.0.1"
281
+ *
282
+ * @property host
283
+ * @memberOf Connection
284
+ * @instance
285
+ * @api public
286
+ */
287
+
288
+ Object.defineProperty(Connection.prototype, 'host', {
289
+ configurable: true,
290
+ enumerable: true,
291
+ writable: true
292
+ });
293
+
294
+ /**
295
+ * The port portion of the URI. If multiple hosts, such as a replica set,
296
+ * this will contain the port from the first host name in the URI.
297
+ *
298
+ * #### Example:
299
+ *
300
+ * mongoose.createConnection('mongodb://127.0.0.1:27017/mydb').port; // 27017
301
+ *
302
+ * @property port
303
+ * @memberOf Connection
304
+ * @instance
305
+ * @api public
306
+ */
307
+
308
+ Object.defineProperty(Connection.prototype, 'port', {
309
+ configurable: true,
310
+ enumerable: true,
311
+ writable: true
312
+ });
313
+
314
+ /**
315
+ * The username specified in the URI
316
+ *
317
+ * #### Example:
318
+ *
319
+ * mongoose.createConnection('mongodb://val:psw@127.0.0.1:27017/mydb').user; // "val"
320
+ *
321
+ * @property user
322
+ * @memberOf Connection
323
+ * @instance
324
+ * @api public
325
+ */
326
+
327
+ Object.defineProperty(Connection.prototype, 'user', {
328
+ configurable: true,
329
+ enumerable: true,
330
+ writable: true
331
+ });
332
+
333
+ /**
334
+ * The password specified in the URI
335
+ *
336
+ * #### Example:
337
+ *
338
+ * mongoose.createConnection('mongodb://val:psw@127.0.0.1:27017/mydb').pass; // "psw"
339
+ *
340
+ * @property pass
341
+ * @memberOf Connection
342
+ * @instance
343
+ * @api public
344
+ */
345
+
346
+ Object.defineProperty(Connection.prototype, 'pass', {
347
+ configurable: true,
348
+ enumerable: true,
349
+ writable: true
350
+ });
351
+
352
+ /**
353
+ * The mongodb.Db instance, set when the connection is opened
354
+ *
355
+ * @property db
356
+ * @memberOf Connection
357
+ * @instance
358
+ * @api public
359
+ */
360
+
361
+ Connection.prototype.db;
362
+
363
+ /**
364
+ * The MongoClient instance this connection uses to talk to MongoDB. Mongoose automatically sets this property
365
+ * when the connection is opened.
366
+ *
367
+ * @property client
368
+ * @memberOf Connection
369
+ * @instance
370
+ * @api public
371
+ */
372
+
373
+ Connection.prototype.client;
374
+
375
+ /**
376
+ * A hash of the global options that are associated with this connection
377
+ *
378
+ * @property config
379
+ * @memberOf Connection
380
+ * @instance
381
+ * @api public
382
+ */
383
+
384
+ Connection.prototype.config;
385
+
386
+ /**
387
+ * Helper for `createCollection()`. Will explicitly create the given collection
388
+ * with specified options. Used to create [capped collections](https://www.mongodb.com/docs/manual/core/capped-collections/)
389
+ * and [views](https://www.mongodb.com/docs/manual/core/views/) from mongoose.
390
+ *
391
+ * Options are passed down without modification to the [MongoDB driver's `createCollection()` function](https://mongodb.github.io/node-mongodb-native/4.9/classes/Db.html#createCollection)
392
+ *
393
+ * @method createCollection
394
+ * @param {string} collection The collection to create
395
+ * @param {Object} [options] see [MongoDB driver docs](https://mongodb.github.io/node-mongodb-native/4.9/classes/Db.html#createCollection)
396
+ * @param {Function} [callback]
397
+ * @return {Promise} Returns a Promise if no `callback` is given.
398
+ * @api public
399
+ */
400
+
401
+ Connection.prototype.createCollection = _wrapConnHelper(function createCollection(collection, options, cb) {
402
+ if (typeof options === 'function') {
403
+ cb = options;
404
+ options = {};
405
+ }
406
+ this.db.createCollection(collection, options, cb);
407
+ });
408
+
409
+ /**
410
+ * _Requires MongoDB >= 3.6.0._ Starts a [MongoDB session](https://www.mongodb.com/docs/manual/release-notes/3.6/#client-sessions)
411
+ * for benefits like causal consistency, [retryable writes](https://www.mongodb.com/docs/manual/core/retryable-writes/),
412
+ * and [transactions](https://thecodebarbarian.com/a-node-js-perspective-on-mongodb-4-transactions.html).
413
+ *
414
+ * #### Example:
415
+ *
416
+ * const session = await conn.startSession();
417
+ * let doc = await Person.findOne({ name: 'Ned Stark' }, null, { session });
418
+ * await doc.remove();
419
+ * // `doc` will always be null, even if reading from a replica set
420
+ * // secondary. Without causal consistency, it is possible to
421
+ * // get a doc back from the below query if the query reads from a
422
+ * // secondary that is experiencing replication lag.
423
+ * doc = await Person.findOne({ name: 'Ned Stark' }, null, { session, readPreference: 'secondary' });
424
+ *
425
+ *
426
+ * @method startSession
427
+ * @param {Object} [options] see the [mongodb driver options](https://mongodb.github.io/node-mongodb-native/4.9/classes/MongoClient.html#startSession)
428
+ * @param {Boolean} [options.causalConsistency=true] set to false to disable causal consistency
429
+ * @param {Function} [callback]
430
+ * @return {Promise<ClientSession>} promise that resolves to a MongoDB driver `ClientSession`
431
+ * @api public
432
+ */
433
+
434
+ Connection.prototype.startSession = _wrapConnHelper(function startSession(options, cb) {
435
+ if (typeof options === 'function') {
436
+ cb = options;
437
+ options = null;
438
+ }
439
+ const session = this.client.startSession(options);
440
+ cb(null, session);
441
+ });
442
+
443
+ /**
444
+ * _Requires MongoDB >= 3.6.0._ Executes the wrapped async function
445
+ * in a transaction. Mongoose will commit the transaction if the
446
+ * async function executes successfully and attempt to retry if
447
+ * there was a retriable error.
448
+ *
449
+ * Calls the MongoDB driver's [`session.withTransaction()`](https://mongodb.github.io/node-mongodb-native/4.9/classes/ClientSession.html#withTransaction),
450
+ * but also handles resetting Mongoose document state as shown below.
451
+ *
452
+ * #### Example:
453
+ *
454
+ * const doc = new Person({ name: 'Will Riker' });
455
+ * await db.transaction(async function setRank(session) {
456
+ * doc.rank = 'Captain';
457
+ * await doc.save({ session });
458
+ * doc.isNew; // false
459
+ *
460
+ * // Throw an error to abort the transaction
461
+ * throw new Error('Oops!');
462
+ * },{ readPreference: 'primary' }).catch(() => {});
463
+ *
464
+ * // true, `transaction()` reset the document's state because the
465
+ * // transaction was aborted.
466
+ * doc.isNew;
467
+ *
468
+ * @method transaction
469
+ * @param {Function} fn Function to execute in a transaction
470
+ * @param {mongodb.TransactionOptions} [options] Optional settings for the transaction
471
+ * @return {Promise<Any>} promise that is fulfilled if Mongoose successfully committed the transaction, or rejects if the transaction was aborted or if Mongoose failed to commit the transaction. If fulfilled, the promise resolves to a MongoDB command result.
472
+ * @api public
473
+ */
474
+
475
+ Connection.prototype.transaction = function transaction(fn, options) {
476
+ return this.startSession().then(session => {
477
+ session[sessionNewDocuments] = new Map();
478
+ return session.withTransaction(() => fn(session), options).
479
+ then(res => {
480
+ delete session[sessionNewDocuments];
481
+ return res;
482
+ }).
483
+ catch(err => {
484
+ // If transaction was aborted, we need to reset newly
485
+ // inserted documents' `isNew`.
486
+ for (const doc of session[sessionNewDocuments].keys()) {
487
+ const state = session[sessionNewDocuments].get(doc);
488
+ if (state.hasOwnProperty('isNew')) {
489
+ doc.$isNew = state.$isNew;
490
+ }
491
+ if (state.hasOwnProperty('versionKey')) {
492
+ doc.set(doc.schema.options.versionKey, state.versionKey);
493
+ }
494
+
495
+ if (state.modifiedPaths.length > 0 && doc.$__.activePaths.states.modify == null) {
496
+ doc.$__.activePaths.states.modify = {};
497
+ }
498
+ for (const path of state.modifiedPaths) {
499
+ doc.$__.activePaths.paths[path] = 'modify';
500
+ doc.$__.activePaths.states.modify[path] = true;
501
+ }
502
+
503
+ for (const path of state.atomics.keys()) {
504
+ const val = doc.$__getValue(path);
505
+ if (val == null) {
506
+ continue;
507
+ }
508
+ val[arrayAtomicsSymbol] = state.atomics.get(path);
509
+ }
510
+ }
511
+ delete session[sessionNewDocuments];
512
+ throw err;
513
+ })
514
+ .finally(() => {
515
+ session.endSession()
516
+ .catch(() => {});
517
+ });
518
+ });
519
+ };
520
+
521
+ /**
522
+ * Helper for `dropCollection()`. Will delete the given collection, including
523
+ * all documents and indexes.
524
+ *
525
+ * @method dropCollection
526
+ * @param {string} collection The collection to delete
527
+ * @param {Function} [callback]
528
+ * @return {Promise} Returns a Promise if no `callback` is given.
529
+ * @api public
530
+ */
531
+
532
+ Connection.prototype.dropCollection = _wrapConnHelper(function dropCollection(collection, cb) {
533
+ this.db.dropCollection(collection, cb);
534
+ });
535
+
536
+ /**
537
+ * Helper for `dropDatabase()`. Deletes the given database, including all
538
+ * collections, documents, and indexes.
539
+ *
540
+ * #### Example:
541
+ *
542
+ * const conn = mongoose.createConnection('mongodb://127.0.0.1:27017/mydb');
543
+ * // Deletes the entire 'mydb' database
544
+ * await conn.dropDatabase();
545
+ *
546
+ * @method dropDatabase
547
+ * @param {Function} [callback]
548
+ * @return {Promise} Returns a Promise if no `callback` is given.
549
+ * @api public
550
+ */
551
+
552
+ Connection.prototype.dropDatabase = _wrapConnHelper(function dropDatabase(cb) {
553
+ // If `dropDatabase()` is called, this model's collection will not be
554
+ // init-ed. It is sufficiently common to call `dropDatabase()` after
555
+ // `mongoose.connect()` but before creating models that we want to
556
+ // support this. See gh-6796
557
+ for (const model of Object.values(this.models)) {
558
+ delete model.$init;
559
+ }
560
+ this.db.dropDatabase(cb);
561
+ });
562
+
563
+ /*!
564
+ * ignore
565
+ */
566
+
567
+ function _wrapConnHelper(fn) {
568
+ return function() {
569
+ const cb = arguments.length > 0 ? arguments[arguments.length - 1] : null;
570
+ const argsWithoutCb = typeof cb === 'function' ?
571
+ Array.prototype.slice.call(arguments, 0, arguments.length - 1) :
572
+ Array.prototype.slice.call(arguments);
573
+ const disconnectedError = new DisconnectedError(this.id, fn.name);
574
+
575
+ return promiseOrCallback(cb, cb => {
576
+ immediate(() => {
577
+ if ((this.readyState === STATES.connecting || this.readyState === STATES.disconnected) && this._shouldBufferCommands()) {
578
+ this._queue.push({ fn: fn, ctx: this, args: argsWithoutCb.concat([cb]) });
579
+ } else if (this.readyState === STATES.disconnected && this.db == null) {
580
+ cb(disconnectedError);
581
+ } else {
582
+ try {
583
+ fn.apply(this, argsWithoutCb.concat([cb]));
584
+ } catch (err) {
585
+ return cb(err);
586
+ }
587
+ }
588
+ });
589
+ });
590
+ };
591
+ }
592
+
593
+ /*!
594
+ * ignore
595
+ */
596
+
597
+ Connection.prototype._shouldBufferCommands = function _shouldBufferCommands() {
598
+ if (this.config.bufferCommands != null) {
599
+ return this.config.bufferCommands;
600
+ }
601
+ if (this.base.get('bufferCommands') != null) {
602
+ return this.base.get('bufferCommands');
603
+ }
604
+ return true;
605
+ };
606
+
607
+ /**
608
+ * error
609
+ *
610
+ * Graceful error handling, passes error to callback
611
+ * if available, else emits error on the connection.
612
+ *
613
+ * @param {Error} err
614
+ * @param {Function} callback optional
615
+ * @emits "error" Emits the `error` event with the given `err`, unless a callback is specified
616
+ * @returns {Promise|null} Returns a rejected Promise if no `callback` is given.
617
+ * @api private
618
+ */
619
+
620
+ Connection.prototype.error = function(err, callback) {
621
+ if (callback) {
622
+ callback(err);
623
+ return null;
624
+ }
625
+ if (this.listeners('error').length > 0) {
626
+ this.emit('error', err);
627
+ }
628
+ return Promise.reject(err);
629
+ };
630
+
631
+ /**
632
+ * Called when the connection is opened
633
+ *
634
+ * @api private
635
+ */
636
+
637
+ Connection.prototype.onOpen = function() {
638
+ this.readyState = STATES.connected;
639
+
640
+ for (const d of this._queue) {
641
+ d.fn.apply(d.ctx, d.args);
642
+ }
643
+ this._queue = [];
644
+
645
+ // avoid having the collection subscribe to our event emitter
646
+ // to prevent 0.3 warning
647
+ for (const i in this.collections) {
648
+ if (utils.object.hasOwnProperty(this.collections, i)) {
649
+ this.collections[i].onOpen();
650
+ }
651
+ }
652
+
653
+ this.emit('open');
654
+ };
655
+
656
+ /**
657
+ * Opens the connection with a URI using `MongoClient.connect()`.
658
+ *
659
+ * @param {String} uri The URI to connect with.
660
+ * @param {Object} [options] Passed on to [`MongoClient.connect`](https://mongodb.github.io/node-mongodb-native/4.9/classes/MongoClient.html#connect-1)
661
+ * @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.
662
+ * @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.
663
+ * @param {String} [options.dbName] The name of the database we want to use. If not provided, use database name from connection string.
664
+ * @param {String} [options.user] username for authentication, equivalent to `options.auth.user`. Maintained for backwards compatibility.
665
+ * @param {String} [options.pass] password for authentication, equivalent to `options.auth.password`. Maintained for backwards compatibility.
666
+ * @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).
667
+ * @param {Number} [options.minPoolSize=0] 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).
668
+ * @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).
669
+ * @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.
670
+ * @param {Boolean} [options.autoIndex=true] Mongoose-specific option. Set to false to disable automatic index creation for all models associated with this connection.
671
+ * @param {Class} [options.promiseLibrary] Sets the [underlying driver's promise library](https://mongodb.github.io/node-mongodb-native/4.9/interfaces/MongoClientOptions.html#promiseLibrary).
672
+ * @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).
673
+ * @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.
674
+ * @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.
675
+ * @param {Boolean} [options.autoCreate=false] Set to `true` to make Mongoose automatically call `createCollection()` on every model created on this connection.
676
+ * @param {Function} [callback]
677
+ * @returns {Promise<Connection>} Returns a Promise if no `callback` is given.
678
+ * @api public
679
+ */
680
+
681
+ Connection.prototype.openUri = function(uri, options, callback) {
682
+ if (typeof options === 'function') {
683
+ callback = options;
684
+ options = null;
685
+ }
686
+
687
+ if (['string', 'number'].indexOf(typeof options) !== -1) {
688
+ throw new MongooseError('Mongoose 5.x no longer supports ' +
689
+ '`mongoose.connect(host, dbname, port)` or ' +
690
+ '`mongoose.createConnection(host, dbname, port)`. See ' +
691
+ 'https://mongoosejs.com/docs/connections.html for supported connection syntax');
692
+ }
693
+
694
+ if (typeof uri !== 'string') {
695
+ throw new MongooseError('The `uri` parameter to `openUri()` must be a ' +
696
+ `string, got "${typeof uri}". Make sure the first parameter to ` +
697
+ '`mongoose.connect()` or `mongoose.createConnection()` is a string.');
698
+ }
699
+
700
+ if (callback != null && typeof callback !== 'function') {
701
+ throw new MongooseError('3rd parameter to `mongoose.connect()` or ' +
702
+ '`mongoose.createConnection()` must be a function, got "' +
703
+ typeof callback + '"');
704
+ }
705
+
706
+ if (this._destroyCalled) {
707
+ const error = 'Connection has been closed and destroyed, and cannot be used for re-opening the connection. ' +
708
+ 'Please create a new connection with `mongoose.createConnection()` or `mongoose.connect()`.';
709
+ if (typeof callback === 'function') {
710
+ callback(error);
711
+ return;
712
+ }
713
+ else {
714
+ throw new MongooseError(error);
715
+ }
716
+ }
717
+
718
+ if (this.readyState === STATES.connecting || this.readyState === STATES.connected) {
719
+ if (this._connectionString !== uri) {
720
+ throw new MongooseError('Can\'t call `openUri()` on an active connection with ' +
721
+ 'different connection strings. Make sure you aren\'t calling `mongoose.connect()` ' +
722
+ 'multiple times. See: https://mongoosejs.com/docs/connections.html#multiple_connections');
723
+ }
724
+
725
+ if (typeof callback === 'function') {
726
+ this.$initialConnection = this.$initialConnection.then(
727
+ () => callback(null, this),
728
+ err => callback(err)
729
+ );
730
+ }
731
+ return this;
732
+ }
733
+
734
+ this._connectionString = uri;
735
+ this.readyState = STATES.connecting;
736
+ this._closeCalled = false;
737
+
738
+ const Promise = PromiseProvider.get();
739
+ const _this = this;
740
+
741
+ options = processConnectionOptions(uri, options);
742
+
743
+ if (options) {
744
+ options = utils.clone(options);
745
+
746
+ const autoIndex = options.config && options.config.autoIndex != null ?
747
+ options.config.autoIndex :
748
+ options.autoIndex;
749
+ if (autoIndex != null) {
750
+ this.config.autoIndex = autoIndex !== false;
751
+ delete options.config;
752
+ delete options.autoIndex;
753
+ }
754
+
755
+ if ('autoCreate' in options) {
756
+ this.config.autoCreate = !!options.autoCreate;
757
+ delete options.autoCreate;
758
+ }
759
+
760
+ if ('sanitizeFilter' in options) {
761
+ this.config.sanitizeFilter = options.sanitizeFilter;
762
+ delete options.sanitizeFilter;
763
+ }
764
+
765
+ // Backwards compat
766
+ if (options.user || options.pass) {
767
+ options.auth = options.auth || {};
768
+ options.auth.username = options.user;
769
+ options.auth.password = options.pass;
770
+
771
+ this.user = options.user;
772
+ this.pass = options.pass;
773
+ }
774
+ delete options.user;
775
+ delete options.pass;
776
+
777
+ if (options.bufferCommands != null) {
778
+ this.config.bufferCommands = options.bufferCommands;
779
+ delete options.bufferCommands;
780
+ }
781
+ } else {
782
+ options = {};
783
+ }
784
+
785
+ this._connectionOptions = options;
786
+ const dbName = options.dbName;
787
+ if (dbName != null) {
788
+ this.$dbName = dbName;
789
+ }
790
+ delete options.dbName;
791
+
792
+ if (!utils.hasUserDefinedProperty(options, 'driverInfo')) {
793
+ options.driverInfo = {
794
+ name: 'Mongoose',
795
+ version: pkg.version
796
+ };
797
+ }
798
+
799
+ const promise = new Promise((resolve, reject) => {
800
+ let client;
801
+ try {
802
+ client = new mongodb.MongoClient(uri, options);
803
+ } catch (error) {
804
+ _this.readyState = STATES.disconnected;
805
+ return reject(error);
806
+ }
807
+ _this.client = client;
808
+
809
+ client.setMaxListeners(0);
810
+ client.connect((error) => {
811
+ if (error) {
812
+ return reject(error);
813
+ }
814
+
815
+ _setClient(_this, client, options, dbName);
816
+
817
+ for (const db of this.otherDbs) {
818
+ _setClient(db, client, {}, db.name);
819
+ }
820
+
821
+ resolve(_this);
822
+ });
823
+ });
824
+
825
+ const serverSelectionError = new ServerSelectionError();
826
+ this.$initialConnection = promise.
827
+ then(() => this).
828
+ catch(err => {
829
+ this.readyState = STATES.disconnected;
830
+ if (err != null && err.name === 'MongoServerSelectionError') {
831
+ err = serverSelectionError.assimilateError(err);
832
+ }
833
+
834
+ if (this.listeners('error').length > 0) {
835
+ immediate(() => this.emit('error', err));
836
+ }
837
+ throw err;
838
+ });
839
+
840
+ if (callback != null) {
841
+ this.$initialConnection = this.$initialConnection.then(
842
+ () => { callback(null, this); return this; },
843
+ err => callback(err)
844
+ );
845
+ }
846
+
847
+ for (const model of Object.values(this.models)) {
848
+ // Errors handled internally, so safe to ignore error
849
+ model.init(function $modelInitNoop() {});
850
+ }
851
+
852
+ return this.$initialConnection;
853
+ };
854
+
855
+ /*!
856
+ * ignore
857
+ */
858
+
859
+ function _setClient(conn, client, options, dbName) {
860
+ const db = dbName != null ? client.db(dbName) : client.db();
861
+ conn.db = db;
862
+ conn.client = client;
863
+ conn.host = client &&
864
+ client.s &&
865
+ client.s.options &&
866
+ client.s.options.hosts &&
867
+ client.s.options.hosts[0] &&
868
+ client.s.options.hosts[0].host || void 0;
869
+ conn.port = client &&
870
+ client.s &&
871
+ client.s.options &&
872
+ client.s.options.hosts &&
873
+ client.s.options.hosts[0] &&
874
+ client.s.options.hosts[0].port || void 0;
875
+ conn.name = dbName != null ? dbName : client && client.s && client.s.options && client.s.options.dbName || void 0;
876
+ conn._closeCalled = client._closeCalled;
877
+
878
+ const _handleReconnect = () => {
879
+ // If we aren't disconnected, we assume this reconnect is due to a
880
+ // socket timeout. If there's no activity on a socket for
881
+ // `socketTimeoutMS`, the driver will attempt to reconnect and emit
882
+ // this event.
883
+ if (conn.readyState !== STATES.connected) {
884
+ conn.readyState = STATES.connected;
885
+ conn.emit('reconnect');
886
+ conn.emit('reconnected');
887
+ conn.onOpen();
888
+ }
889
+ };
890
+
891
+ const type = client &&
892
+ client.topology &&
893
+ client.topology.description &&
894
+ client.topology.description.type || '';
895
+
896
+ if (type === 'Single') {
897
+ client.on('serverDescriptionChanged', ev => {
898
+ const newDescription = ev.newDescription;
899
+ if (newDescription.type === 'Unknown') {
900
+ conn.readyState = STATES.disconnected;
901
+ } else {
902
+ _handleReconnect();
903
+ }
904
+ });
905
+ } else if (type.startsWith('ReplicaSet')) {
906
+ client.on('topologyDescriptionChanged', ev => {
907
+ // Emit disconnected if we've lost connectivity to the primary
908
+ const description = ev.newDescription;
909
+ if (conn.readyState === STATES.connected && description.type !== 'ReplicaSetWithPrimary') {
910
+ // Implicitly emits 'disconnected'
911
+ conn.readyState = STATES.disconnected;
912
+ } else if (conn.readyState === STATES.disconnected && description.type === 'ReplicaSetWithPrimary') {
913
+ _handleReconnect();
914
+ }
915
+ });
916
+ }
917
+
918
+ conn.onOpen();
919
+
920
+ for (const i in conn.collections) {
921
+ if (utils.object.hasOwnProperty(conn.collections, i)) {
922
+ conn.collections[i].onOpen();
923
+ }
924
+ }
925
+ }
926
+
927
+ /**
928
+ * Destory the connection (not just a alias of [`.close`](#connection_Connection-close))
929
+ *
930
+ * @param {Boolean} [force]
931
+ * @param {Function} [callback]
932
+ * @returns {Promise} Returns a Promise if no `callback` is given.
933
+ */
934
+
935
+ Connection.prototype.destroy = function(force, callback) {
936
+ if (typeof force === 'function') {
937
+ callback = force;
938
+ force = false;
939
+ }
940
+
941
+ if (force != null && typeof force === 'object') {
942
+ this.$wasForceClosed = !!force.force;
943
+ } else {
944
+ this.$wasForceClosed = !!force;
945
+ }
946
+
947
+ return promiseOrCallback(callback, cb => {
948
+ this._close(force, true, cb);
949
+ });
950
+ };
951
+
952
+ /**
953
+ * Closes the connection
954
+ *
955
+ * @param {Boolean} [force] optional
956
+ * @param {Function} [callback] optional
957
+ * @return {Promise} Returns a Promise if no `callback` is given.
958
+ * @api public
959
+ */
960
+
961
+ Connection.prototype.close = function(force, callback) {
962
+ if (typeof force === 'function') {
963
+ callback = force;
964
+ force = false;
965
+ }
966
+
967
+ if (force != null && typeof force === 'object') {
968
+ this.$wasForceClosed = !!force.force;
969
+ } else {
970
+ this.$wasForceClosed = !!force;
971
+ }
972
+
973
+ for (const model of Object.values(this.models)) {
974
+ // If manually disconnecting, make sure to clear each model's `$init`
975
+ // promise, so Mongoose knows to re-run `init()` in case the
976
+ // connection is re-opened. See gh-12047.
977
+ delete model.$init;
978
+ }
979
+
980
+ return promiseOrCallback(callback, cb => {
981
+ this._close(force, false, cb);
982
+ });
983
+ };
984
+
985
+ /**
986
+ * Handles closing the connection
987
+ *
988
+ * @param {Boolean} force
989
+ * @param {Boolean} destroy
990
+ * @param {Function} [callback]
991
+ * @returns {Connection} this
992
+ * @api private
993
+ */
994
+ Connection.prototype._close = function(force, destroy, callback) {
995
+ const _this = this;
996
+ const closeCalled = this._closeCalled;
997
+ this._closeCalled = true;
998
+ this._destroyCalled = destroy;
999
+ if (this.client != null) {
1000
+ this.client._closeCalled = true;
1001
+ this.client._destroyCalled = destroy;
1002
+ }
1003
+
1004
+ const conn = this;
1005
+ switch (this.readyState) {
1006
+ case STATES.disconnected:
1007
+ if (destroy && this.base.connections.indexOf(conn) !== -1) {
1008
+ this.base.connections.splice(this.base.connections.indexOf(conn), 1);
1009
+ }
1010
+ if (closeCalled) {
1011
+ callback();
1012
+ } else {
1013
+ this.doClose(force, function(err) {
1014
+ if (err) {
1015
+ return callback(err);
1016
+ }
1017
+ _this.onClose(force);
1018
+ callback(null);
1019
+ });
1020
+ }
1021
+ break;
1022
+
1023
+ case STATES.connected:
1024
+ this.readyState = STATES.disconnecting;
1025
+ this.doClose(force, function(err) {
1026
+ if (err) {
1027
+ return callback(err);
1028
+ }
1029
+ if (destroy && _this.base.connections.indexOf(conn) !== -1) {
1030
+ _this.base.connections.splice(_this.base.connections.indexOf(conn), 1);
1031
+ }
1032
+ _this.onClose(force);
1033
+ callback(null);
1034
+ });
1035
+
1036
+ break;
1037
+ case STATES.connecting:
1038
+ this.once('open', function() {
1039
+ destroy ? _this.destroy(force, callback) : _this.close(force, callback);
1040
+ });
1041
+ break;
1042
+
1043
+ case STATES.disconnecting:
1044
+ this.once('close', function() {
1045
+ if (destroy && _this.base.connections.indexOf(conn) !== -1) {
1046
+ _this.base.connections.splice(_this.base.connections.indexOf(conn), 1);
1047
+ }
1048
+ callback();
1049
+ });
1050
+ break;
1051
+ }
1052
+
1053
+ return this;
1054
+ };
1055
+
1056
+ /**
1057
+ * Abstract method that drivers must implement.
1058
+ *
1059
+ * @api private
1060
+ */
1061
+
1062
+ Connection.prototype.doClose = function() {
1063
+ throw new Error('Connection#doClose unimplemented by driver');
1064
+ };
1065
+
1066
+ /**
1067
+ * Called when the connection closes
1068
+ *
1069
+ * @api private
1070
+ */
1071
+
1072
+ Connection.prototype.onClose = function(force) {
1073
+ this.readyState = STATES.disconnected;
1074
+
1075
+ // avoid having the collection subscribe to our event emitter
1076
+ // to prevent 0.3 warning
1077
+ for (const i in this.collections) {
1078
+ if (utils.object.hasOwnProperty(this.collections, i)) {
1079
+ this.collections[i].onClose(force);
1080
+ }
1081
+ }
1082
+
1083
+ this.emit('close', force);
1084
+
1085
+ for (const db of this.otherDbs) {
1086
+ this._destroyCalled ? db.destroy({ force: force, skipCloseClient: true }) : db.close({ force: force, skipCloseClient: true });
1087
+ }
1088
+ };
1089
+
1090
+ /**
1091
+ * Retrieves a collection, creating it if not cached.
1092
+ *
1093
+ * Not typically needed by applications. Just talk to your collection through your model.
1094
+ *
1095
+ * @param {String} name of the collection
1096
+ * @param {Object} [options] optional collection options
1097
+ * @return {Collection} collection instance
1098
+ * @api public
1099
+ */
1100
+
1101
+ Connection.prototype.collection = function(name, options) {
1102
+ const defaultOptions = {
1103
+ autoIndex: this.config.autoIndex != null ? this.config.autoIndex : this.base.options.autoIndex,
1104
+ autoCreate: this.config.autoCreate != null ? this.config.autoCreate : this.base.options.autoCreate
1105
+ };
1106
+ options = Object.assign({}, defaultOptions, options ? utils.clone(options) : {});
1107
+ options.$wasForceClosed = this.$wasForceClosed;
1108
+ const Collection = this.base && this.base.__driver && this.base.__driver.Collection || driver.get().Collection;
1109
+ if (!(name in this.collections)) {
1110
+ this.collections[name] = new Collection(name, this, options);
1111
+ }
1112
+ return this.collections[name];
1113
+ };
1114
+
1115
+ /**
1116
+ * Declares a plugin executed on all schemas you pass to `conn.model()`
1117
+ *
1118
+ * Equivalent to calling `.plugin(fn)` on each schema you create.
1119
+ *
1120
+ * #### Example:
1121
+ *
1122
+ * const db = mongoose.createConnection('mongodb://127.0.0.1:27017/mydb');
1123
+ * db.plugin(() => console.log('Applied'));
1124
+ * db.plugins.length; // 1
1125
+ *
1126
+ * db.model('Test', new Schema({})); // Prints "Applied"
1127
+ *
1128
+ * @param {Function} fn plugin callback
1129
+ * @param {Object} [opts] optional options
1130
+ * @return {Connection} this
1131
+ * @see plugins /docs/plugins.html
1132
+ * @api public
1133
+ */
1134
+
1135
+ Connection.prototype.plugin = function(fn, opts) {
1136
+ this.plugins.push([fn, opts]);
1137
+ return this;
1138
+ };
1139
+
1140
+ /**
1141
+ * Defines or retrieves a model.
1142
+ *
1143
+ * const mongoose = require('mongoose');
1144
+ * const db = mongoose.createConnection(..);
1145
+ * db.model('Venue', new Schema(..));
1146
+ * const Ticket = db.model('Ticket', new Schema(..));
1147
+ * const Venue = db.model('Venue');
1148
+ *
1149
+ * _When no `collection` argument is passed, Mongoose produces a collection name by passing the model `name` to the [utils.toCollectionName](#utils_exports-toCollectionName) method. This method pluralizes the name. If you don't like this behavior, either pass a collection name or set your schemas collection name option._
1150
+ *
1151
+ * #### Example:
1152
+ *
1153
+ * const schema = new Schema({ name: String }, { collection: 'actor' });
1154
+ *
1155
+ * // or
1156
+ *
1157
+ * schema.set('collection', 'actor');
1158
+ *
1159
+ * // or
1160
+ *
1161
+ * const collectionName = 'actor'
1162
+ * const M = conn.model('Actor', schema, collectionName)
1163
+ *
1164
+ * @param {String|Function} name the model name or class extending Model
1165
+ * @param {Schema} [schema] a schema. necessary when defining a model
1166
+ * @param {String} [collection] name of mongodb collection (optional) if not given it will be induced from model name
1167
+ * @param {Object} [options]
1168
+ * @param {Boolean} [options.overwriteModels=false] If true, overwrite existing models with the same name to avoid `OverwriteModelError`
1169
+ * @see Mongoose#model #index_Mongoose-model
1170
+ * @return {Model} The compiled model
1171
+ * @api public
1172
+ */
1173
+
1174
+ Connection.prototype.model = function(name, schema, collection, options) {
1175
+ if (!(this instanceof Connection)) {
1176
+ throw new MongooseError('`connection.model()` should not be run with ' +
1177
+ '`new`. If you are doing `new db.model(foo)(bar)`, use ' +
1178
+ '`db.model(foo)(bar)` instead');
1179
+ }
1180
+
1181
+ let fn;
1182
+ if (typeof name === 'function') {
1183
+ fn = name;
1184
+ name = fn.name;
1185
+ }
1186
+
1187
+ // collection name discovery
1188
+ if (typeof schema === 'string') {
1189
+ collection = schema;
1190
+ schema = false;
1191
+ }
1192
+
1193
+ if (utils.isObject(schema)) {
1194
+ if (!schema.instanceOfSchema) {
1195
+ schema = new Schema(schema);
1196
+ } else if (!(schema instanceof this.base.Schema)) {
1197
+ schema = schema._clone(this.base.Schema);
1198
+ }
1199
+ }
1200
+ if (schema && !schema.instanceOfSchema) {
1201
+ throw new Error('The 2nd parameter to `mongoose.model()` should be a ' +
1202
+ 'schema or a POJO');
1203
+ }
1204
+
1205
+ const defaultOptions = { cache: false, overwriteModels: this.base.options.overwriteModels };
1206
+ const opts = Object.assign(defaultOptions, options, { connection: this });
1207
+ if (this.models[name] && !collection && opts.overwriteModels !== true) {
1208
+ // model exists but we are not subclassing with custom collection
1209
+ if (schema && schema.instanceOfSchema && schema !== this.models[name].schema) {
1210
+ throw new MongooseError.OverwriteModelError(name);
1211
+ }
1212
+ return this.models[name];
1213
+ }
1214
+
1215
+ let model;
1216
+
1217
+ if (schema && schema.instanceOfSchema) {
1218
+ applyPlugins(schema, this.plugins, null, '$connectionPluginsApplied');
1219
+
1220
+ // compile a model
1221
+ model = this.base._model(fn || name, schema, collection, opts);
1222
+
1223
+ // only the first model with this name is cached to allow
1224
+ // for one-offs with custom collection names etc.
1225
+ if (!this.models[name]) {
1226
+ this.models[name] = model;
1227
+ }
1228
+
1229
+ // Errors handled internally, so safe to ignore error
1230
+ model.init(function $modelInitNoop() {});
1231
+
1232
+ return model;
1233
+ }
1234
+
1235
+ if (this.models[name] && collection) {
1236
+ // subclassing current model with alternate collection
1237
+ model = this.models[name];
1238
+ schema = model.prototype.schema;
1239
+ const sub = model.__subclass(this, schema, collection);
1240
+ // do not cache the sub model
1241
+ return sub;
1242
+ }
1243
+
1244
+ if (arguments.length === 1) {
1245
+ model = this.models[name];
1246
+ if (!model) {
1247
+ throw new MongooseError.MissingSchemaError(name);
1248
+ }
1249
+ return model;
1250
+ }
1251
+
1252
+ if (!model) {
1253
+ throw new MongooseError.MissingSchemaError(name);
1254
+ }
1255
+
1256
+ if (this === model.prototype.db
1257
+ && (!collection || collection === model.collection.name)) {
1258
+ // model already uses this connection.
1259
+
1260
+ // only the first model with this name is cached to allow
1261
+ // for one-offs with custom collection names etc.
1262
+ if (!this.models[name]) {
1263
+ this.models[name] = model;
1264
+ }
1265
+
1266
+ return model;
1267
+ }
1268
+ this.models[name] = model.__subclass(this, schema, collection);
1269
+ return this.models[name];
1270
+ };
1271
+
1272
+ /**
1273
+ * Removes the model named `name` from this connection, if it exists. You can
1274
+ * use this function to clean up any models you created in your tests to
1275
+ * prevent OverwriteModelErrors.
1276
+ *
1277
+ * #### Example:
1278
+ *
1279
+ * conn.model('User', new Schema({ name: String }));
1280
+ * console.log(conn.model('User')); // Model object
1281
+ * conn.deleteModel('User');
1282
+ * console.log(conn.model('User')); // undefined
1283
+ *
1284
+ * // Usually useful in a Mocha `afterEach()` hook
1285
+ * afterEach(function() {
1286
+ * conn.deleteModel(/.+/); // Delete every model
1287
+ * });
1288
+ *
1289
+ * @api public
1290
+ * @param {String|RegExp} name if string, the name of the model to remove. If regexp, removes all models whose name matches the regexp.
1291
+ * @return {Connection} this
1292
+ */
1293
+
1294
+ Connection.prototype.deleteModel = function(name) {
1295
+ if (typeof name === 'string') {
1296
+ const model = this.model(name);
1297
+ if (model == null) {
1298
+ return this;
1299
+ }
1300
+ const collectionName = model.collection.name;
1301
+ delete this.models[name];
1302
+ delete this.collections[collectionName];
1303
+
1304
+ this.emit('deleteModel', model);
1305
+ } else if (name instanceof RegExp) {
1306
+ const pattern = name;
1307
+ const names = this.modelNames();
1308
+ for (const name of names) {
1309
+ if (pattern.test(name)) {
1310
+ this.deleteModel(name);
1311
+ }
1312
+ }
1313
+ } else {
1314
+ throw new Error('First parameter to `deleteModel()` must be a string ' +
1315
+ 'or regexp, got "' + name + '"');
1316
+ }
1317
+
1318
+ return this;
1319
+ };
1320
+
1321
+ /**
1322
+ * Watches the entire underlying database for changes. Similar to
1323
+ * [`Model.watch()`](/docs/api/model.html#model_Model-watch).
1324
+ *
1325
+ * This function does **not** trigger any middleware. In particular, it
1326
+ * does **not** trigger aggregate middleware.
1327
+ *
1328
+ * The ChangeStream object is an event emitter that emits the following events:
1329
+ *
1330
+ * - 'change': A change occurred, see below example
1331
+ * - 'error': An unrecoverable error occurred. In particular, change streams currently error out if they lose connection to the replica set primary. Follow [this GitHub issue](https://github.com/Automattic/mongoose/issues/6799) for updates.
1332
+ * - 'end': Emitted if the underlying stream is closed
1333
+ * - 'close': Emitted if the underlying stream is closed
1334
+ *
1335
+ * #### Example:
1336
+ *
1337
+ * const User = conn.model('User', new Schema({ name: String }));
1338
+ *
1339
+ * const changeStream = conn.watch().on('change', data => console.log(data));
1340
+ *
1341
+ * // Triggers a 'change' event on the change stream.
1342
+ * await User.create({ name: 'test' });
1343
+ *
1344
+ * @api public
1345
+ * @param {Array} [pipeline]
1346
+ * @param {Object} [options] passed without changes to [the MongoDB driver's `Db#watch()` function](https://mongodb.github.io/node-mongodb-native/4.9/classes/Db.html#watch)
1347
+ * @return {ChangeStream} mongoose-specific change stream wrapper, inherits from EventEmitter
1348
+ */
1349
+
1350
+ Connection.prototype.watch = function(pipeline, options) {
1351
+ const disconnectedError = new DisconnectedError(this.id, 'watch');
1352
+
1353
+ const changeStreamThunk = cb => {
1354
+ immediate(() => {
1355
+ if (this.readyState === STATES.connecting) {
1356
+ this.once('open', function() {
1357
+ const driverChangeStream = this.db.watch(pipeline, options);
1358
+ cb(null, driverChangeStream);
1359
+ });
1360
+ } else if (this.readyState === STATES.disconnected && this.db == null) {
1361
+ cb(disconnectedError);
1362
+ } else {
1363
+ const driverChangeStream = this.db.watch(pipeline, options);
1364
+ cb(null, driverChangeStream);
1365
+ }
1366
+ });
1367
+ };
1368
+
1369
+ const changeStream = new ChangeStream(changeStreamThunk, pipeline, options);
1370
+ return changeStream;
1371
+ };
1372
+
1373
+ /**
1374
+ * Returns a promise that resolves when this connection
1375
+ * successfully connects to MongoDB, or rejects if this connection failed
1376
+ * to connect.
1377
+ *
1378
+ * #### Example:
1379
+ *
1380
+ * const conn = await mongoose.createConnection('mongodb://127.0.0.1:27017/test').
1381
+ * asPromise();
1382
+ * conn.readyState; // 1, means Mongoose is connected
1383
+ *
1384
+ * @api public
1385
+ * @return {Promise}
1386
+ */
1387
+
1388
+ Connection.prototype.asPromise = function asPromise() {
1389
+ return this.$initialConnection;
1390
+ };
1391
+
1392
+ /**
1393
+ * Returns an array of model names created on this connection.
1394
+ * @api public
1395
+ * @return {String[]}
1396
+ */
1397
+
1398
+ Connection.prototype.modelNames = function() {
1399
+ return Object.keys(this.models);
1400
+ };
1401
+
1402
+ /**
1403
+ * Returns if the connection requires authentication after it is opened. Generally if a
1404
+ * username and password are both provided than authentication is needed, but in some cases a
1405
+ * password is not required.
1406
+ *
1407
+ * @api private
1408
+ * @return {Boolean} true if the connection should be authenticated after it is opened, otherwise false.
1409
+ */
1410
+ Connection.prototype.shouldAuthenticate = function() {
1411
+ return this.user != null &&
1412
+ (this.pass != null || this.authMechanismDoesNotRequirePassword());
1413
+ };
1414
+
1415
+ /**
1416
+ * Returns a boolean value that specifies if the current authentication mechanism needs a
1417
+ * password to authenticate according to the auth objects passed into the openUri methods.
1418
+ *
1419
+ * @api private
1420
+ * @return {Boolean} true if the authentication mechanism specified in the options object requires
1421
+ * a password, otherwise false.
1422
+ */
1423
+ Connection.prototype.authMechanismDoesNotRequirePassword = function() {
1424
+ if (this.options && this.options.auth) {
1425
+ return noPasswordAuthMechanisms.indexOf(this.options.auth.authMechanism) >= 0;
1426
+ }
1427
+ return true;
1428
+ };
1429
+
1430
+ /**
1431
+ * Returns a boolean value that specifies if the provided objects object provides enough
1432
+ * data to authenticate with. Generally this is true if the username and password are both specified
1433
+ * but in some authentication methods, a password is not required for authentication so only a username
1434
+ * is required.
1435
+ *
1436
+ * @param {Object} [options] the options object passed into the openUri methods.
1437
+ * @api private
1438
+ * @return {Boolean} true if the provided options object provides enough data to authenticate with,
1439
+ * otherwise false.
1440
+ */
1441
+ Connection.prototype.optionsProvideAuthenticationData = function(options) {
1442
+ return (options) &&
1443
+ (options.user) &&
1444
+ ((options.pass) || this.authMechanismDoesNotRequirePassword());
1445
+ };
1446
+
1447
+ /**
1448
+ * Returns the [MongoDB driver `MongoClient`](https://mongodb.github.io/node-mongodb-native/4.9/classes/MongoClient.html) instance
1449
+ * that this connection uses to talk to MongoDB.
1450
+ *
1451
+ * #### Example:
1452
+ *
1453
+ * const conn = await mongoose.createConnection('mongodb://127.0.0.1:27017/test').
1454
+ * asPromise();
1455
+ *
1456
+ * conn.getClient(); // MongoClient { ... }
1457
+ *
1458
+ * @api public
1459
+ * @return {MongoClient}
1460
+ */
1461
+
1462
+ Connection.prototype.getClient = function getClient() {
1463
+ return this.client;
1464
+ };
1465
+
1466
+ /**
1467
+ * Set the [MongoDB driver `MongoClient`](https://mongodb.github.io/node-mongodb-native/4.9/classes/MongoClient.html) instance
1468
+ * that this connection uses to talk to MongoDB. This is useful if you already have a MongoClient instance, and want to
1469
+ * reuse it.
1470
+ *
1471
+ * #### Example:
1472
+ *
1473
+ * const client = await mongodb.MongoClient.connect('mongodb://127.0.0.1:27017/test');
1474
+ *
1475
+ * const conn = mongoose.createConnection().setClient(client);
1476
+ *
1477
+ * conn.getClient(); // MongoClient { ... }
1478
+ * conn.readyState; // 1, means 'CONNECTED'
1479
+ *
1480
+ * @api public
1481
+ * @param {MongClient} client The Client to set to be used.
1482
+ * @return {Connection} this
1483
+ */
1484
+
1485
+ Connection.prototype.setClient = function setClient(client) {
1486
+ if (!(client instanceof mongodb.MongoClient)) {
1487
+ throw new MongooseError('Must call `setClient()` with an instance of MongoClient');
1488
+ }
1489
+ if (this.readyState !== STATES.disconnected) {
1490
+ throw new MongooseError('Cannot call `setClient()` on a connection that is already connected.');
1491
+ }
1492
+ if (client.topology == null) {
1493
+ throw new MongooseError('Cannot call `setClient()` with a MongoClient that you have not called `connect()` on yet.');
1494
+ }
1495
+
1496
+ this._connectionString = client.s.url;
1497
+ _setClient(this, client, {}, client.s.options.dbName);
1498
+
1499
+ for (const model of Object.values(this.models)) {
1500
+ // Errors handled internally, so safe to ignore error
1501
+ model.init(function $modelInitNoop() {});
1502
+ }
1503
+
1504
+ return this;
1505
+ };
1506
+
1507
+ /**
1508
+ * Syncs all the indexes for the models registered with this connection.
1509
+ *
1510
+ * @param {Object} [options]
1511
+ * @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.
1512
+ * @return {Promise<Object>} Returns a Promise, when the Promise resolves the value is a list of the dropped indexes.
1513
+ */
1514
+ Connection.prototype.syncIndexes = async function syncIndexes(options = {}) {
1515
+ const result = {};
1516
+ const errorsMap = { };
1517
+
1518
+ const { continueOnError } = options;
1519
+ delete options.continueOnError;
1520
+
1521
+ for (const model of Object.values(this.models)) {
1522
+ try {
1523
+ result[model.modelName] = await model.syncIndexes(options);
1524
+ } catch (err) {
1525
+ if (!continueOnError) {
1526
+ errorsMap[model.modelName] = err;
1527
+ break;
1528
+ } else {
1529
+ result[model.modelName] = err;
1530
+ }
1531
+ }
1532
+ }
1533
+
1534
+ if (!continueOnError && Object.keys(errorsMap).length) {
1535
+ const message = Object.entries(errorsMap).map(([modelName, err]) => `${modelName}: ${err.message}`).join(', ');
1536
+ const syncIndexesError = new SyncIndexesError(message, errorsMap);
1537
+ throw syncIndexesError;
1538
+ }
1539
+
1540
+ return result;
1541
+ };
1542
+
1543
+ /**
1544
+ * Switches to a different database using the same connection pool.
1545
+ *
1546
+ * Returns a new connection object, with the new db.
1547
+ *
1548
+ * #### Example:
1549
+ *
1550
+ * // Connect to `initialdb` first
1551
+ * const conn = await mongoose.createConnection('mongodb://127.0.0.1:27017/initialdb').asPromise();
1552
+ *
1553
+ * // Creates an un-cached connection to `mydb`
1554
+ * const db = conn.useDb('mydb');
1555
+ * // Creates a cached connection to `mydb2`. All calls to `conn.useDb('mydb2', { useCache: true })` will return the same
1556
+ * // connection instance as opposed to creating a new connection instance
1557
+ * const db2 = conn.useDb('mydb2', { useCache: true });
1558
+ *
1559
+ * @method useDb
1560
+ * @memberOf Connection
1561
+ * @param {String} name The database name
1562
+ * @param {Object} [options]
1563
+ * @param {Boolean} [options.useCache=false] If true, cache results so calling `useDb()` multiple times with the same name only creates 1 connection object.
1564
+ * @param {Boolean} [options.noListener=false] If true, the connection object will not make the db listen to events on the original connection. See [issue #9961](https://github.com/Automattic/mongoose/issues/9961).
1565
+ * @return {Connection} New Connection Object
1566
+ * @api public
1567
+ */
1568
+
1569
+ /*!
1570
+ * Module exports.
1571
+ */
1572
+
1573
+ Connection.STATES = STATES;
1574
+ module.exports = Connection;