@datanimbus/mongoose 9.13.1 → 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
package/lib/utils.js CHANGED
@@ -4,20 +4,21 @@
4
4
  * Module dependencies.
5
5
  */
6
6
 
7
- const UUID = require('bson').UUID;
7
+ const UUID = require('mongodb/lib/bson').UUID;
8
8
  const ms = require('ms');
9
9
  const mpath = require('mpath');
10
10
  const ObjectId = require('./types/objectid');
11
- const PopulateOptions = require('./options/PopulateOptions');
11
+ const PopulateOptions = require('./options/populateOptions');
12
12
  const clone = require('./helpers/clone');
13
13
  const immediate = require('./helpers/immediate');
14
14
  const isObject = require('./helpers/isObject');
15
15
  const isMongooseArray = require('./types/array/isMongooseArray');
16
- const isMongooseDocumentArray = require('./types/DocumentArray/isMongooseDocumentArray');
16
+ const isMongooseDocumentArray = require('./types/documentArray/isMongooseDocumentArray');
17
+ const isMongooseDocument = require('./helpers/isMongooseDocument');
17
18
  const isBsonType = require('./helpers/isBsonType');
19
+ const isPOJO = require('./helpers/isPOJO');
18
20
  const getFunctionName = require('./helpers/getFunctionName');
19
21
  const isMongooseObject = require('./helpers/isMongooseObject');
20
- const promiseOrCallback = require('./helpers/promiseOrCallback');
21
22
  const schemaMerge = require('./helpers/schema/merge');
22
23
  const specialProperties = require('./helpers/specialProperties');
23
24
  const { trustedSymbol } = require('./helpers/query/trusted');
@@ -31,13 +32,16 @@ exports.isMongooseDocumentArray = isMongooseDocumentArray.isMongooseDocumentArra
31
32
  exports.registerMongooseArray = isMongooseArray.registerMongooseArray;
32
33
  exports.registerMongooseDocumentArray = isMongooseDocumentArray.registerMongooseDocumentArray;
33
34
 
35
+ const oneSpaceRE = /\s/;
36
+ const manySpaceRE = /\s+/;
37
+
34
38
  /**
35
39
  * Produces a collection name from model `name`. By default, just returns
36
40
  * the model name
37
41
  *
38
- * @param {String} name a model name
42
+ * @param {string} name a model name
39
43
  * @param {Function} pluralize function that pluralizes the collection name
40
- * @return {String} a collection name
44
+ * @return {string} a collection name
41
45
  * @api private
42
46
  */
43
47
 
@@ -49,6 +53,12 @@ exports.toCollectionName = function(name, pluralize) {
49
53
  return name;
50
54
  }
51
55
  if (typeof pluralize === 'function') {
56
+ if (typeof name !== 'string') {
57
+ throw new TypeError('Collection name must be a string');
58
+ }
59
+ if (name.length === 0) {
60
+ throw new TypeError('Collection name cannot be empty');
61
+ }
52
62
  return pluralize(name);
53
63
  }
54
64
  return name;
