@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
@@ -1,13 +1,17 @@
1
1
  'use strict';
2
2
 
3
3
  const Document = require('../../../document');
4
- const ArraySubdocument = require('../../ArraySubdocument');
4
+ const ArraySubdocument = require('../../arraySubdocument');
5
+ const MongooseError = require('../../../error/mongooseError');
5
6
  const cleanModifiedSubpaths = require('../../../helpers/document/cleanModifiedSubpaths');
7
+ const clone = require('../../../helpers/clone');
6
8
  const internalToObjectOptions = require('../../../options').internalToObjectOptions;
7
9
  const mpath = require('mpath');
8
10
  const utils = require('../../../utils');
9
11
  const isBsonType = require('../../../helpers/isBsonType');
12
+ const UUID = require('mongodb/lib/bson').UUID;
10
13
 
14
+ const arrayAtomicsBackupSymbol = require('../../../helpers/symbols').arrayAtomicsBackupSymbol;
11
15
  const arrayAtomicsSymbol = require('../../../helpers/symbols').arrayAtomicsSymbol;
12
16
  const arrayParentSymbol = require('../../../helpers/symbols').arrayParentSymbol;
13
17
  const arrayPathSymbol = require('../../../helpers/symbols').arrayPathSymbol;
@@ -57,9 +61,9 @@ const methods = {
57
61
  val = val.toObject(opts);
58
62
  } else if (Array.isArray(val)) {
59
63
  val = this.toObject.call(val, opts);
60
- } else if (val != null && Array.isArray(val.$each)) {
64
+ } else if (Array.isArray(val?.$each)) {
61
65
  val.$each = this.toObject.call(val.$each, opts);
62
- } else if (val != null && typeof val.valueOf === 'function') {
66
+ } else if (typeof val?.valueOf === 'function') {
63
67
  val = val.valueOf();
64
68
  }
65
69
 
@@ -73,6 +77,36 @@ const methods = {
73
77
  return ret;
74
78
  },
75
79
 
80
+ /**
81
+ * Public API for getting atomics. Alias for $__getAtomics() that can be
82
+ * implemented by custom container types.
83
+ *
84
+ * @return {Array}
85
+ * @method getAtomics
86
+ * @memberOf MongooseArray
87
+ * @instance
88
+ * @api public
89
+ */
90
+
91
+ getAtomics() {
92
+ return this.$__getAtomics();
93
+ },
94
+
95
+ /**
96
+ * Clears all pending atomic operations. Called by Mongoose after save().
97
+ *
98
+ * @return {void}
99
+ * @method clearAtomics
100
+ * @memberOf MongooseArray
101
+ * @instance
102
+ * @api public
103
+ */
104
+
105
+ clearAtomics() {
106
+ this[arrayAtomicsBackupSymbol] = this[arrayAtomicsSymbol];
107
+ this[arrayAtomicsSymbol] = {};
108
+ },
109
+
76
110
  /*!
77
111
  * ignore
78
112
  */
@@ -97,13 +131,20 @@ const methods = {
97
131
  return this[arrayPathSymbol];
98
132
  },
99
133
 
134
+ /*!
135
+ * ignore
136
+ */
137
+ $schemaType() {
138
+ return this[arraySchemaSymbol];
139
+ },
140
+
100
141
  /**
101
142
  * Atomically shifts the array at most one time per document `save()`.
102
143
  *
103
144
  * #### Note:
104
145
  *
105
146
  * _Calling this multiple times on an array before saving sends the same command as calling it once._
106
- * _This update is implemented using the MongoDB [$pop](https://www.mongodb.org/display/DOCS/Updating/#Updating-%24pop) method which enforces this restriction._
147
+ * _This update is implemented using the MongoDB [$pop](https://www.mongodb.com/docs/manual/reference/operator/update/pop/) method which enforces this restriction._
107
148
  *
108
149
  * doc.array = [1,2,3];
109
150
  *
@@ -128,7 +169,7 @@ const methods = {
128
169
  * @memberOf MongooseArray
129
170
  * @instance
130
171
  * @method $shift
131
- * @see mongodb https://www.mongodb.org/display/DOCS/Updating/#Updating-%24pop
172
+ * @see mongodb https://www.mongodb.com/docs/manual/reference/operator/update/pop/
132
173
  */
