@datanimbus/mongoose 6.13.13 → 9.13.2

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 (302) hide show
  1. package/README.md +80 -70
  2. package/eslint.config.mjs +202 -0
  3. package/index.js +2 -1
  4. package/lib/aggregate.js +276 -174
  5. package/lib/cast/bigint.js +46 -0
  6. package/lib/cast/boolean.js +3 -3
  7. package/lib/cast/decimal128.js +4 -1
  8. package/lib/cast/double.js +56 -0
  9. package/lib/cast/int32.js +42 -0
  10. package/lib/cast/number.js +6 -6
  11. package/lib/cast/objectid.js +3 -3
  12. package/lib/cast/string.js +3 -3
  13. package/lib/cast/uuid.js +35 -0
  14. package/lib/cast.js +100 -92
  15. package/lib/collection.js +31 -22
  16. package/lib/connection.js +792 -507
  17. package/lib/constants.js +73 -0
  18. package/lib/cursor/{AggregationCursor.js → aggregationCursor.js} +205 -52
  19. package/lib/cursor/changeStream.js +218 -0
  20. package/lib/cursor/queryCursor.js +676 -0
  21. package/lib/defaults/schemaDefaultsCache.js +62 -0
  22. package/lib/document.js +2419 -1306
  23. package/lib/drivers/node-mongodb-native/bulkWriteResult.js +5 -0
  24. package/lib/drivers/node-mongodb-native/collection.js +101 -135
  25. package/lib/drivers/node-mongodb-native/connection.js +386 -28
  26. package/lib/drivers/node-mongodb-native/index.js +3 -5
  27. package/lib/error/browserMissingSchema.js +5 -4
  28. package/lib/error/bulkSaveIncompleteError.js +44 -0
  29. package/lib/error/cast.js +30 -21
  30. package/lib/error/createCollectionsError.js +26 -0
  31. package/lib/error/divergentArray.js +11 -9
  32. package/lib/error/eachAsyncMultiError.js +2 -2
  33. package/lib/error/index.js +38 -29
  34. package/lib/error/invalidSchemaOption.js +32 -0
  35. package/lib/error/messages.js +4 -3
  36. package/lib/error/missingSchema.js +8 -6
  37. package/lib/error/notFound.js +7 -5
  38. package/lib/error/objectExpected.js +9 -8
  39. package/lib/error/objectParameter.js +12 -11
  40. package/lib/error/overwriteModel.js +7 -6
  41. package/lib/error/parallelSave.js +11 -8
  42. package/lib/error/parallelValidate.js +9 -7
  43. package/lib/error/serverSelection.js +1 -0
  44. package/lib/error/setOptionError.js +11 -9
  45. package/lib/error/strict.js +12 -10
  46. package/lib/error/strictPopulate.js +11 -9
  47. package/lib/error/syncIndexes.js +2 -2
  48. package/lib/error/validation.js +11 -17
  49. package/lib/error/validator.js +9 -8
  50. package/lib/error/version.js +12 -10
  51. package/lib/filters/operators.js +8 -0
  52. package/lib/helpers/aggregate/prepareDiscriminatorPipeline.js +4 -4
  53. package/lib/helpers/buildMiddlewareFilter.js +42 -0
  54. package/lib/helpers/clone.js +121 -35
  55. package/lib/helpers/common.js +7 -7
  56. package/lib/helpers/cursor/eachAsync.js +14 -11
  57. package/lib/helpers/cursor/waitForInitialization.js +17 -0
  58. package/lib/helpers/discriminator/applyEmbeddedDiscriminators.js +36 -0
  59. package/lib/helpers/discriminator/areDiscriminatorValuesEqual.js +1 -1
  60. package/lib/helpers/discriminator/getConstructor.js +9 -6
  61. package/lib/helpers/discriminator/getDiscriminatorByKey.js +1 -1
  62. package/lib/helpers/discriminator/getDiscriminatorByValue.js +1 -1
  63. package/lib/helpers/discriminator/getDiscriminatorValueFromFilter.js +30 -0
  64. package/lib/helpers/discriminator/getSchemaDiscriminatorByValue.js +1 -1
  65. package/lib/helpers/discriminator/mergeDiscriminatorSchema.js +41 -9
  66. package/lib/helpers/document/applyDefaults.js +82 -14
  67. package/lib/helpers/document/applyTimestamps.js +106 -0
  68. package/lib/helpers/document/applyVirtuals.js +147 -0
  69. package/lib/helpers/document/cleanModifiedSubpaths.js +14 -4
  70. package/lib/helpers/document/compile.js +20 -15
  71. package/lib/helpers/document/getDeepestSubdocumentForPath.js +38 -0
  72. package/lib/helpers/document/getEmbeddedDiscriminatorPath.js +6 -3
  73. package/lib/helpers/document/handleSpreadDoc.js +2 -1
  74. package/lib/helpers/document/isInPathsToSave.js +24 -0
  75. package/lib/helpers/document/toObjectRecursive.js +49 -0
  76. package/lib/helpers/get.js +1 -1
  77. package/lib/helpers/getDefaultBulkwriteResult.js +11 -20
  78. package/lib/helpers/getInheritedProperty.js +28 -0
  79. package/lib/helpers/getOwnProperty.js +19 -0
  80. package/lib/helpers/indexes/applySchemaCollation.js +1 -1
  81. package/lib/helpers/indexes/decorateDiscriminatorIndexOptions.js +1 -1
  82. package/lib/helpers/indexes/getRelatedIndexes.js +8 -4
  83. package/lib/helpers/indexes/isDefaultIdIndex.js +1 -1
  84. package/lib/helpers/indexes/isIndexEqual.js +13 -12
  85. package/lib/helpers/indexes/isIndexSpecEqual.js +32 -0
  86. package/lib/helpers/indexes/isTimeseriesIndex.js +16 -0
  87. package/lib/helpers/isBsonType.js +3 -6
  88. package/lib/helpers/isMongooseDocument.js +24 -0
  89. package/lib/helpers/isMongooseObject.js +6 -4
  90. package/lib/helpers/isObject.js +2 -2
  91. package/lib/helpers/isPOJO.js +12 -0
  92. package/lib/helpers/isSimpleValidator.js +2 -2
  93. package/lib/helpers/minimize.js +41 -0
  94. package/lib/helpers/model/applyDefaultsToPOJO.js +2 -2
  95. package/lib/helpers/model/applyHooks.js +72 -54
  96. package/lib/helpers/model/applyMethods.js +3 -3
  97. package/lib/helpers/model/applyStaticHooks.js +20 -50
  98. package/lib/helpers/model/castBulkWrite.js +278 -172
  99. package/lib/helpers/model/decorateBulkWriteResult.js +8 -0
  100. package/lib/helpers/model/discriminator.js +77 -21
  101. package/lib/helpers/omitUndefined.js +20 -0
  102. package/lib/helpers/parallelLimit.js +61 -34
  103. package/lib/helpers/path/setDottedPath.js +1 -1
  104. package/lib/helpers/pathTrie.js +167 -0
  105. package/lib/helpers/pluralize.js +5 -4
  106. package/lib/helpers/populate/assignRawDocsToIdStructure.js +12 -7
  107. package/lib/helpers/populate/assignVals.js +46 -21
  108. package/lib/helpers/populate/createPopulateQueryFilter.js +13 -5
  109. package/lib/helpers/populate/getModelsMapForPopulate.js +250 -108
  110. package/lib/helpers/populate/getSchemaTypes.js +27 -30
  111. package/lib/helpers/populate/getVirtual.js +31 -0
  112. package/lib/helpers/populate/markArraySubdocsPopulated.js +6 -4
  113. package/lib/helpers/populate/modelNamesFromRefPath.js +11 -5
  114. package/lib/helpers/populate/removeDeselectedForeignField.js +3 -2
  115. package/lib/helpers/populate/setInheritedReadOptions.js +21 -0
  116. package/lib/helpers/populate/setPopulatedVirtualValue.js +33 -0
  117. package/lib/helpers/populate/splitPopulateQuery.js +81 -0
  118. package/lib/helpers/printJestWarning.js +1 -1
  119. package/lib/helpers/processConnectionOptions.js +7 -2
  120. package/lib/helpers/projection/applyProjection.js +8 -2
  121. package/lib/helpers/projection/hasIncludedChildren.js +1 -1
  122. package/lib/helpers/projection/isExclusive.js +8 -6
  123. package/lib/helpers/projection/isInclusive.js +2 -1
  124. package/lib/helpers/projection/isPathExcluded.js +3 -3
  125. package/lib/helpers/projection/isPathSelectedInclusive.js +1 -11
  126. package/lib/helpers/projection/isSubpath.js +1 -1
  127. package/lib/helpers/projection/parseProjection.js +9 -4
  128. package/lib/helpers/query/applyGlobalOption.js +9 -9
  129. package/lib/helpers/query/cast$expr.js +52 -23
  130. package/lib/helpers/query/castFilterPath.js +22 -22
  131. package/lib/helpers/query/castUpdate.js +207 -79
  132. package/lib/helpers/query/cloneMongooseOptions.js +44 -0
  133. package/lib/helpers/query/getEmbeddedDiscriminatorPath.js +27 -13
  134. package/lib/helpers/query/handleImmutable.js +18 -2
  135. package/lib/helpers/query/handleReadPreferenceAliases.js +23 -0
  136. package/lib/helpers/query/sanitizeFilter.js +3 -2
  137. package/lib/helpers/query/selectPopulatedFields.js +13 -0
  138. package/lib/helpers/query/validOps.js +1 -22
  139. package/lib/helpers/schema/applyPlugins.js +2 -2
  140. package/lib/helpers/schema/applyReadConcern.js +20 -0
  141. package/lib/helpers/schema/applyWriteConcern.js +12 -3
  142. package/lib/helpers/schema/cleanPositionalOperators.js +5 -3
  143. package/lib/helpers/schema/getIndexes.js +20 -13
  144. package/lib/helpers/schema/getKeysInSchemaOrder.js +13 -16
  145. package/lib/helpers/schema/getPath.js +11 -3
  146. package/lib/helpers/schema/getSubdocumentStrictValue.js +32 -0
  147. package/lib/helpers/schema/handleIdOption.js +1 -1
  148. package/lib/helpers/schema/idGetter.js +7 -2
  149. package/lib/helpers/schema/merge.js +9 -1
  150. package/lib/helpers/schematype/getConditionalHandler.js +23 -0
  151. package/lib/helpers/schematype/handleImmutable.js +1 -1
  152. package/lib/helpers/setDefaultsOnInsert.js +85 -43
  153. package/lib/helpers/symbols.js +4 -4
  154. package/lib/helpers/timestamps/setDocumentTimestamps.js +2 -2
  155. package/lib/helpers/timestamps/setupTimestamps.js +69 -37
  156. package/lib/helpers/update/applyTimestampsToChildren.js +1 -1
  157. package/lib/helpers/update/applyTimestampsToUpdate.js +53 -37
  158. package/lib/helpers/update/castArrayFilters.js +68 -29
  159. package/lib/helpers/update/decorateUpdateWithVersionKey.js +35 -0
  160. package/lib/helpers/update/modifiedPaths.js +2 -2
  161. package/lib/helpers/update/removeUnusedArrayFilters.js +11 -2
  162. package/lib/helpers/updateValidators.js +87 -128
  163. package/lib/index.js +6 -1320
  164. package/lib/internal.js +7 -1
  165. package/lib/model.js +2587 -2618
  166. package/lib/modifiedPathsSnapshot.js +9 -0
  167. package/lib/mongoose.js +1456 -0
  168. package/lib/options/saveOptions.js +2 -0
  169. package/lib/options/{SchemaArrayOptions.js → schemaArrayOptions.js} +16 -5
  170. package/lib/options/{SchemaBufferOptions.js → schemaBufferOptions.js} +2 -2
  171. package/lib/options/{SchemaDateOptions.js → schemaDateOptions.js} +1 -1
  172. package/lib/options/{SchemaDocumentArrayOptions.js → schemaDocumentArrayOptions.js} +24 -1
  173. package/lib/options/{SchemaMapOptions.js → schemaMapOptions.js} +1 -1
  174. package/lib/options/{SchemaNumberOptions.js → schemaNumberOptions.js} +5 -5
  175. package/lib/options/{SchemaObjectIdOptions.js → schemaObjectIdOptions.js} +4 -4
  176. package/lib/options/{SchemaStringOptions.js → schemaStringOptions.js} +10 -10
  177. package/lib/options/schemaSubdocumentOptions.js +89 -0
  178. package/lib/options/{SchemaTypeOptions.js → schemaTypeOptions.js} +28 -14
  179. package/lib/options/schemaUnionOptions.js +32 -0
  180. package/lib/options/{VirtualOptions.js → virtualOptions.js} +13 -13
  181. package/lib/options.js +4 -1
  182. package/lib/plugins/index.js +0 -2
  183. package/lib/plugins/saveSubdocs.js +85 -50
  184. package/lib/plugins/sharding.js +43 -15
  185. package/lib/plugins/trackTransaction.js +46 -34
  186. package/lib/query.js +1844 -1909
  187. package/lib/{queryhelpers.js → queryHelpers.js} +184 -81
  188. package/lib/schema/array.js +229 -169
  189. package/lib/schema/bigint.js +281 -0
  190. package/lib/schema/boolean.js +90 -26
  191. package/lib/schema/buffer.js +119 -50
  192. package/lib/schema/date.js +102 -38
  193. package/lib/schema/decimal128.js +88 -37
  194. package/lib/schema/{documentarray.js → documentArray.js} +259 -151
  195. package/lib/schema/documentArrayElement.js +180 -0
  196. package/lib/schema/double.js +244 -0
  197. package/lib/schema/index.js +12 -19
  198. package/lib/schema/int32.js +288 -0
  199. package/lib/schema/map.js +129 -20
  200. package/lib/schema/mixed.js +40 -26
  201. package/lib/schema/number.js +128 -51
  202. package/lib/schema/{objectid.js → objectId.js} +89 -47
  203. package/lib/schema/operators/exists.js +1 -1
  204. package/lib/schema/operators/geospatial.js +2 -2
  205. package/lib/schema/operators/text.js +4 -4
  206. package/lib/schema/string.js +125 -66
  207. package/lib/schema/subdocument.js +443 -0
  208. package/lib/schema/symbols.js +2 -0
  209. package/lib/schema/union.js +167 -0
  210. package/lib/schema/uuid.js +90 -120
  211. package/lib/schema.js +1267 -388
  212. package/lib/{schematype.js → schemaType.js} +481 -246
  213. package/lib/standardSchema/convertErrorToIssues.js +20 -0
  214. package/lib/{statemachine.js → stateMachine.js} +66 -17
  215. package/lib/tracing.js +38 -0
  216. package/lib/types/array/index.js +13 -10
  217. package/lib/types/array/methods/index.js +243 -63
  218. package/lib/types/{ArraySubdocument.js → arraySubdocument.js} +35 -14
  219. package/lib/types/buffer.js +31 -14
  220. package/lib/types/decimal128.js +1 -1
  221. package/lib/types/{DocumentArray → documentArray}/index.js +13 -13
  222. package/lib/types/{DocumentArray → documentArray}/methods/index.js +197 -31
  223. package/lib/types/double.js +13 -0
  224. package/lib/types/index.js +5 -2
  225. package/lib/types/map.js +62 -25
  226. package/lib/types/objectid.js +2 -2
  227. package/lib/types/subdocument.js +79 -58
  228. package/lib/types/uuid.js +13 -0
  229. package/lib/utils.js +201 -155
  230. package/lib/{validoptions.js → validOptions.js} +10 -2
  231. package/lib/{virtualtype.js → virtualType.js} +47 -18
  232. package/package.json +75 -92
  233. package/types/aggregate.d.ts +31 -7
  234. package/types/augmentations.d.ts +2 -2
  235. package/types/collection.d.ts +21 -16
  236. package/types/connection.d.ts +82 -27
  237. package/types/cursor.d.ts +15 -10
  238. package/types/document.d.ts +137 -56
  239. package/types/error.d.ts +11 -6
  240. package/types/expressions.d.ts +33 -2
  241. package/types/index.d.ts +805 -190
  242. package/types/indexes.d.ts +85 -13
  243. package/types/inferhydrateddoctype.d.ts +151 -0
  244. package/types/inferrawdoctype.d.ts +201 -0
  245. package/types/inferschematype.d.ts +287 -128
  246. package/types/middlewares.d.ts +50 -7
  247. package/types/models.d.ts +1555 -268
  248. package/types/mongooseoptions.d.ts +56 -7
  249. package/types/pipelinestage.d.ts +42 -3
  250. package/types/populate.d.ts +63 -1
  251. package/types/query.d.ts +592 -255
  252. package/types/schemaoptions.d.ts +78 -12
  253. package/types/schematypes.d.ts +254 -65
  254. package/types/session.d.ts +0 -4
  255. package/types/tracing.d.ts +10 -0
  256. package/types/types.d.ts +25 -8
  257. package/types/utility.d.ts +329 -30
  258. package/types/validation.d.ts +19 -14
  259. package/types/virtuals.d.ts +10 -10
  260. package/.eslintrc.js +0 -232
  261. package/.mocharc.yml +0 -4
  262. package/browser.js +0 -8
  263. package/lgtm.yml +0 -12
  264. package/lib/browser.js +0 -158
  265. package/lib/browserDocument.js +0 -101
  266. package/lib/cursor/ChangeStream.js +0 -154
  267. package/lib/cursor/QueryCursor.js +0 -545
  268. package/lib/document_provider.js +0 -30
  269. package/lib/drivers/browser/ReadPreference.js +0 -7
  270. package/lib/drivers/browser/binary.js +0 -14
  271. package/lib/drivers/browser/decimal128.js +0 -7
  272. package/lib/drivers/browser/index.js +0 -16
  273. package/lib/drivers/browser/objectid.js +0 -29
  274. package/lib/drivers/node-mongodb-native/ReadPreference.js +0 -47
  275. package/lib/drivers/node-mongodb-native/binary.js +0 -10
  276. package/lib/drivers/node-mongodb-native/decimal128.js +0 -7
  277. package/lib/drivers/node-mongodb-native/objectid.js +0 -16
  278. package/lib/error/disconnected.js +0 -33
  279. package/lib/helpers/printStrictQueryWarning.js +0 -11
  280. package/lib/helpers/promiseOrCallback.js +0 -55
  281. package/lib/helpers/query/applyQueryMiddleware.js +0 -79
  282. package/lib/helpers/query/completeMany.js +0 -52
  283. package/lib/helpers/query/wrapThunk.js +0 -36
  284. package/lib/options/SchemaSubdocumentOptions.js +0 -42
  285. package/lib/options/removeOptions.js +0 -14
  286. package/lib/plugins/removeSubdocs.js +0 -31
  287. package/lib/plugins/validateBeforeSave.js +0 -45
  288. package/lib/promise_provider.js +0 -49
  289. package/lib/schema/DocumentArrayElement.js +0 -100
  290. package/lib/schema/SubdocumentPath.js +0 -369
  291. package/scripts/build-browser.js +0 -18
  292. package/scripts/create-tarball.js +0 -7
  293. package/scripts/generateSearch.js +0 -154
  294. package/scripts/tsc-diagnostics-check.js +0 -15
  295. package/tools/auth.js +0 -31
  296. package/tools/repl.js +0 -35
  297. package/tools/sharded.js +0 -46
  298. package/tsconfig.json +0 -9
  299. /package/lib/{connectionstate.js → connectionState.js} +0 -0
  300. /package/lib/helpers/populate/{SkipPopulateValue.js → skipPopulateValue.js} +0 -0
  301. /package/lib/options/{PopulateOptions.js → populateOptions.js} +0 -0
  302. /package/lib/types/{DocumentArray → documentArray}/isMongooseDocumentArray.js +0 -0