@@ -61,7 +71,7 @@ exports.toCollectionName = function(name, pluralize) {
61
71
  *
62
72
  * @param {any} a a value to compare to `b`
63
73
  * @param {any} b a value to compare to `a`
64
- * @return {Boolean}
74
+ * @return {boolean}
65
75
  * @api private
66
76
  */
67
77
 
@@ -78,7 +88,7 @@ exports.deepEqual = function deepEqual(a, b) {
78
88
  return a.getTime() === b.getTime();
79
89
  }
80
90
 
81
- if ((isBsonType(a, 'ObjectID') && isBsonType(b, 'ObjectID')) ||
91
+ if ((isBsonType(a, 'ObjectId') && isBsonType(b, 'ObjectId')) ||
82
92
  (isBsonType(a, 'Decimal128') && isBsonType(b, 'Decimal128'))) {
83
93
  return a.toString() === b.toString();
84
94
  }
@@ -110,6 +120,16 @@ exports.deepEqual = function deepEqual(a, b) {
110
120
  deepEqual(Array.from(a.values()), Array.from(b.values()));
111
121
  }
112
122
 
123
+ if (a instanceof Set || b instanceof Set) {
124
+ if (!(a instanceof Set) || !(b instanceof Set)) {
125
+ return false;
126
+ }
127
+ if (a.size !== b.size) {
128
+ return false;
129
+ }
130
+ return deepEqual(Array.from(a.values()), Array.from(b.values()));
131
+ }
132
+
113
133
  // Handle MongooseNumbers
114
134
  if (a instanceof Number && b instanceof Number) {
115
135
  return a.valueOf() === b.valueOf();
@@ -135,13 +155,13 @@ exports.deepEqual = function deepEqual(a, b) {
135
155
  return true;
136
156
  }
137
157
 
138
- if (a.$__ != null) {
158
+ if (isMongooseDocument(a)) {
139
159
  a = a._doc;
140
160
  } else if (isMongooseObject(a)) {
141
161
  a = a.toObject();
142
162
  }
143
163
 
144
- if (b.$__ != null) {
164
+ if (isMongooseDocument(b)) {
145
165
  b = b._doc;
146
166
  } else if (isMongooseObject(b)) {
147
167
  b = b.toObject();
@@ -181,20 +201,15 @@ exports.deepEqual = function deepEqual(a, b) {
181
201
  */
182
202
 
183
203
  exports.last = function(arr) {
204
+ if (arr == null) {
205
+ return void 0;
206
+ }
184
207
  if (arr.length > 0) {
185
208
  return arr[arr.length - 1];
186
209
  }
187
210
  return void 0;
188
211
  };
189
212
 
190
- exports.clone = clone;
191
-
192
- /*!
193
- * ignore
194
- */
195
-
196
- exports.promiseOrCallback = promiseOrCallback;
197
-
198
213
  /*!
199
214
  * ignore
200
215
  */
@@ -226,46 +241,55 @@ exports.omit = function omit(obj, keys) {
226
241
  return ret;
227
242
  };
228
243
 
229
-
230
244
  /**
231
- * Shallow copies defaults into options.
232
- *
233
- * @param {Object} defaults
234
- * @param {Object} [options]
235
- * @return {Object} the merged object
236
- * @api private
237
- */
238
-
239
- exports.options = function(defaults, options) {
240
- const keys = Object.keys(defaults);
241
- let i = keys.length;
242
- let k;
243
-
244
- options = options || {};
245
-
246
- while (i--) {
247
- k = keys[i];
248
- if (!(k in options)) {
249
- options[k] = defaults[k];
245
+ * Simplified version of `clone()` that only clones POJOs and arrays. Skips documents, dates, objectids, etc.
246
+ * @param {any} val
247
+ * @returns
248
+ */
249
+
250
+ exports.clonePOJOsAndArrays = function clonePOJOsAndArrays(val) {
251
+ if (val == null) {
252
+ return val;
253
+ }
254
+ // Skip documents because we assume they'll be cloned later. See gh-15312 for how documents are handled with `merge()`.
255
+ if (isMongooseDocument(val)) {
256
+ return val;
257
+ }
258
+ if (isPOJO(val)) {
259
+ val = { ...val };
260
+ for (const key of Object.keys(val)) {
261
+ val[key] = exports.clonePOJOsAndArrays(val[key]);
250
262
  }
263
+ return val;
264
+ }
265
+ if (Array.isArray(val)) {
266
+ val = [...val];
267
+ for (let i = 0; i < val.length; ++i) {
268
+ val[i] = exports.clonePOJOsAndArrays(val[i]);
269
+ }
270
+ return val;
251
271
  }
252
272
 
253
- return options;
273
+ return val;
254
274
  };
255
275
 
256
276
  /**
257
277
  * Merges `from` into `to` without overwriting existing properties.
258
278
  *
259
- * @param {Object} to
260
- * @param {Object} from
261
- * @param {Object} [options]
262
- * @param {String} [path]
279
+ * @param {object} to
280
+ * @param {object} from
281
+ * @param {object} [options]
282
+ * @param {string} [path]
263
283
  * @api private
264
284
  */
265
285
 
266
286
  exports.merge = function merge(to, from, options, path) {
267
287
  options = options || {};
268
288
 
289
+ if (from == null) {
290
+ return to;
291
+ }
292
+
269
293
  const keys = Object.keys(from);
270
294
  let i = 0;
271
295
  const len = keys.length;
@@ -290,7 +314,7 @@ exports.merge = function merge(to, from, options, path) {
290
314
  continue;
291
315
  }
292
316
  if (to[key] == null) {
293
- to[key] = from[key];
317
+ to[key] = exports.clonePOJOsAndArrays(from[key]);
294
318
  } else if (exports.isObject(from[key])) {
295
319
  if (!exports.isObject(to[key])) {
296
320
  to[key] = {};
@@ -300,8 +324,8 @@ exports.merge = function merge(to, from, options, path) {
300
324
  // base schema has a given path as a single nested but discriminator schema
301
325
  // has the path as a document array, or vice versa (gh-9534)
302
326
  if (options.isDiscriminatorSchemaMerge &&
303
- (from[key].$isSingleNested && to[key].$isMongooseDocumentArray) ||
304
- (from[key].$isMongooseDocumentArray && to[key].$isSingleNested)) {
327
+ ((from[key].$isSingleNested && to[key].$isMongooseDocumentArray) ||
328
+ (from[key].$isMongooseDocumentArray && to[key].$isSingleNested))) {
305
329
  continue;
306
330
  } else if (from[key].instanceOfSchema) {
307
331
  if (to[key].instanceOfSchema) {
@@ -310,7 +334,7 @@ exports.merge = function merge(to, from, options, path) {
310
334
  to[key] = from[key].clone();
311
335
  }
312
336
  continue;
313
- } else if (isBsonType(from[key], 'ObjectID')) {
337
+ } else if (isBsonType(from[key], 'ObjectId')) {
314
338
  to[key] = new ObjectId(from[key]);
315
339
  continue;
316
340
  }
@@ -320,13 +344,15 @@ exports.merge = function merge(to, from, options, path) {
320
344
  to[key] = from[key];
321
345
  }
322
346
  }
347
+
348
+ return to;
323
349
  };
324
350
 
325
351
  /**
326
352
  * Applies toObject recursively.
327
353
  *
328
- * @param {Document|Array|Object} obj
329
- * @return {Object}
354
+ * @param {Document|Array|object} obj
355
+ * @return {object}
330
356
  * @api private
331
357
  */
332
358
 
@@ -381,66 +407,63 @@ exports.isObject = isObject;
381
407
  *
382
408
  * `Object.getPrototypeOf()` is part of ES5: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/getPrototypeOf
383
409
  *
384
- * @param {Object|Array|String|Function|RegExp|any} arg
410
+ * @param {object|Array|string|Function|RegExp|any} arg
385
411
  * @api private
386
- * @return {Boolean}
412
+ * @return {boolean}
387
413
  */
388
414
 
389
- exports.isPOJO = function isPOJO(arg) {
390
- if (arg == null || typeof arg !== 'object') {
391
- return false;
392
- }
393
- const proto = Object.getPrototypeOf(arg);
394
- // Prototype may be null if you used `Object.create(null)`
395
- // Checking `proto`'s constructor is safe because `getPrototypeOf()`
396
- // explicitly crosses the boundary from object data to object metadata
397
- return !proto || proto.constructor.name === 'Object';
398
- };
415
+ exports.isPOJO = require('./helpers/isPOJO');
399
416
 
400
417
  /**
401
418
  * Determines if `arg` is an object that isn't an instance of a built-in value
402
419
  * class, like Array, Buffer, ObjectId, etc.
403
- * @param {Any} val
420
+ * @param {any} val
404
421
  */
405
422
 
406
423
  exports.isNonBuiltinObject = function isNonBuiltinObject(val) {
407
424
  return typeof val === 'object' &&
408
- !exports.isNativeObject(val) &&
425
+ !Array.isArray(val) &&
426
+ !(val instanceof Date) &&
427
+ !(val instanceof Boolean) &&
428
+ !(val instanceof Number) &&
429
+ !(val instanceof String) &&
409
430
  !exports.isMongooseType(val) &&
410
431
  !(val instanceof UUID) &&
411
432
  val != null;
412
433
  };
413
434
 
414
435
  /**
415
- * Determines if `obj` is a built-in object like an array, date, boolean,
416
- * etc.
417
- * @param {Any} arg
436
+ * Determines if `val` is an object that has no own keys
437
+ * @param {any} val
418
438
  */
419
439
 
420
- exports.isNativeObject = function(arg) {
421
- return Array.isArray(arg) ||
422
- arg instanceof Date ||
423
- arg instanceof Boolean ||
424
- arg instanceof Number ||
425
- arg instanceof String;
440
+ exports.isEmptyObject = function isEmptyObject(val) {
441
+ if (val == null || typeof val !== 'object') {
442
+ return false;
443
+ }
444
+ return exports.hasOwnKeys(val) === false;
426
445
  };
427
446
 
428
447
  /**
429
- * Determines if `val` is an object that has no own keys
430
- * @param {Any} val
448
+ * Determines if `obj` has any own keys. Assumes obj is already an object.
449
+ * Faster than Object.keys(obj).length > 0.
450
+ * @param {object} obj
431
451
  */
432
452
 
433
- exports.isEmptyObject = function(val) {
434
- return val != null &&
435
- typeof val === 'object' &&
436
- Object.keys(val).length === 0;
453
+ exports.hasOwnKeys = function hasOwnKeys(obj) {
454
+ for (const key in obj) {
455
+ if (Object.prototype.hasOwnProperty.call(obj, key)) {
456
+ return true;
457
+ }
458
+ }
459
+ return false;
437
460
  };
438
461
 
439
462
  /**
440
463
  * Search if `obj` or any POJOs nested underneath `obj` has a property named
441
464
  * `key`
442
- * @param {Object} obj
443
- * @param {String} key
465
+ * @param {object} obj
466
+ * @param {string} key
444
467
  */
445
468
 
446
469
  exports.hasKey = function hasKey(obj, key) {
@@ -487,11 +510,11 @@ exports.tick = function tick(callback) {
487
510
  /**
488
511
  * Returns true if `v` is an object that can be serialized as a primitive in
489
512
  * MongoDB
490
- * @param {Any} v
513
+ * @param {any} v
491
514
  */
492
515
 
493
516
  exports.isMongooseType = function(v) {
494
- return isBsonType(v, 'ObjectID') || isBsonType(v, 'Decimal128') || v instanceof Buffer;
517
+ return isBsonType(v, 'ObjectId') || isBsonType(v, 'Decimal128') || v instanceof Buffer;
495
518
  };
496
519
 
497
520
  exports.isMongooseObject = isMongooseObject;
@@ -499,7 +522,7 @@ exports.isMongooseObject = isMongooseObject;
499
522
  /**
500
523
  * Converts `expires` options of index objects to `expiresAfterSeconds` options for MongoDB.
501
524
  *
502
- * @param {Object} object
525
+ * @param {object} object
503
526
  * @api private
504
527
  */
505
528
 
@@ -519,14 +542,14 @@ exports.expires = function expires(object) {
519
542
 
520
543
  /**
521
544
  * populate helper
522
- * @param {String} path
523
- * @param {String} select
545
+ * @param {string} path
546
+ * @param {string} select
524
547
  * @param {Model} model
525
- * @param {Object} match
526
- * @param {Object} options
527
- * @param {Any} subPopulate
528
- * @param {Boolean} justOne
529
- * @param {Boolean} count
548
+ * @param {object} match
549
+ * @param {object} options
550
+ * @param {any} subPopulate
551
+ * @param {boolean} justOne
552
+ * @param {boolean} count
530
553
  */
531
554
 
532
555
  exports.populate = function populate(path, select, model, match, options, subPopulate, justOne, count) {
@@ -536,7 +559,7 @@ exports.populate = function populate(path, select, model, match, options, subPop
536
559
  if (path instanceof PopulateOptions) {
537
560
  // If reusing old populate docs, avoid reusing `_docs` because that may
538
561
  // lead to bugs and memory leaks. See gh-11641
539
- path._docs = [];
562
+ path._docs = {};
540
563
  path._childDocs = [];
541
564
  return [path];
542
565
  }
@@ -571,8 +594,8 @@ exports.populate = function populate(path, select, model, match, options, subPop
571
594
  };
572
595
  }
573
596
 
574
- if (typeof obj.path !== 'string') {
575
- throw new TypeError('utils.populate: invalid path. Expected string. Got typeof `' + typeof path + '`');
597
+ if (typeof obj.path !== 'string' && !(Array.isArray(obj.path) && obj.path.every(el => typeof el === 'string'))) {
598
+ throw new TypeError('utils.populate: invalid path. Expected string or array of strings. Got typeof `' + typeof path + '`');
576
599
  }
577
600
 
578
601
  return _populateObj(obj);
@@ -583,8 +606,8 @@ exports.populate = function populate(path, select, model, match, options, subPop
583
606
  function makeSingles(arr) {
584
607
  const ret = [];
585
608
  arr.forEach(function(obj) {
586
- if (/[\s]/.test(obj.path)) {
587
- const paths = obj.path.split(' ');
609
+ if (oneSpaceRE.test(obj.path)) {
610
+ const paths = obj.path.split(manySpaceRE);
588
611
  paths.forEach(function(p) {
589
612
  const copy = Object.assign({}, obj);
590
613
  copy.path = p;
@@ -603,9 +626,9 @@ function _populateObj(obj) {
603
626
  if (Array.isArray(obj.populate)) {
604
627
  const ret = [];
605
628
  obj.populate.forEach(function(obj) {
606
- if (/[\s]/.test(obj.path)) {
629
+ if (oneSpaceRE.test(obj.path)) {
607
630
  const copy = Object.assign({}, obj);
608
- const paths = copy.path.split(' ');
631
+ const paths = copy.path.split(manySpaceRE);
609
632
  paths.forEach(function(p) {
610
633
  copy.path = p;
611
634
  ret.push(exports.populate(copy)[0]);
@@ -620,9 +643,13 @@ function _populateObj(obj) {
620
643
  }
621
644
 
622
645
  const ret = [];
623
- const paths = obj.path.split(' ');
646
+ const paths = oneSpaceRE.test(obj.path)
647
+ ? obj.path.split(manySpaceRE)
648
+ : Array.isArray(obj.path)
649
+ ? obj.path
650
+ : [obj.path];
624
651
  if (obj.options != null) {
625
- obj.options = exports.clone(obj.options);
652
+ obj.options = clone(obj.options);
626
653
  }
627
654
 
628
655
  for (const path of paths) {
@@ -635,23 +662,42 @@ function _populateObj(obj) {
635
662
  /**
636
663
  * Return the value of `obj` at the given `path`.
637
664
  *
638
- * @param {String} path
639
- * @param {Object} obj
640
- * @param {Any} map
665
+ * @param {string} path
666
+ * @param {object} obj
667
+ * @param {any} map
641
668
  */
642
669
 
643
670
  exports.getValue = function(path, obj, map) {
644
- return mpath.get(path, obj, '_doc', map);
671
+ return mpath.get(path, obj, getValueLookup, map);
645
672
  };
646
673
 
674
+ /*!
675
+ * ignore
676
+ */
677
+
678
+ const mapGetterOptions = Object.freeze({ getters: false });
679
+
680
+ function getValueLookup(obj, part) {
681
+ if (part === '$*' && obj instanceof Map) {
682
+ return obj;
683
+ }
684
+ let _from = obj?._doc || obj;
685
+ if (_from?.isMongooseArrayProxy) {
686
+ _from = _from.__array;
687
+ }
688
+ return _from instanceof Map ?
689
+ _from.get(part, mapGetterOptions) :
690
+ _from[part];
691
+ }
692
+
647
693
  /**
648
694
  * Sets the value of `obj` at the given `path`.
649
695
  *
650
- * @param {String} path
696
+ * @param {string} path
651
697
  * @param {Anything} val
652
- * @param {Object} obj
653
- * @param {Any} map
654
- * @param {Any} _copying
698
+ * @param {object} obj
699
+ * @param {any} map
700
+ * @param {any} _copying
655
701
  */
656
702
 
657
703
  exports.setValue = function(path, val, obj, map, _copying) {
@@ -661,13 +707,16 @@ exports.setValue = function(path, val, obj, map, _copying) {
661
707
  /**
662
708
  * Returns an array of values from object `o`.
663
709
  *
664
- * @param {Object} o
710
+ * @param {object} o
665
711
  * @return {Array}
666
712
  * @api private
667
713
  */
668
714
 
669
715
  exports.object = {};
670
716
  exports.object.vals = function vals(o) {
717
+ if (o == null) {
718
+ return [];
719
+ }
671
720
  const keys = Object.keys(o);
672
721
  let i = keys.length;
673
722
  const ret = [];
@@ -679,34 +728,16 @@ exports.object.vals = function vals(o) {
679
728
  return ret;
680
729
  };
681
730
 
682
- /**
683
- * @see exports.options
684
- */
685
-
686
- exports.object.shallowCopy = exports.options;
687
-
688
- const hop = Object.prototype.hasOwnProperty;
689
-
690
- /**
691
- * Safer helper for hasOwnProperty checks
692
- *
693
- * @param {Object} obj
694
- * @param {String} prop
695
- */
696
-
697
- exports.object.hasOwnProperty = function(obj, prop) {
698
- return hop.call(obj, prop);
699
- };
700
731
 
701
732
  /**
702
733
  * Determine if `val` is null or undefined
703
734
  *
704
- * @param {Any} val
705
- * @return {Boolean}
735
+ * @param {any} val
736
+ * @return {boolean}
706
737
  */
707
738
 
708
739
  exports.isNullOrUndefined = function(val) {
709
- return val === null || val === undefined;
740
+ return val == null;
710
741
  };
711
742
 
712
743
  /*!
@@ -747,8 +778,6 @@ exports.array.flatten = function flatten(arr, filter, ret) {
747
778
  * ignore
748
779
  */
749
780
 
750
- const _hasOwnProperty = Object.prototype.hasOwnProperty;
751
-
752
781
  exports.hasUserDefinedProperty = function(obj, key) {
753
782
  if (obj == null) {
754
783
  return false;
@@ -763,7 +792,7 @@ exports.hasUserDefinedProperty = function(obj, key) {
763
792
  return false;
764
793
  }
765
794
 
766
- if (_hasOwnProperty.call(obj, key)) {
795
+ if (Object.hasOwn(obj, key)) {
767
796
  return true;
768
797
  }
769
798
  if (typeof obj === 'object' && key in obj) {
@@ -819,12 +848,13 @@ exports.array.unique = function(arr) {
819
848
  }
820
849
  ret.push(item);
821
850
  primitives.add(item);
822
- } else if (isBsonType(item, 'ObjectID')) {
823
- if (ids.has(item.toString())) {
851
+ } else if (isBsonType(item, 'ObjectId')) {
852
+ const idStr = item.toString();
853
+ if (ids.has(idStr)) {
824
854
  continue;
825
855
  }
826
856
  ret.push(item);
827
- ids.add(item.toString());
857
+ ids.add(idStr);
828
858
  } else {
829
859
  ret.push(item);
830
860
  }
@@ -839,7 +869,7 @@ exports.buffer = {};
839
869
  * Determines if two buffers are equal.
840
870
  *
841
871
  * @param {Buffer} a
842
- * @param {Object} b
872
+ * @param {object} b
843
873
  */
844
874
 
845
875
  exports.buffer.areEqual = function(a, b) {
@@ -849,23 +879,15 @@ exports.buffer.areEqual = function(a, b) {
849
879
  if (!Buffer.isBuffer(b)) {
850
880
  return false;
851
881
  }
852
- if (a.length !== b.length) {
853
- return false;
854
- }
855
- for (let i = 0, len = a.length; i < len; ++i) {
856
- if (a[i] !== b[i]) {
857
- return false;
858
- }
859
- }
860
- return true;
882
+ return a.equals(b);
861
883
  };
862
884
 
863
885
  exports.getFunctionName = getFunctionName;
864
886
 
865
887
  /**
866
888
  * Decorate buffers
867
- * @param {Object} destination
868
- * @param {Object} source
889
+ * @param {object} destination
890
+ * @param {object} source
869
891
  */
870
892
 
871
893
  exports.decorate = function(destination, source) {
@@ -880,8 +902,8 @@ exports.decorate = function(destination, source) {
880
902
  /**
881
903
  * merges to with a copy of from
882
904
  *
883
- * @param {Object} to
884
- * @param {Object} fromObj
905
+ * @param {object} to
906
+ * @param {object} fromObj
885
907
  * @api private
886
908
  */
887
909
 
@@ -908,11 +930,11 @@ exports.mergeClone = function(to, fromObj) {
908
930
  // Skip inherited properties like `Object.prototype.toString` to avoid setting
909
931
  // properties on shared objects. Document properties are getters on the
910
932
  // prototype, so check `_doc`.
911
- if (!exports.object.hasOwnProperty(to.$__ == null ? to : to._doc, key) && key in to) {
933
+ if (!Object.hasOwn(isMongooseDocument(to) ? to._doc : to, key) && key in to) {
912
934
  continue;
913
935
  }
914
936
  if (typeof to[key] === 'undefined') {
915
- to[key] = exports.clone(fromObj[key], {
937
+ to[key] = clone(fromObj[key], {
916
938
  transform: false,
917
939
  virtuals: false,
918
940
  depopulate: true,
@@ -921,12 +943,13 @@ exports.mergeClone = function(to, fromObj) {
921
943
  });
922
944
  } else {
923
945
  let val = fromObj[key];
924
- if (val != null && val.valueOf && !(val instanceof Date)) {
946
+ if (val?.valueOf && !(val instanceof Date)) {
925
947
  val = val.valueOf();
926
948
  }
927
949
  if (exports.isObject(val)) {
928
950
  let obj = val;
929
- if (isMongooseObject(val) && !val.isMongooseBuffer) {
951
+ const isBuffer = Buffer.isBuffer(val) && val.isMongooseBuffer;
952
+ if (isMongooseObject(val) && !isBuffer) {
930
953
  obj = obj.toObject({
931
954
  transform: false,
932
955
  virtuals: false,
@@ -935,12 +958,12 @@ exports.mergeClone = function(to, fromObj) {
935
958
  flattenDecimals: false
936
959
  });
937
960
  }
938
- if (val.isMongooseBuffer) {
961
+ if (isBuffer) {
939
962
  obj = Buffer.from(obj);
940
963
  }
941
964
  exports.mergeClone(to[key], obj);
942
965
  } else {
943
- to[key] = exports.clone(val, {
966
+ to[key] = clone(val, {
944
967
  flattenDecimals: false
945
968
  });
946
969
  }
@@ -962,6 +985,29 @@ exports.each = function(arr, fn) {
962
985
  }
963
986
  };
964
987
 
988
+ /**
989
+ * Rename an object key, while preserving its position in the object
990
+ *
991
+ * @param {object} oldObj
992
+ * @param {string|number} oldKey
993
+ * @param {string|number} newKey
994
+ * @api private
995
+ */
996
+ exports.renameObjKey = function(oldObj, oldKey, newKey) {
997
+ const keys = Object.keys(oldObj);
998
+ return keys.reduce(
999
+ (acc, val) => {
1000
+ if (val === oldKey) {
1001
+ acc[newKey] = oldObj[oldKey];
1002
+ } else {
1003
+ acc[val] = oldObj[val];
1004
+ }
1005
+ return acc;
1006
+ },
1007
+ {}
1008
+ );
1009
+ };
1010
+
965
1011
  /*!
966
1012
  * ignore
967
1013
  */