133
174
 
134
175
  $shift() {
@@ -151,7 +192,7 @@ const methods = {
151
192
  * #### NOTE:
152
193
  *
153
194
  * _Calling this multiple times on an array before saving sends the same command as calling it once._
154
- * _This update is implemented using the MongoDB [$pop](https://www.mongodb.org/display/DOCS/Updating/#Updating-%24pop) method which enforces this restriction._
195
+ * _This update is implemented using the MongoDB [$pop](https://www.mongodb.com/docs/manual/reference/operator/update/pop/) method which enforces this restriction._
155
196
  *
156
197
  * doc.array = [1,2,3];
157
198
  *
@@ -176,7 +217,7 @@ const methods = {
176
217
  * @method $pop
177
218
  * @memberOf MongooseArray
178
219
  * @instance
179
- * @see mongodb https://www.mongodb.org/display/DOCS/Updating/#Updating-%24pop
220
+ * @see mongodb https://www.mongodb.com/docs/manual/reference/operator/update/pop/
180
221
  * @method $pop
181
222
  * @memberOf MongooseArray
182
223
  */
@@ -206,7 +247,7 @@ const methods = {
206
247
  * Casts a member based on this arrays schema.
207
248
  *
208
249
  * @param {any} value
209
- * @return value the casted value
250
+ * @return {any} the casted value
210
251
  * @method _cast
211
252
  * @api private
212
253
  * @memberOf MongooseArray
@@ -221,35 +262,37 @@ const methods = {
221
262
  populated = parent.$populated(this[arrayPathSymbol], true);
222
263
  }
223
264
 
224
- if (populated && value !== null && value !== undefined) {
265
+ if (populated && value != null) {
225
266
  // cast to the populated Models schema
226
267
  Model = populated.options[populateModelSymbol];
268
+ if (Model == null) {
269
+ throw new MongooseError('No populated model found for path `' + this[arrayPathSymbol] + '`. This is likely a bug in Mongoose, please report an issue on github.com/Automattic/mongoose.');
270
+ }
227
271
 
228
272
  // only objects are permitted so we can safely assume that
229
273
  // non-objects are to be interpreted as _id
230
274
  if (Buffer.isBuffer(value) ||
231
- isBsonType(value, 'ObjectID') || !utils.isObject(value)) {
275
+ isBsonType(value, 'ObjectId') || !utils.isObject(value)) {
232
276
  value = { _id: value };
233
277
  }
234
278
 
235
279
  // gh-2399
236
280
  // we should cast model only when it's not a discriminator
237
- const isDisc = value.schema && value.schema.discriminatorMapping &&
238
- value.schema.discriminatorMapping.key !== undefined;
281
+ const isDisc = value.schema?.discriminatorMapping?.key !== undefined;
239
282
  if (!isDisc) {
240
283
  value = new Model(value);
241
284
  }
242
- return this[arraySchemaSymbol].caster.applySetters(value, parent, true);
285
+ return this[arraySchemaSymbol].embeddedSchemaType.applySetters(value, parent, true);
243
286
  }
244
287
 
245
- return this[arraySchemaSymbol].caster.applySetters(value, parent, false);
288
+ return this[arraySchemaSymbol].embeddedSchemaType.applySetters(value, parent, false);
246
289
  },
247
290
 
248
291
  /**
249
292
  * Internal helper for .map()
250
293
  *
251
294
  * @api private
252
- * @return {Number}
295
+ * @return {number}
253
296
  * @method _mapCast
254
297
  * @memberOf MongooseArray
255
298
  */
@@ -264,7 +307,7 @@ const methods = {
264
307
  * If it bubbles up from an embedded document change, then it takes the following arguments (otherwise, takes 0 arguments)
265
308
  *
266
309
  * @param {ArraySubdocument} subdoc the embedded doc that invoked this method on the Array
267
- * @param {String} embeddedPath the path which changed in the subdoc
310
+ * @param {string} embeddedPath the path which changed in the subdoc
268
311
  * @method _markModified
269
312
  * @api private
270
313
  * @memberOf MongooseArray
@@ -326,7 +369,7 @@ const methods = {
326
369
 
327
370
  // check for impossible $atomic combos (Mongo denies more than one
328
371
  // $atomic op on a single path
329
- if (atomics.$set || Object.keys(atomics).length && !(op in atomics)) {
372
+ if (atomics.$set || utils.hasOwnKeys(atomics) && !(op in atomics)) {
330
373
  // a different op was previously registered.
331
374
  // save the entire thing.
332
375
  this[arrayAtomicsSymbol] = { $set: this };
@@ -369,7 +412,15 @@ const methods = {
369
412
  if (val != null && utils.hasUserDefinedProperty(val, '$each')) {
370
413
  atomics.$push = val;
371
414
  } else {
372
- atomics.$push.$each = atomics.$push.$each.concat(val);
415
+ if (val.length === 1) {
416
+ atomics.$push.$each.push(val[0]);
417
+ } else if (val.length < 10000) {
418
+ atomics.$push.$each.push(...val);
419
+ } else {
420
+ for (const v of val) {
421
+ atomics.$push.$each.push(v);
422
+ }
423
+ }
373
424
  }
374
425
  } else {
375
426
  atomics[op] = val;
@@ -397,36 +448,43 @@ const methods = {
397
448
 
398
449
  addToSet() {
399
450
  _checkManualPopulation(this, arguments);
451
+ _depopulateIfNecessary(this, arguments);
400
452
 
401
- let values = [].map.call(arguments, this._mapCast, this);
402
- values = this[arraySchemaSymbol].applySetters(values, this[arrayParentSymbol]);
453
+ const values = [].map.call(arguments, this._mapCast, this);
403
454
  const added = [];
404
455
  let type = '';
405
456
  if (values[0] instanceof ArraySubdocument) {
406
457
  type = 'doc';
407
458
  } else if (values[0] instanceof Date) {
408
459
  type = 'date';
460
+ } else if (isBsonType(values[0], 'ObjectId')) {
461
+ type = 'ObjectId';
409
462
  }
410
463
 
411
- const rawValues = utils.isMongooseArray(values) ? values.__array : this;
464
+ const rawValues = utils.isMongooseArray(values) ? values.__array : values;
412
465
  const rawArray = utils.isMongooseArray(this) ? this.__array : this;
413
466
 
414
467
  rawValues.forEach(function(v) {
415
468
  let found;
416
- const val = +v;
417
469
  switch (type) {
418
470
  case 'doc':
419
471
  found = this.some(function(doc) {
420
472
  return doc.equals(v);
421
473
  });
422
474
  break;
423
- case 'date':
475
+ case 'date': {
476
+ const val = +v;
424
477
  found = this.some(function(d) {
425
478
  return +d === val;
426
479
  });
427
480
  break;
481
+ }
482
+ case 'ObjectId':
483
+ found = this.find(o => o.toString() === v.toString());
484
+ break;
428
485
  default:
429
486
  found = ~this.indexOf(v);
487
+ break;
430
488
  }
431
489
 
432
490
  if (!found) {
@@ -444,7 +502,7 @@ const methods = {
444
502
  * Returns the number of pending atomic operations to send to the db for this array.
445
503
  *
446
504
  * @api private
447
- * @return {Number}
505
+ * @return {number}
448
506
  * @method hasAtomics
449
507
  * @memberOf MongooseArray
450
508
  */
@@ -460,9 +518,9 @@ const methods = {
460
518
  /**
461
519
  * Return whether or not the `obj` is included in the array.
462
520
  *
463
- * @param {Object} obj the item to check
464
- * @param {Number} fromIndex
465
- * @return {Boolean}
521
+ * @param {object} obj the item to check
522
+ * @param {number} fromIndex
523
+ * @return {boolean}
466
524
  * @api public
467
525
  * @method includes
468
526
  * @memberOf MongooseArray
@@ -476,23 +534,37 @@ const methods = {
476
534
  /**
477
535
  * Return the index of `obj` or `-1` if not found.
478
536
  *
479
- * @param {Object} obj the item to look for
480
- * @param {Number} fromIndex
481
- * @return {Number}
537
+ * @param {object} obj the item to look for
538
+ * @param {number} fromIndex
539
+ * @return {number}
482
540
  * @api public
483
541
  * @method indexOf
484
542
  * @memberOf MongooseArray
485
543
  */
486
544
 
487
545
  indexOf(obj, fromIndex) {
488
- if (isBsonType(obj, 'ObjectID')) {
546
+ // Compare ObjectIds and UUIDs by their string form, since two instances
547
+ // with the same value are not `==`
548
+ if (isBsonType(obj, 'ObjectId') || obj instanceof UUID) {
489
549
  obj = obj.toString();
490
550
  }
551
+ // `==` compares these by reference, or coerces them so they match other
552
+ // types, like `new Double(4.5) == 4.5`. Compare them by type and value instead.
553
+ let compare = null;
554
+ if (obj instanceof Date) {
555
+ compare = compareDate;
556
+ } else if (Buffer.isBuffer(obj)) {
557
+ compare = compareBuffer;
558
+ } else if (isBsonType(obj, 'Double')) {
559
+ compare = compareDouble;
560
+ } else if (isBsonType(obj, 'Decimal128')) {
561
+ compare = compareDecimal128;
562
+ }
491
563
 
492
564
  fromIndex = fromIndex == null ? 0 : fromIndex;
493
565
  const len = this.length;
494
566
  for (let i = fromIndex; i < len; ++i) {
495
- if (obj == this[i]) {
567
+ if (compare === null ? obj == this[i] : compare(obj, this[i])) {
496
568
  return i;
497
569
  }
498
570
  }
@@ -516,7 +588,7 @@ const methods = {
516
588
  *
517
589
  * #### Note:
518
590
  *
519
- * _marks the entire array as modified, which if saved, will store it as a `$set` operation, potentially overwritting any changes that happen between when you retrieved the object and when you save it._
591
+ * _marks the entire array as modified, which if saved, will store it as a `$set` operation, potentially overwriting any changes that happen between when you retrieved the object and when you save it._
520
592
  *
521
593
  * @param {...any} [args]
522
594
  * @api public
@@ -539,7 +611,7 @@ const methods = {
539
611
  *
540
612
  * _marks the entire array as modified which will pass the entire thing to $set potentially overwriting any changes that happen between when you retrieved the object and when you save it._
541
613
  *
542
- * @see MongooseArray#$pop #types_array_MongooseArray-%24pop
614
+ * @see MongooseArray#$pop https://mongoosejs.com/docs/api/array.html#MongooseArray.prototype.$pop()
543
615
  * @api public
544
616
  * @method pop
545
617
  * @memberOf MongooseArray
@@ -555,7 +627,7 @@ const methods = {
555
627
  /**
556
628
  * Pulls items from the array atomically. Equality is determined by casting
557
629
  * the provided value to an embedded document and comparing using
558
- * [the `Document.equals()` function.](/docs/api/document.html#document_Document-equals)
630
+ * [the `Document.equals()` function.](https://mongoosejs.com/docs/api/document.html#Document.prototype.equals())
559
631
  *
560
632
  * #### Example:
561
633
  *
@@ -577,15 +649,18 @@ const methods = {
577
649
  * The first pull call will result in a atomic operation on the database, if pull is called repeatedly without saving the document, a $set operation is used on the complete array instead, overwriting possible changes that happened on the database in the meantime.
578
650
  *
579
651
  * @param {...any} [args]
580
- * @see mongodb https://www.mongodb.org/display/DOCS/Updating/#Updating-%24pull
652
+ * @see mongodb https://www.mongodb.com/docs/manual/reference/operator/update/pull/
581
653
  * @api public
582
654
  * @method pull
583
655
  * @memberOf MongooseArray
584
656
  */
585
657
 
586
658
  pull() {
587
- const values = [].map.call(arguments, this._cast, this);
588
- const cur = this[arrayParentSymbol].get(this[arrayPathSymbol]);
659
+ const values = [].map.call(arguments, (v, i) => this._cast(v, i, { defaults: false }), this);
660
+ let cur = this;
661
+ if (utils.isMongooseArray(cur)) {
662
+ cur = cur.__array;
663
+ }
589
664
  let i = cur.length;
590
665
  let mem;
591
666
  this._markModified();
@@ -597,10 +672,10 @@ const methods = {
597
672
  return mem.equals(v);
598
673
  });
599
674
  if (some) {
600
- [].splice.call(cur, i, 1);
675
+ cur.splice(i, 1);
601
676
  }
602
- } else if (~cur.indexOf.call(values, mem)) {
603
- [].splice.call(cur, i, 1);
677
+ } else if (~this.indexOf.call(values, mem)) {
678
+ cur.splice(i, 1);
604
679
  }
605
680
  }
606
681
 
@@ -648,7 +723,7 @@ const methods = {
648
723
  * });
649
724
  * doc.nums; // [1, 2, 3, 4, 5]
650
725
  *
651
- * @param {...Object} [args]
726
+ * @param {...object} [args]
652
727
  * @api public
653
728
  * @method push
654
729
  * @memberOf MongooseArray
@@ -670,19 +745,16 @@ const methods = {
670
745
  }
671
746
 
672
747
  _checkManualPopulation(this, values);
748
+ _depopulateIfNecessary(this, values);
673
749
 
674
- const parent = this[arrayParentSymbol];
675
750
  values = [].map.call(values, this._mapCast, this);
676
- values = this[arraySchemaSymbol].applySetters(values, parent, undefined,
677
- undefined, { skipDocumentArrayCast: true });
678
751
  let ret;
679
752
  const atomics = this[arrayAtomicsSymbol];
680
753
  this._markModified();
681
754
  if (isOverwrite) {
682
755
  atomic.$each = values;
683
756
 
684
- if ((atomics.$push && atomics.$push.$each && atomics.$push.$each.length || 0) !== 0 &&
685
- atomics.$push.$position != atomic.$position) {
757
+ if (_cannotMergePush(atomics.$push, atomic)) {
686
758
  if (atomic.$position != null) {
687
759
  [].splice.apply(arr, [atomic.$position, 0].concat(values));
688
760
  ret = arr.length;
@@ -699,18 +771,23 @@ const methods = {
699
771
  }
700
772
  } else {
701
773
  atomic = values;
702
- ret = [].push.apply(arr, values);
774
+ ret = _basePush.apply(arr, values);
775
+ if (atomics.$push?.$position != null) {
776
+ this._registerAtomic('$set', this);
777
+ }
703
778
  }
704
779
 
705
- this._registerAtomic('$push', atomic);
780
+ // add to a pending `$each` instead of replacing it (gh-16618)
781
+ this._registerAtomic('$push', atomics.$push?.$each?.length ? values : atomic);
782
+
706
783
  return ret;
707
784
  },
708
785
 
709
786
  /**
710
- * Alias of [pull](#mongoosearray_MongooseArray-pull)
787
+ * Alias of [pull](https://mongoosejs.com/docs/api/array.html#MongooseArray.prototype.pull())
711
788
  *
712
- * @see MongooseArray#pull #types_array_MongooseArray-pull
713
- * @see mongodb https://www.mongodb.org/display/DOCS/Updating/#Updating-%24pull
789
+ * @see MongooseArray#pull https://mongoosejs.com/docs/api/array.html#MongooseArray.prototype.pull()
790
+ * @see mongodb https://www.mongodb.com/docs/manual/reference/operator/update/pull/
714
791
  * @api public
715
792
  * @memberOf MongooseArray
716
793
  * @instance
@@ -772,7 +849,7 @@ const methods = {
772
849
  *
773
850
  * #### Note:
774
851
  *
775
- * _marks the entire array as modified, which if saved, will store it as a `$set` operation, potentially overwritting any changes that happen between when you retrieved the object and when you save it._
852
+ * _marks the entire array as modified, which if saved, will store it as a `$set` operation, potentially overwriting any changes that happen between when you retrieved the object and when you save it._
776
853
  *
777
854
  * @api public
778
855
  * @method shift
@@ -792,12 +869,12 @@ const methods = {
792
869
  *
793
870
  * #### Note:
794
871
  *
795
- * _marks the entire array as modified, which if saved, will store it as a `$set` operation, potentially overwritting any changes that happen between when you retrieved the object and when you save it._
872
+ * _marks the entire array as modified, which if saved, will store it as a `$set` operation, potentially overwriting any changes that happen between when you retrieved the object and when you save it._
796
873
  *
797
874
  * @api public
798
875
  * @method sort
799
876
  * @memberOf MongooseArray
800
- * @see https://masteringjs.io/tutorials/fundamentals/array-sort
877
+ * @see MasteringJS: Array sort https://masteringjs.io/tutorials/fundamentals/array-sort
801
878
  */
802
879
 
803
880
  sort() {
@@ -812,12 +889,12 @@ const methods = {
812
889
  *
813
890
  * #### Note:
814
891
  *
815
- * _marks the entire array as modified, which if saved, will store it as a `$set` operation, potentially overwritting any changes that happen between when you retrieved the object and when you save it._
892
+ * _marks the entire array as modified, which if saved, will store it as a `$set` operation, potentially overwriting any changes that happen between when you retrieved the object and when you save it._
816
893
  *
817
894
  * @api public
818
895
  * @method splice
819
896
  * @memberOf MongooseArray
820
- * @see https://masteringjs.io/tutorials/fundamentals/array-splice
897
+ * @see MasteringJS: Array splice https://masteringjs.io/tutorials/fundamentals/array-splice
821
898
  */
822
899
 
823
900
  splice() {
@@ -858,7 +935,7 @@ const methods = {
858
935
  /**
859
936
  * Returns a native js Array.
860
937
  *
861
- * @param {Object} options
938
+ * @param {object} options
862
939
  * @return {Array}
863
940
  * @api public
864
941
  * @method toObject
@@ -867,8 +944,8 @@ const methods = {
867
944
 
868
945
  toObject(options) {
869
946
  const arr = utils.isMongooseArray(this) ? this.__array : this;
870
- if (options && options.depopulate) {
871
- options = utils.clone(options);
947
+ if (options?.depopulate) {
948
+ options = clone(options);
872
949
  options._isNested = true;
873
950
  // Ensure return value is a vanilla array, because in Node.js 6+ `map()`
874
951
  // is smart enough to use the inherited array's constructor.
@@ -905,7 +982,6 @@ const methods = {
905
982
  values = arguments;
906
983
  } else {
907
984
  values = [].map.call(arguments, this._cast, this);
908
- values = this[arraySchemaSymbol].applySetters(values, this[arrayParentSymbol]);
909
985
  }
910
986
 
911
987
  const arr = utils.isMongooseArray(this) ? this.__array : this;
@@ -920,6 +996,74 @@ const methods = {
920
996
  * ignore
921
997
  */
922
998
 
999
+ /**
1000
+ * Compare dates by timestamp like `addToSet()` does, so `pull()` works on date arrays.
1001
+ * @api private
1002
+ */
1003
+
1004
+ function compareDate(obj, cur) {
1005
+ return cur instanceof Date && +obj === +cur;
1006
+ }
1007
+
1008
+ /**
1009
+ * MongoDB stores a subtype with binary data, so equal bytes with different
1010
+ * subtypes are different values.
1011
+ * @api private
1012
+ */
1013
+
1014
+ function compareBuffer(obj, cur) {
1015
+ return Buffer.isBuffer(cur) && (obj._subtype || 0) === (cur._subtype || 0) && obj.equals(cur);
1016
+ }
1017
+
1018
+ /**
1019
+ * Match Doubles only against other Doubles. MongoDB considers NaN equal to NaN.
1020
+ * @api private
1021
+ */
1022
+
1023
+ function compareDouble(obj, cur) {
1024
+ if (!isBsonType(cur, 'Double')) {
1025
+ return false;
1026
+ }
1027
+ const a = obj.valueOf();
1028
+ const b = cur.valueOf();
1029
+ return a === b || (Number.isNaN(a) && Number.isNaN(b));
1030
+ }
1031
+
1032
+ const decimal128StringRE = /^(-?)(\d+)(?:\.(\d*))?(?:E([+-]\d+))?$/;
1033
+
1034
+ /**
1035
+ * Match Decimal128s only against other Decimal128s, by numeric value, like
1036
+ * MongoDB does: '1.50' matches '1.5', '1E+3' matches '1000', '-0' matches '0'.
1037
+ * @api private
1038
+ */
1039
+
1040
+ function compareDecimal128(obj, cur) {
1041
+ if (!isBsonType(cur, 'Decimal128')) {
1042
+ return false;
1043
+ }
1044
+ const a = obj.toString();
1045
+ const b = cur.toString();
1046
+ if (a === b) {
1047
+ return true;
1048
+ }
1049
+ const matchA = decimal128StringRE.exec(a);
1050
+ const matchB = decimal128StringRE.exec(b);
1051
+ if (matchA === null || matchB === null) {
1052
+ return false; // NaN and Infinity only match the same string
1053
+ }
1054
+ // `toString()` writes `coefficient * 10 ** exponent`, so compare coefficients
1055
+ // after scaling the one with the larger exponent down to the smaller exponent
1056
+ const fractionA = matchA[3] || '';
1057
+ const fractionB = matchB[3] || '';
1058
+ const coefficientA = BigInt(matchA[1] + matchA[2] + fractionA);
1059
+ const coefficientB = BigInt(matchB[1] + matchB[2] + fractionB);
1060
+ const exponentA = (+matchA[4] || 0) - fractionA.length;
1061
+ const exponentB = (+matchB[4] || 0) - fractionB.length;
1062
+ return exponentA > exponentB ?
1063
+ coefficientA * 10n ** BigInt(exponentA - exponentB) === coefficientB :
1064
+ coefficientB * 10n ** BigInt(exponentB - exponentA) === coefficientA;
1065
+ }
1066
+
923
1067
  function _isAllSubdocs(docs, ref) {
924
1068
  if (!ref) {
925
1069
  return false;
@@ -968,7 +1112,7 @@ function _minimizePath(obj, parts, i) {
968
1112
  }
969
1113
 
970
1114
  _minimizePath(obj[parts[0]], parts, i + 1);
971
- if (obj[parts[0]] != null && typeof obj[parts[0]] === 'object' && Object.keys(obj[parts[0]]).length === 0) {
1115
+ if (obj[parts[0]] != null && typeof obj[parts[0]] === 'object' && utils.hasOwnKeys(obj[parts[0]]) === false) {
972
1116
  delete obj[parts[0]];
973
1117
  }
974
1118
  }
@@ -980,7 +1124,7 @@ function _minimizePath(obj, parts, i) {
980
1124
  function _checkManualPopulation(arr, docs) {
981
1125
  const ref = arr == null ?
982
1126
  null :
983
- arr[arraySchemaSymbol] && arr[arraySchemaSymbol].caster && arr[arraySchemaSymbol].caster.options && arr[arraySchemaSymbol].caster.options.ref || null;
1127
+ arr[arraySchemaSymbol]?.embeddedSchemaType?.options?.ref || null;
984
1128
  if (arr.length === 0 &&
985
1129
  docs.length !== 0) {
986
1130
  if (_isAllSubdocs(docs, ref)) {
@@ -991,6 +1135,42 @@ function _checkManualPopulation(arr, docs) {
991
1135
  }
992
1136
  }
993
1137
 
1138
+ /*!
1139
+ * If `docs` isn't all instances of the right model, depopulate `arr`
1140
+ */
1141
+
1142
+ function _depopulateIfNecessary(arr, docs) {
1143
+ const ref = arr == null ?
1144
+ null :
1145
+ arr[arraySchemaSymbol]?.embeddedSchemaType?.options?.ref || null;
1146
+ const parentDoc = arr[arrayParentSymbol];
1147
+ const path = arr[arrayPathSymbol];
1148
+ if (!ref || !parentDoc.populated(path)) {
1149
+ return;
1150
+ }
1151
+ for (const doc of docs) {
1152
+ if (doc == null) {
1153
+ continue;
1154
+ }
1155
+ if (typeof doc !== 'object' || doc instanceof String || doc instanceof Number || doc instanceof Buffer || utils.isMongooseType(doc)) {
1156
+ parentDoc.depopulate(path);
1157
+ break;
1158
+ }
1159
+ }
1160
+ }
1161
+
1162
+ /*!
1163
+ * A `{ $each }` push can only join a pending `$push` when neither has
1164
+ * `$position`, `$slice` or `$sort` (gh-14244, gh-16618)
1165
+ */
1166
+
1167
+ function _cannotMergePush(pending, atomic) {
1168
+ if (!pending?.$each?.length) {
1169
+ return false;
1170
+ }
1171
+ return [pending, atomic].some(push => push.$position != null || push.$slice != null || push.$sort != null);
1172
+ }
1173
+
994
1174
  const returnVanillaArrayMethods = [
995
1175
  'filter',
996
1176
  'flat',