@@ -8,32 +8,42 @@ const EventEmitter = require('events').EventEmitter;
8
8
  const Subdocument = require('./subdocument');
9
9
  const utils = require('../utils');
10
10
 
11
+ const arrayParentSymbol = require('../helpers/symbols').arrayParentSymbol;
11
12
  const documentArrayParent = require('../helpers/symbols').documentArrayParent;
12
13
 
13
14
  /**
14
15
  * A constructor.
15
16
  *
16
- * @param {Object} obj js object returned from the db
17
+ * @param {object} obj js object returned from the db
17
18
  * @param {MongooseDocumentArray} parentArr the parent array of this document
18
- * @param {Boolean} skipId
19
- * @param {Object} fields
20
- * @param {Number} index
19
+ * @param {boolean} skipId
20
+ * @param {object} fields
21
+ * @param {number} index
21
22
  * @inherits Document
22
23
  * @api private
23
24
  */
24
25
 
25
26
  function ArraySubdocument(obj, parentArr, skipId, fields, index) {
27
+ let parent;
26
28
  if (utils.isMongooseDocumentArray(parentArr)) {
27
29
  this.__parentArray = parentArr;
28
- this[documentArrayParent] = parentArr.$parent();
30
+ parent = parentArr[arrayParentSymbol];
29
31
  } else {
30
32
  this.__parentArray = undefined;
31
- this[documentArrayParent] = undefined;
32
33
  }
34
+ this[documentArrayParent] = parent;
33
35
  this.$setIndex(index);
34
- this.$__parent = this[documentArrayParent];
36
+ this.$__parent = parent;
35
37
 
36
- Subdocument.call(this, obj, fields, this[documentArrayParent], skipId, { isNew: true });
38
+ const options = { isNew: true };
39
+ if (parent != null && 'defaults' in parent.$__) {
40
+ options.defaults = parent.$__.defaults;
41
+ }
42
+ if (typeof skipId === 'object' && skipId != null) {
43
+ Object.assign(options, skipId);
44
+ }
45
+
46
+ Subdocument.call(this, obj, fields, null, options);
37
47
  }
38
48
 
39
49
  /*!
@@ -65,7 +75,7 @@ for (const i in EventEmitter.prototype) {
65
75
  ArraySubdocument.prototype.$setIndex = function(index) {
66
76
  this.__index = index;
67
77
 
68
- if (this.$__ != null && this.$__.validationError != null) {
78
+ if (this.$__?.validationError != null) {
69
79
  const keys = Object.keys(this.$__.validationError.errors);
70
80
  for (const key of keys) {
71
81
  this.invalidate(key, this.$__.validationError.errors[key]);
@@ -99,9 +109,9 @@ ArraySubdocument.prototype.$__removeFromParent = function() {
99
109
  /**
100
110
  * Returns the full path to this document. If optional `path` is passed, it is appended to the full path.
101
111
  *
102
- * @param {String} [path]
103
- * @param {Boolean} [skipIndex] Skip adding the array index. For example `arr.foo` instead of `arr.0.foo`.
104
- * @return {String}
112
+ * @param {string} [path]
113
+ * @param {boolean} [skipIndex] Skip adding the array index. For example `arr.foo` instead of `arr.0.foo`.
114
+ * @return {string}
105
115
  * @api private
106
116
  * @method $__fullPath
107
117
  * @memberOf ArraySubdocument
@@ -137,7 +147,7 @@ ArraySubdocument.prototype.$__fullPath = function(path, skipIndex) {
137
147
  */
138
148
 
139
149
  ArraySubdocument.prototype.$__pathRelativeToParent = function(path, skipIndex) {
140
- if (this.__index == null || (!this.__parentArray || !this.__parentArray.$path)) {
150
+ if (this.__index == null || !this.__parentArray?.$path) {
141
151
  return null;
142
152
  }
143
153
  if (skipIndex) {
@@ -161,6 +171,17 @@ ArraySubdocument.prototype.$parent = function() {
161
171
  return this[documentArrayParent];
162
172
  };
163
173
 
174
+ /*!
175
+ * Sets this sub-documents parent document.
176
+ *
177
+ * @api private
178
+ */
179
+
180
+ ArraySubdocument.prototype.$__setParent = function $__setParent(parent) {
181
+ this[documentArrayParent] = parent;
182
+ this.$__parent = parent;
183
+ };
184
+
164
185
  /**
165
186
  * Returns this subdocument's parent array.
166
187
  *
@@ -175,7 +196,7 @@ ArraySubdocument.prototype.$parent = function() {
175
196
  *
176
197
  * @api public
177
198
  * @method parentArray
178
- * @returns DocumentArray
199
+ * @returns {DocumentArray}
179
200
  */
180
201
 
181
202
  ArraySubdocument.prototype.parentArray = function() {
@@ -4,7 +4,8 @@
4
4
 
5
5
  'use strict';
6
6
 
7
- const Binary = require('../driver').get().Binary;
7
+ const Binary = require('mongodb/lib/bson').Binary;
8
+ const UUID = require('mongodb/lib/bson').UUID;
8
9
  const utils = require('../utils');
9
10
 
10
11
  /**
@@ -13,8 +14,8 @@ const utils = require('../utils');
13
14
  * Values always have to be passed to the constructor to initialize.
14
15
  *
15
16
  * @param {Buffer} value
16
- * @param {String} encode
17
- * @param {Number} offset
17
+ * @param {string} encode
18
+ * @param {number} offset
18
19
  * @api private
19
20
  * @inherits Buffer https://nodejs.org/api/buffer.html
20
21
  * @see https://bit.ly/f6CnZU
@@ -120,7 +121,7 @@ MongooseBuffer.mixin = {
120
121
  *
121
122
  * `Buffer#copy` does not mark `target` as modified so you must copy from a `MongooseBuffer` for it to work as expected. This is a work around since `copy` modifies the target, not this.
122
123
  *
123
- * @return {Number} The number of bytes copied.
124
+ * @return {number} The number of bytes copied.
124
125
  * @param {Buffer} target
125
126
  * @method copy
126
127
  * @memberOf MongooseBuffer.mixin
@@ -130,7 +131,7 @@ MongooseBuffer.mixin = {
130
131
  copy: function(target) {
131
132
  const ret = Buffer.prototype.copy.apply(this, arguments);
132
133
 
133
- if (target && target.isMongooseBuffer) {
134
+ if (target?.isMongooseBuffer) {
134
135
  target._markModified();
135
136
  }
136
137
 
@@ -168,14 +169,14 @@ utils.each(
168
169
  *
169
170
  * #### SubTypes:
170
171
  *
171
- * const bson = require('bson')
172
- * bson.BSON_BINARY_SUBTYPE_DEFAULT
173
- * bson.BSON_BINARY_SUBTYPE_FUNCTION
174
- * bson.BSON_BINARY_SUBTYPE_BYTE_ARRAY
175
- * bson.BSON_BINARY_SUBTYPE_UUID
176
- * bson.BSON_BINARY_SUBTYPE_MD5
177
- * bson.BSON_BINARY_SUBTYPE_USER_DEFINED
178
- * doc.buffer.toObject(bson.BSON_BINARY_SUBTYPE_USER_DEFINED);
172
+ * const mongodb = require('mongodb')
173
+ * mongodb.BSON.BSON_BINARY_SUBTYPE_DEFAULT
174
+ * mongodb.BSON.BSON_BINARY_SUBTYPE_FUNCTION
175
+ * mongodb.BSON.BSON_BINARY_SUBTYPE_BYTE_ARRAY
176
+ * mongodb.BSON.BSON_BINARY_SUBTYPE_UUID
177
+ * mongodb.BSON.BSON_BINARY_SUBTYPE_MD5
178
+ * mongodb.BSON.BSON_BINARY_SUBTYPE_USER_DEFINED
179
+ * doc.buffer.toObject(mongodb.BSON.BSON_BINARY_SUBTYPE_USER_DEFINED);
179
180
  *
180
181
  * @see bsonspec https://bsonspec.org/#/specification
181
182
  * @param {Hex} [subtype]
@@ -207,11 +208,27 @@ MongooseBuffer.mixin.toBSON = function() {
207
208
  return new Binary(this, this._subtype || 0);
208
209
  };
209
210
 
211
+ /**
212
+ * Converts this buffer to a UUID. Throws an error if subtype is not 4.
213
+ *
214
+ * @return {UUID}
215
+ * @api public
216
+ * @method toUUID
217
+ * @memberOf MongooseBuffer
218
+ */
219
+
220
+ MongooseBuffer.mixin.toUUID = function() {
221
+ if (this._subtype !== 4) {
222
+ throw new Error('Cannot convert a Buffer with subtype ' + this._subtype + ' to a UUID');
223
+ }
224
+ return new UUID(this);
225
+ };
226
+
210
227
  /**
211
228
  * Determines if this buffer is equals to `other` buffer
212
229
  *
213
230
  * @param {Buffer} other
214
- * @return {Boolean}
231
+ * @return {boolean}
215
232
  * @method equals
216
233
  * @memberOf MongooseBuffer
217
234
  */
@@ -10,4 +10,4 @@
10
10
 
11
11
  'use strict';
12
12
 
13
- module.exports = require('../driver').get().Decimal128;
13
+ module.exports = require('mongodb/lib/bson').Decimal128;
@@ -6,7 +6,6 @@
6
6
 
7
7
  const ArrayMethods = require('../array/methods');
8
8
  const DocumentArrayMethods = require('./methods');
9
- const Document = require('../../document');
10
9
 
11
10
  const arrayAtomicsSymbol = require('../../helpers/symbols').arrayAtomicsSymbol;
12
11
  const arrayAtomicsBackupSymbol = require('../../helpers/symbols').arrayAtomicsBackupSymbol;
@@ -20,7 +19,7 @@ const numberRE = /^\d+$/;
20
19
  * DocumentArray constructor
21
20
  *
22
21
  * @param {Array} values
23
- * @param {String} path the path to this array
22
+ * @param {string} path the path to this array
24
23
  * @param {Document} doc parent document
25
24
  * @api private
26
25
  * @return {MongooseDocumentArray}
@@ -28,7 +27,7 @@ const numberRE = /^\d+$/;
28
27
  * @see https://bit.ly/f6CnZU
29
28
  */
30
29
 
31
- function MongooseDocumentArray(values, path, doc) {
30
+ function MongooseDocumentArray(values, path, doc, schematype) {
32
31
  const __array = [];
33
32
 
34
33
  const internals = {
@@ -51,11 +50,7 @@ function MongooseDocumentArray(values, path, doc) {
51
50
  internals[arrayPathSymbol] = path;
52
51
  internals.__array = __array;
53
52
 
54
- // Because doc comes from the context of another function, doc === global
55
- // can happen if there was a null somewhere up the chain (see #3020 && #3034)
56
- // RB Jun 17, 2015 updated to check for presence of expected paths instead
57
- // to make more proof against unusual node environments
58
- if (doc && doc instanceof Document) {
53
+ if (doc?.$__) {
59
54
  internals[arrayParentSymbol] = doc;
60
55
  internals[arraySchemaSymbol] = doc.$__schema.path(path);
61
56
 
@@ -66,7 +61,7 @@ function MongooseDocumentArray(values, path, doc) {
66
61
  while (internals[arraySchemaSymbol] != null &&
67
62
  internals[arraySchemaSymbol].$isMongooseArray &&
68
63
  !internals[arraySchemaSymbol].$isMongooseDocumentArray) {
69
- internals[arraySchemaSymbol] = internals[arraySchemaSymbol].casterConstructor;
64
+ internals[arraySchemaSymbol] = internals[arraySchemaSymbol].embeddedSchemaType;
70
65
  }
71
66
  }
72
67
 
@@ -78,13 +73,16 @@ function MongooseDocumentArray(values, path, doc) {
78
73
  prop === 'isMongooseDocumentArrayProxy') {
79
74
  return true;
80
75
  }
81
- if (internals.hasOwnProperty(prop)) {
76
+ if (Object.hasOwn(internals, prop)) {
82
77
  return internals[prop];
83
78
  }
84
- if (DocumentArrayMethods.hasOwnProperty(prop)) {
79
+ if (Object.hasOwn(DocumentArrayMethods, prop)) {
85
80
  return DocumentArrayMethods[prop];
86
81
  }
87
- if (ArrayMethods.hasOwnProperty(prop)) {
82
+ if (schematype?.virtuals && Object.hasOwn(schematype.virtuals, prop)) {
83
+ return schematype.virtuals[prop].applyGetters(undefined, target);
84
+ }
85
+ if (Object.hasOwn(ArrayMethods, prop)) {
88
86
  return ArrayMethods[prop];
89
87
  }
90
88
 
@@ -93,8 +91,10 @@ function MongooseDocumentArray(values, path, doc) {
93
91
  set: function(target, prop, value) {
94
92
  if (typeof prop === 'string' && numberRE.test(prop)) {
95
93
  DocumentArrayMethods.set.call(proxy, prop, value, false);
96
- } else if (internals.hasOwnProperty(prop)) {
94
+ } else if (Object.hasOwn(internals, prop)) {
97
95
  internals[prop] = value;
96
+ } else if (schematype?.virtuals && Object.hasOwn(schematype.virtuals, prop)) {
97
+ schematype.virtuals[prop].applySetters(value, target);
98
98
  } else {
99
99
  __array[prop] = value;
100
100
  }
@@ -2,7 +2,6 @@
2
2
 
3
3
  const ArrayMethods = require('../../array/methods');
4
4
  const Document = require('../../../document');
5
- const castObjectId = require('../../../cast/objectid');
6
5
  const getDiscriminatorByKey = require('../../../helpers/discriminator/getDiscriminatorByKey');
7
6
  const getDiscriminatorByValue = require('../../../helpers/discriminator/getDiscriminatorByValue');
8
7
  const internalToObjectOptions = require('../../../options').internalToObjectOptions;
@@ -14,6 +13,9 @@ const arrayPathSymbol = require('../../../helpers/symbols').arrayPathSymbol;
14
13
  const arraySchemaSymbol = require('../../../helpers/symbols').arraySchemaSymbol;
15
14
  const documentArrayParent = require('../../../helpers/symbols').documentArrayParent;
16
15
 
16
+ const _baseReverse = Array.prototype.reverse;
17
+ const _baseToString = Array.prototype.toString;
18
+
17
19
  const methods = {
18
20
  /*!
19
21
  * ignore
@@ -23,6 +25,15 @@ const methods = {
23
25
  return this.toObject(internalToObjectOptions);
24
26
  },
25
27
 
28
+ toString() {
29
+ return _baseToString.call(this.__array.map(subdoc => {
30
+ if (subdoc?.$__ != null) {
31
+ return subdoc.toString();
32
+ }
33
+ return subdoc;
34
+ }));
35
+ },
36
+
26
37
  /*!
27
38
  * ignore
28
39
  */
@@ -31,6 +42,13 @@ const methods = {
31
42
  return this[arrayParentSymbol];
32
43
  },
33
44
 
45
+ /*!
46
+ * ignore
47
+ */
48
+ $schemaType() {
49
+ return this[arraySchemaSymbol];
50
+ },
51
+
34
52
  /**
35
53
  * Overrides MongooseArray#cast
36
54
  *
@@ -39,17 +57,17 @@ const methods = {
39
57
  * @memberOf MongooseDocumentArray
40
58
  */
41
59
 
42
- _cast(value, index) {
60
+ _cast(value, index, options) {
43
61
  if (this[arraySchemaSymbol] == null) {
44
62
  return value;
45
63
  }
46
- let Constructor = this[arraySchemaSymbol].casterConstructor;
64
+ let Constructor = this[arraySchemaSymbol].Constructor;
47
65
  const isInstance = Constructor.$isMongooseDocumentArray ?
48
66
  utils.isMongooseDocumentArray(value) :
49
67
  value instanceof Constructor;
50
68
  if (isInstance ||
51
69
  // Hack re: #5001, see #5005
52
- (value && value.constructor && value.constructor.baseCasterConstructor === Constructor)) {
70
+ value?.constructor?.baseCasterConstructor === Constructor) {
53
71
  if (!(value[documentArrayParent] && value.__parentArray)) {
54
72
  // value may have been created using array.create()
55
73
  value[documentArrayParent] = this[arrayParentSymbol];
@@ -59,7 +77,7 @@ const methods = {
59
77
  return value;
60
78
  }
61
79
 
62
- if (value === undefined || value === null) {
80
+ if (value == null) {
63
81
  return null;
64
82
  }
65
83
 
@@ -67,7 +85,7 @@ const methods = {
67
85
  // only objects are permitted so we can safely assume that
68
86
  // non-objects are to be interpreted as _id
69
87
  if (Buffer.isBuffer(value) ||
70
- isBsonType(value, 'ObjectID') || !utils.isObject(value)) {
88
+ isBsonType(value, 'ObjectId') || !utils.isObject(value)) {
71
89
  value = { _id: value };
72
90
  }
73
91
 
@@ -92,7 +110,7 @@ const methods = {
92
110
  if (Constructor.$isMongooseDocumentArray) {
93
111
  return Constructor.cast(value, this, undefined, undefined, index);
94
112
  }
95
- const ret = new Constructor(value, this, undefined, undefined, index);
113
+ const ret = new Constructor(value, this, options, undefined, index);
96
114
  ret.isNew = true;
97
115
  return ret;
98
116
  },
@@ -105,24 +123,37 @@ const methods = {
105
123
  * const embeddedDoc = m.array.id(some_id);
106
124
  *
107
125
  * @return {EmbeddedDocument|null} the subdocument or null if not found.
108
- * @param {ObjectId|String|Number|Buffer} id
109
- * @TODO cast to the _id based on schema for proper comparison
126
+ * @param {ObjectId|string|number|Buffer} id
110
127
  * @method id
111
128
  * @api public
112
129
  * @memberOf MongooseDocumentArray
113
130
  */
114
131
 
115
132
  id(id) {
116
- let casted;
117
- let sid;
118
- let _id;
133
+ if (id == null) {
134
+ return null;
135
+ }
119
136
 
120
- try {
121
- casted = castObjectId(id).toString();
122
- } catch (e) {
123
- casted = null;
137
+ const schemaType = this[arraySchemaSymbol];
138
+ let idSchemaType = null;
139
+
140
+ if (schemaType?.schema) {
141
+ idSchemaType = schemaType.schema.path('_id');
142
+ } else if (schemaType?.casterConstructor?.schema) {
143
+ idSchemaType = schemaType.casterConstructor.schema.path('_id');
144
+ }
145
+
146
+ let castedId = null;
147
+ if (idSchemaType) {
148
+ try {
149
+ castedId = idSchemaType.cast(id);
150
+ } catch {
151
+ // ignore error
152
+ }
124
153
  }
125
154
 
155
+ let _id;
156
+
126
157
  for (const val of this) {
127
158
  if (!val) {
128
159
  continue;
@@ -130,18 +161,20 @@ const methods = {
130
161
 
131
162
  _id = val.get('_id');
132
163
 
133
- if (_id === null || typeof _id === 'undefined') {
164
+ if (_id == null) {
134
165
  continue;
135
166
  } else if (_id instanceof Document) {
136
- sid || (sid = String(id));
137
- if (sid == _id._id) {
167
+ _id = _id.get('_id');
168
+ if (castedId != null && utils.deepEqual(castedId, _id)) {
138
169
  return val;
139
- }
140
- } else if (!isBsonType(id, 'ObjectID') && !isBsonType(_id, 'ObjectID')) {
141
- if (id == _id || utils.deepEqual(id, _id)) {
170
+ } else if (castedId == null && (id == _id || utils.deepEqual(id, _id))) {
171
+ // Backwards compat: compare user-specified param to _id using loose equality
142
172
  return val;
143
173
  }
144
- } else if (casted == _id) {
174
+ } else if (castedId != null && utils.deepEqual(castedId, _id)) {
175
+ return val;
176
+ } else if (castedId == null && (_id == id || utils.deepEqual(id, _id))) {
177
+ // Backwards compat: compare user-specified param to _id using loose equality
145
178
  return val;
146
179
  }
147
180
  }
@@ -156,7 +189,7 @@ const methods = {
156
189
  *
157
190
  * _Each sub-document is converted to a plain object by calling its `#toObject` method._
158
191
  *
159
- * @param {Object} [options] optional options to pass to each documents `toObject` method call during conversion
192
+ * @param {object} [options] optional options to pass to each documents `toObject` method call during conversion
160
193
  * @return {Array}
161
194
  * @method toObject
162
195
  * @api public
@@ -182,17 +215,66 @@ const methods = {
182
215
  },
183
216
 
184
217
  /**
185
- * Wraps [`Array#push`](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/push) with proper change tracking.
218
+ * Wraps [`MongooseArray#addToSet`](https://mongoosejs.com/docs/api/array.html#MongooseArray.prototype.addToSet())
219
+ * with proper change tracking.
220
+ *
221
+ * @param {...object} [args]
222
+ * @api public
223
+ * @method addToSet
224
+ * @memberOf MongooseDocumentArray
225
+ */
226
+
227
+ addToSet() {
228
+ // Arguments are cast before duplicates are skipped, so any value added
229
+ // after a skipped duplicate is cast with an index that is too high.
230
+ const ret = ArrayMethods.addToSet.apply(this, arguments);
231
+
232
+ _updateSubdocIndexes(this);
233
+
234
+ return ret;
235
+ },
236
+
237
+ /**
238
+ * Wraps [`Array#push`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/push) with proper change tracking.
186
239
  *
187
- * @param {...Object} [args]
240
+ * @param {...object} [args]
188
241
  * @api public
189
242
  * @method push
190
243
  * @memberOf MongooseDocumentArray
191
244
  */
192
245
 
193
246
  push() {
247
+ const shouldReindex = _shouldReindexAfterPush(arguments);
194
248
  const ret = ArrayMethods.push.apply(this, arguments);
195
249
 
250
+ if (shouldReindex) {
251
+ _updateSubdocIndexes(this);
252
+ }
253
+ _updateParentPopulated(this);
254
+
255
+ return ret;
256
+ },
257
+
258
+ /**
259
+ * Wraps [`Array#pop`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/pop) with proper change tracking.
260
+ * @api private
261
+ */
262
+
263
+ pop() {
264
+ const ret = ArrayMethods.pop.apply(this, arguments);
265
+
266
+ _updateParentPopulated(this);
267
+
268
+ return ret;
269
+ },
270
+
271
+ /*!
272
+ * ignore
273
+ */
274
+
275
+ $pop() {
276
+ const ret = ArrayMethods.$pop.apply(this, arguments);
277
+
196
278
  _updateParentPopulated(this);
197
279
 
198
280
  return ret;
@@ -201,7 +283,7 @@ const methods = {
201
283
  /**
202
284
  * Pulls items from the array atomically.
203
285
  *
204
- * @param {...Object} [args]
286
+ * @param {...object} [args]
205
287
  * @api public
206
288
  * @method pull
207
289
  * @memberOf MongooseDocumentArray
@@ -210,32 +292,96 @@ const methods = {
210
292
  pull() {
211
293
  const ret = ArrayMethods.pull.apply(this, arguments);
212
294
 
295
+ _updateSubdocIndexes(this);
213
296
  _updateParentPopulated(this);
214
297
 
215
298
  return ret;
216
299
  },
217
300
 
218
301
  /**
219
- * Wraps [`Array#shift`](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/unshift) with proper change tracking.
302
+ * Wraps [`Array#shift`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/shift) with proper change tracking.
220
303
  * @api private
221
304
  */
222
305
 
223
306
  shift() {
224
307
  const ret = ArrayMethods.shift.apply(this, arguments);
225
308
 
309
+ _updateSubdocIndexes(this);
310
+ _updateParentPopulated(this);
311
+
312
+ return ret;
313
+ },
314
+
315
+ /*!
316
+ * ignore
317
+ */
318
+
319
+ $shift() {
320
+ const ret = ArrayMethods.$shift.apply(this, arguments);
321
+
322
+ _updateSubdocIndexes(this);
226
323
  _updateParentPopulated(this);
227
324
 
228
325
  return ret;
229
326
  },
230
327
 
231
328
  /**
232
- * Wraps [`Array#splice`](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/splice) with proper change tracking and casting.
329
+ * Wraps [`Array#splice`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice) with proper change tracking and casting.
233
330
  * @api private
234
331
  */
235
332
 
236
333
  splice() {
237
334
  const ret = ArrayMethods.splice.apply(this, arguments);
238
335
 
336
+ _updateSubdocIndexes(this);
337
+ _updateParentPopulated(this);
338
+
339
+ return ret;
340
+ },
341
+
342
+ /**
343
+ * Wraps [`Array#reverse`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reverse)
344
+ * with proper change tracking.
345
+ * @api private
346
+ */
347
+
348
+ reverse() {
349
+ _baseReverse.call(this.__array);
350
+ this._registerAtomic('$set', this);
351
+
352
+ _updateSubdocIndexes(this);
353
+ _updateParentPopulated(this);
354
+
355
+ return this;
356
+ },
357
+
358
+ /**
359
+ * Wraps [`Array#sort`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort)
360
+ * with proper change tracking.
361
+ *
362
+ * @param {Function} [compareFunction]
363
+ * @api private
364
+ */
365
+
366
+ sort() {
367
+ const ret = ArrayMethods.sort.apply(this, arguments);
368
+
369
+ _updateSubdocIndexes(this);
370
+ _updateParentPopulated(this);
371
+
372
+ return ret;
373
+ },
374
+
375
+ /**
376
+ * Wraps [`Array#unshift`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/unshift)
377
+ * with proper change tracking.
378
+ * @api private
379
+ */
380
+
381
+ unshift() {
382
+ const ret = ArrayMethods.unshift.apply(this, arguments);
383
+
384
+ _updateSubdocIndexes(this);
239
385
  _updateParentPopulated(this);
240
386
 
241
387
  return ret;
@@ -258,14 +404,14 @@ const methods = {
258
404
  *
259
405
  * This is the same subdocument constructor used for casting.
260
406
  *
261
- * @param {Object} obj the value to cast to this arrays SubDocument schema
407
+ * @param {object} obj the value to cast to this arrays SubDocument schema
262
408
  * @method create
263
409
  * @api public
264
410
  * @memberOf MongooseDocumentArray
265
411
  */
266
412
 
267
413
  create(obj) {
268
- let Constructor = this[arraySchemaSymbol].casterConstructor;
414
+ let Constructor = this[arraySchemaSymbol].Constructor;
269
415
  if (obj &&
270
416
  Constructor.discriminators &&
271
417
  Constructor.schema &&
@@ -362,6 +508,26 @@ const methods = {
362
508
 
363
509
  module.exports = methods;
364
510
 
511
+ /*!
512
+ * ignore
513
+ */
514
+
515
+ function _updateSubdocIndexes(arr) {
516
+ const rawArray = utils.isMongooseArray(arr) ? arr.__array : arr;
517
+
518
+ for (let i = 0; i < rawArray.length; ++i) {
519
+ if (typeof rawArray[i]?.$setIndex === 'function') {
520
+ rawArray[i].$setIndex(i);
521
+ }
522
+ }
523
+ }
524
+
525
+ function _shouldReindexAfterPush(args) {
526
+ return args[0] != null &&
527
+ utils.hasUserDefinedProperty(args[0], '$each') &&
528
+ args[0].$position != null;
529
+ }
530
+
365
531
  /**
366
532
  * If this is a document array, each element may contain single
367
533
  * populated paths, so we need to modify the top-level document's
@@ -0,0 +1,13 @@
1
+ /**
2
+ * Double type constructor
3
+ *
4
+ * #### Example:
5
+ *
6
+ * const pi = new mongoose.Types.Double(3.1415);
7
+ *
8
+ * @constructor Double
9
+ */
10
+
11
+ 'use strict';
12
+
13
+ module.exports = require('mongodb/lib/bson').Double;