@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
@@ -0,0 +1,20 @@
1
+ 'use strict';
2
+
3
+ module.exports = function omitUndefined(val) {
4
+ if (val == null || typeof val !== 'object') {
5
+ return val;
6
+ }
7
+ if (Array.isArray(val)) {
8
+ for (let i = val.length - 1; i >= 0; --i) {
9
+ if (val[i] === undefined) {
10
+ val.splice(i, 1);
11
+ }
12
+ }
13
+ }
14
+ for (const key of Object.keys(val)) {
15
+ if (val[key] === void 0) {
16
+ delete val[key];
17
+ }
18
+ }
19
+ return val;
20
+ };
@@ -3,53 +3,80 @@
3
3
  module.exports = parallelLimit;
4
4
 
5
5
  /*!
6
- * ignore
6
+ * Run `fn` over every entry of `params` with at most `limit` calls in flight at
7
+ * a time, resolving to the results in input order. Currently only used by
8
+ * `Model.insertMany()` to bound how many documents validate concurrently.
7
9
  */
8
10
 
9
- function parallelLimit(fns, limit, callback) {
10
- let numInProgress = 0;
11
- let numFinished = 0;
12
- let error = null;
13
-
14
- if (limit <= 0) {
11
+ async function parallelLimit(params, fn, limit) {
12
+ if (!(limit > 0)) {
15
13
  throw new Error('Limit must be positive');
16
14
  }
17
15
 
18
- if (fns.length === 0) {
19
- return callback(null, []);
20
- }
21
-
22
- for (let i = 0; i < fns.length && i < limit; ++i) {
23
- _start();
16
+ const length = params.length;
17
+ if (length === 0) {
18
+ return [];
24
19
  }
25
20
 
26
- function _start() {
27
- fns[numFinished + numInProgress](_done(numFinished + numInProgress));
28
- ++numInProgress;
21
+ const results = new Array(length);
22
+ // Fast path: there's nothing to bound, so kick everything off and wait once
23
+ // instead of running the worker pool below.
24
+ if (limit >= length) {
25
+ for (let i = 0; i < length; ++i) {
26
+ try {
27
+ results[i] = fn(params[i], i);
28
+ } catch (err) {
29
+ // Stop launching, but still hand the calls already in flight to
30
+ // `Promise.all()` so a later rejection from one of them is handled.
31
+ results[i] = Promise.reject(err);
32
+ results.length = i + 1;
33
+ break;
34
+ }
35
+ }
36
+ return Promise.all(results);
29
37
  }
30
38
 
31
- const results = [];
39
+ let nextIndex = 0;
40
+ let hasError = false;
41
+ let firstError = null;
32
42
 
33
- function _done(index) {
34
- return (err, res) => {
35
- --numInProgress;
36
- ++numFinished;
37
-
38
- if (error != null) {
39
- return;
43
+ function worker() {
44
+ if (nextIndex >= length || hasError) {
45
+ return undefined;
46
+ }
47
+ const index = nextIndex++;
48
+ let promise;
49
+ try {
50
+ promise = Promise.resolve(fn(params[index], index));
51
+ } catch (err) {
52
+ if (!hasError) {
53
+ hasError = true;
54
+ firstError = err;
40
55
  }
41
- if (err != null) {
42
- error = err;
43
- return callback(error);
56
+ return undefined;
57
+ }
58
+ return promise.then(
59
+ (val) => {
60
+ results[index] = val;
61
+ return worker();
62
+ },
63
+ (err) => {
64
+ if (!hasError) {
65
+ hasError = true;
66
+ firstError = err;
67
+ }
44
68
  }
69
+ );
70
+ }
45
71
 
46
- results[index] = res;
72
+ const workers = [];
73
+ for (let i = 0; i < limit; ++i) {
74
+ workers.push(worker());
75
+ }
76
+ await Promise.all(workers);
47
77
 
48
- if (numFinished === fns.length) {
49
- return callback(null, results);
50
- } else if (numFinished + numInProgress < fns.length) {
51
- _start();
52
- }
53
- };
78
+ if (hasError) {
79
+ throw firstError;
54
80
  }
81
+ return results;
55
82
  }
@@ -22,7 +22,7 @@ module.exports = function setDottedPath(obj, path, val) {
22
22
  }
23
23
  // Skip inherited properties like `Object.prototype.toString` to avoid
24
24
  // setting properties on shared objects
25
- if (!Object.prototype.hasOwnProperty.call(cur, part) && part in cur) {
25
+ if (!Object.hasOwn(cur, part) && part in cur) {
26
26
  return;
27
27
  }
28
28
  if (cur[part] == null) {
@@ -0,0 +1,167 @@
1
+ 'use strict';
2
+
3
+ const wildcardSegment = '$*';
4
+ const numericSegmentRegex = /^\d+$/;
5
+
6
+ class PathTrieNode {
7
+ constructor() {
8
+ this.children = new Map();
9
+ this.terminal = false;
10
+ this.hasWildcard = false;
11
+ }
12
+ }
13
+
14
+ /**
15
+ * Trie of dotted paths for efficient path matching. Supports the map wildcard
16
+ * segment `$*`, which matches any single segment. For example, a trie
17
+ * containing `settings.$*` matches `settings.theme` but not `settings` or
18
+ * `profile.theme`. In array lookups, numeric segments like array indexes are
19
+ * ignorable: a trie containing `comments.text` matches `comments.0.text`.
20
+ * Single-segment string lookups skip the numeric check entirely.
21
+ *
22
+ * @api private
23
+ */
24
+
25
+ class PathTrie {
26
+ /**
27
+ * @param {string[]} [paths] paths to add to the trie
28
+ */
29
+ constructor(paths) {
30
+ this.root = new PathTrieNode();
31
+ if (paths != null) {
32
+ for (const path of paths) {
33
+ this.add(path);
34
+ }
35
+ }
36
+ }
37
+
38
+ /**
39
+ * Add a dotted path, like `settings.$*` or `profile.firstName`, to the trie.
40
+ *
41
+ * @param {string} path
42
+ */
43
+
44
+ add(path) {
45
+ if (path.indexOf('.') === -1) {
46
+ this._addSegment(this.root, path).terminal = true;
47
+ return;
48
+ }
49
+ let node = this.root;
50
+ for (const segment of path.split('.')) {
51
+ node = this._addSegment(node, segment);
52
+ }
53
+ node.terminal = true;
54
+ }
55
+
56
+ /**
57
+ * @param {PathTrieNode} node
58
+ * @param {string} segment
59
+ */
60
+ _addSegment(node, segment) {
61
+ let child = node.children.get(segment);
62
+ if (child == null) {
63
+ child = new PathTrieNode();
64
+ node.children.set(segment, child);
65
+ if (segment === wildcardSegment) {
66
+ node.hasWildcard = true;
67
+ }
68
+ }
69
+ return child;
70
+ }
71
+
72
+ /**
73
+ * Check if `path` or any of its ancestor paths exist in the trie. `path` is
74
+ * either a single segment string or a pre-split array of segments - lookups
75
+ * never split, callers are responsible for splitting dotted paths.
76
+ * For example, with a trie containing 'profile':
77
+ * matchesPathOrAncestor(['profile', 'firstName']) === true
78
+ * matchesPathOrAncestor('profile') === true
79
+ * But with a trie containing 'profile.firstName':
80
+ * matchesPathOrAncestor('profile') === false
81
+ *
82
+ * @param {string|string[]} path
83
+ */
84
+
85
+ matchesPathOrAncestor(path) {
86
+ return this._walk(path) === true;
87
+ }
88
+
89
+ /**
90
+ * Check if `path`, any of its ancestor paths, or any of its descendant paths
91
+ * exist in the trie. `path` is either a single segment string or a pre-split
92
+ * array of segments - lookups never split, callers are responsible for
93
+ * splitting dotted paths. For example:
94
+ * new PathTrie(['profile']).overlapsPath(['profile', 'firstName']) === true
95
+ * new PathTrie(['profile.firstName']).overlapsPath('profile') === true
96
+ *
97
+ * @param {string|string[]} path
98
+ */
99
+
100
+ overlapsPath(path) {
101
+ return this._walk(path) !== false;
102
+ }
103
+
104
+ /**
105
+ * Walk `path` through the trie. `path` is assumed to be pre-split - if the
106
+ * path has multiple segments, pass in an array of strings. Returns `true` if
107
+ * a terminal node was found at `path` or one of its ancestors, `false` if the
108
+ * walk dead-ended, and the array of reached nodes if `path` is a strict prefix
109
+ * of entries in the trie.
110
+ *
111
+ * @param {string|string[]} path
112
+ */
113
+
114
+ _walk(path) {
115
+ if (typeof path === 'string') {
116
+ const next = [];
117
+ const literal = this.root.children.get(path);
118
+ if (literal != null) {
119
+ if (literal.terminal) {
120
+ return true;
121
+ }
122
+ next.push(literal);
123
+ }
124
+ if (this.root.hasWildcard) {
125
+ const wildcard = this.root.children.get(wildcardSegment);
126
+ if (wildcard.terminal) {
127
+ return true;
128
+ }
129
+ next.push(wildcard);
130
+ }
131
+ return next.length === 0 ? false : next;
132
+ }
133
+ let nodes = [this.root];
134
+ for (const segment of path) {
135
+ const next = [];
136
+ const isNumericSegment = numericSegmentRegex.test(segment);
137
+ for (const node of nodes) {
138
+ if (isNumericSegment) {
139
+ // Numeric segments like array indexes are ignorable: `comments.text`
140
+ // in the trie matches the modified path `comments.0.text`.
141
+ next.push(node);
142
+ }
143
+ const literal = node.children.get(segment);
144
+ if (literal != null) {
145
+ if (literal.terminal) {
146
+ return true;
147
+ }
148
+ next.push(literal);
149
+ }
150
+ if (node.hasWildcard) {
151
+ const wildcard = node.children.get(wildcardSegment);
152
+ if (wildcard.terminal) {
153
+ return true;
154
+ }
155
+ next.push(wildcard);
156
+ }
157
+ }
158
+ if (next.length === 0) {
159
+ return false;
160
+ }
161
+ nodes = next;
162
+ }
163
+ return nodes;
164
+ }
165
+ }
166
+
167
+ module.exports = PathTrie;
@@ -7,13 +7,14 @@ module.exports = pluralize;
7
7
  */
8
8
 
9
9
  exports.pluralization = [
10
- [/(m)an$/gi, '$1en'],
10
+ [/human$/gi, 'humans'],
11
+ [/(m|wom)an$/gi, '$1en'],
11
12
  [/(pe)rson$/gi, '$1ople'],
12
13
  [/(child)$/gi, '$1ren'],
13
14
  [/^(ox)$/gi, '$1en'],
14
15
  [/(ax|test)is$/gi, '$1es'],
15
- [/(octop|vir)us$/gi, '$1i'],
16
- [/(alias|status)$/gi, '$1es'],
16
+ [/(octop|cact|foc|fung|nucle)us$/gi, '$1i'],
17
+ [/(alias|status|virus)$/gi, '$1es'],
17
18
  [/(bu)s$/gi, '$1ses'],
18
19
  [/(buffal|tomat|potat)o$/gi, '$1oes'],
19
20
  [/([ti])um$/gi, '$1a'],
@@ -75,7 +76,7 @@ const uncountables = exports.uncountables;
75
76
  * Pluralize function.
76
77
  *
77
78
  * @author TJ Holowaychuk (extracted from _ext.js_)
78
- * @param {String} string to pluralize
79
+ * @param {string} string to pluralize
79
80
  * @api private
80
81
  */
81
82
 
@@ -1,12 +1,13 @@
1
1
  'use strict';
2
2
 
3
+ const clone = require('../../helpers/clone');
3
4
  const leanPopulateMap = require('./leanPopulateMap');
4
5
  const modelSymbol = require('../symbols').modelSymbol;
5
6
  const utils = require('../../utils');
6
7
 
7
8
  module.exports = assignRawDocsToIdStructure;
8
9
 
9
- const kHasArray = Symbol('assignRawDocsToIdStructure.hasArray');
10
+ const kHasArray = Symbol('mongoose#assignRawDocsToIdStructure#hasArray');
10
11
 
11
12
  /**
12
13
  * Assign `vals` returned by mongo query to the `rawIds`
@@ -25,15 +26,19 @@ const kHasArray = Symbol('assignRawDocsToIdStructure.hasArray');
25
26
  * @param {Array} rawIds
26
27
  * @param {Array} resultDocs
27
28
  * @param {Array} resultOrder
28
- * @param {Object} options
29
- * @param {Boolean} recursed
29
+ * @param {object} options
30
+ * @param {boolean} recursed
30
31
  * @api private
31
32
  */
32
33
 
33
34
  function assignRawDocsToIdStructure(rawIds, resultDocs, resultOrder, options, recursed) {
34
- // honor user specified sort order
35
+ // honor user specified sort order, unless we're populating a single
36
+ // virtual underneath an array (e.g. populating `employees.mostRecentShift` where
37
+ // `mostRecentShift` is a virtual with `justOne`)
35
38
  const newOrder = [];
36
- const sorting = options.sort && rawIds.length > 1;
39
+ const sorting = options.isVirtual && options.justOne && rawIds.length > 1
40
+ ? false :
41
+ options.sort && rawIds.length > 1;
37
42
  const nullIfNotFound = options.$nullIfNotFound;
38
43
  let doc;
39
44
  let sid;
@@ -79,7 +84,7 @@ function assignRawDocsToIdStructure(rawIds, resultDocs, resultOrder, options, re
79
84
  if (options.clone && doc != null) {
80
85
  if (options.lean) {
81
86
  const _model = leanPopulateMap.get(doc);
82
- doc = utils.clone(doc);
87
+ doc = clone(doc);
83
88
  leanPopulateMap.set(doc, _model);
84
89
  } else {
85
90
  doc = doc.constructor.hydrate(doc._doc);
@@ -99,7 +104,7 @@ function assignRawDocsToIdStructure(rawIds, resultDocs, resultOrder, options, re
99
104
  } else {
100
105
  newOrder.push(doc);
101
106
  }
102
- } else if (id != null && id[modelSymbol] != null) {
107
+ } else if (id?.[modelSymbol] != null) {
103
108
  newOrder.push(id);
104
109
  } else {
105
110
  newOrder.push(options.retainNullValues || nullIfNotFound ? null : id);
@@ -1,11 +1,13 @@
1
1
  'use strict';
2
2
 
3
3
  const MongooseMap = require('../../types/map');
4
- const SkipPopulateValue = require('./SkipPopulateValue');
4
+ const SkipPopulateValue = require('./skipPopulateValue');
5
5
  const assignRawDocsToIdStructure = require('./assignRawDocsToIdStructure');
6
6
  const get = require('../get');
7
+ const getInheritedProperty = require('../getInheritedProperty');
7
8
  const getVirtual = require('./getVirtual');
8
9
  const leanPopulateMap = require('./leanPopulateMap');
10
+ const isMongooseDocument = require('../isMongooseDocument');
9
11
  const lookupLocalFields = require('./lookupLocalFields');
10
12
  const markArraySubdocsPopulated = require('./markArraySubdocsPopulated');
11
13
  const mpath = require('mpath');
@@ -19,7 +21,8 @@ module.exports = function assignVals(o) {
19
21
  // `o.options` contains options explicitly listed in `populateOptions`, like
20
22
  // `match` and `limit`.
21
23
  const populateOptions = Object.assign({}, o.options, userOptions, {
22
- justOne: o.justOne
24
+ justOne: o.justOne,
25
+ isVirtual: o.isVirtual
23
26
  });
24
27
  populateOptions.$nullIfNotFound = o.isVirtual;
25
28
  const populatedModel = o.populatedModel;
@@ -38,8 +41,10 @@ module.exports = function assignVals(o) {
38
41
  const options = o.options;
39
42
  const count = o.count && o.isVirtual;
40
43
  let i;
44
+ let setValueIndex = 0;
41
45
 
42
46
  function setValue(val) {
47
+ ++setValueIndex;
43
48
  if (count) {
44
49
  return val;
45
50
  }
@@ -79,11 +84,14 @@ module.exports = function assignVals(o) {
79
84
  return valueFilter(val[0], options, populateOptions, _allIds);
80
85
  } else if (o.justOne === false && !Array.isArray(val)) {
81
86
  return valueFilter([val], options, populateOptions, _allIds);
87
+ } else if (o.justOne === true && !Array.isArray(val) && Array.isArray(_allIds)) {
88
+ return valueFilter(val, options, populateOptions, val == null ? val : _allIds[setValueIndex - 1]);
82
89
  }
83
90
  return valueFilter(val, options, populateOptions, _allIds);
84
91
  }
85
92
 
86
93
  for (i = 0; i < docs.length; ++i) {
94
+ setValueIndex = 0;
87
95
  const _path = o.path.endsWith('.$*') ? o.path.slice(0, -3) : o.path;
88
96
  const existingVal = mpath.get(_path, docs[i], lookupLocalFields);
89
97
  if (existingVal == null && !getVirtual(o.originalModel.schema, _path)) {
@@ -95,8 +103,8 @@ module.exports = function assignVals(o) {
95
103
  valueToSet = numDocs(rawIds[i]);
96
104
  } else if (Array.isArray(o.match)) {
97
105
  valueToSet = Array.isArray(rawIds[i]) ?
98
- rawIds[i].filter(sift(o.match[i])) :
99
- [rawIds[i]].filter(sift(o.match[i]))[0];
106
+ rawIds[i].filter(v => v == null || sift(o.match[i])(v)) :
107
+ [rawIds[i]].filter(v => v == null || sift(o.match[i])(v))[0];
100
108
  } else {
101
109
  valueToSet = rawIds[i];
102
110
  }
@@ -104,7 +112,7 @@ module.exports = function assignVals(o) {
104
112
  // If we're populating a map, the existing value will be an object, so
105
113
  // we need to transform again
106
114
  const originalSchema = o.originalModel.schema;
107
- const isDoc = get(docs[i], '$__', null) != null;
115
+ const isDoc = isMongooseDocument(docs[i]);
108
116
  let isMap = isDoc ?
109
117
  existingVal instanceof Map :
110
118
  utils.isPOJO(existingVal);
@@ -123,11 +131,11 @@ module.exports = function assignVals(o) {
123
131
 
124
132
  if (isDoc && Array.isArray(valueToSet)) {
125
133
  for (const val of valueToSet) {
126
- if (val != null && val.$__ != null) {
134
+ if (isMongooseDocument(val)) {
127
135
  val.$__.parent = docs[i];
128
136
  }
129
137
  }
130
- } else if (isDoc && valueToSet != null && valueToSet.$__ != null) {
138
+ } else if (isDoc && isMongooseDocument(valueToSet)) {
131
139
  valueToSet.$__.parent = docs[i];
132
140
  }
133
141
 
@@ -138,13 +146,29 @@ module.exports = function assignVals(o) {
138
146
  if (Array.isArray(valueToSet)) {
139
147
  valueToSet = valueToSet.map(v => v == null ? void 0 : v);
140
148
  }
141
- mpath.set(_path, valueToSet, docs[i], void 0, setValue, false);
149
+ mpath.set(
150
+ _path,
151
+ valueToSet,
152
+ docs[i],
153
+ // Handle setting paths underneath maps using $* by converting arrays into maps of values
154
+ function lookup(obj, part, val) {
155
+ if (arguments.length >= 3) {
156
+ obj[part] = val;
157
+ return obj[part];
158
+ }
159
+ if (obj instanceof Map && part === '$*') {
160
+ return [...obj.values()];
161
+ }
162
+ return obj[part];
163
+ },
164
+ setValue,
165
+ false
166
+ );
142
167
  continue;
143
168
  }
144
169
 
145
170
  const parts = _path.split('.');
146
171
  let cur = docs[i];
147
- const curPath = parts[0];
148
172
  for (let j = 0; j < parts.length - 1; ++j) {
149
173
  // If we get to an array with a dotted path, like `arr.foo`, don't set
150
174
  // `foo` on the array.
@@ -160,8 +184,9 @@ module.exports = function assignVals(o) {
160
184
  // If nothing to set, avoid creating an unnecessary array. Otherwise
161
185
  // we'll end up with a single doc in the array with only defaults.
162
186
  // See gh-8342, gh-8455
187
+ const curPath = parts.slice(0, j + 1).join('.');
163
188
  const schematype = originalSchema._getSchema(curPath);
164
- if (valueToSet == null && schematype != null && schematype.$isMongooseArray) {
189
+ if (valueToSet == null && schematype?.$isMongooseArray) {
165
190
  break;
166
191
  }
167
192
  cur[parts[j]] = {};
@@ -173,11 +198,11 @@ module.exports = function assignVals(o) {
173
198
  break;
174
199
  }
175
200
  }
176
- if (docs[i].$__) {
201
+ if (isDoc) {
177
202
  o.allOptions.options[populateModelSymbol] = o.allOptions.model;
178
203
  docs[i].$populated(_path, o.unpopulatedValues[i], o.allOptions.options);
179
204
 
180
- if (valueToSet != null && valueToSet.$__ != null) {
205
+ if (isMongooseDocument(valueToSet)) {
181
206
  valueToSet.$__.wasPopulated = { value: o.unpopulatedValues[i] };
182
207
  }
183
208
 
@@ -191,7 +216,7 @@ module.exports = function assignVals(o) {
191
216
  // underneath an array. See gh-6867
192
217
  mpath.set(_path, valueToSet, docs[i], lookupLocalFields, setValue, false);
193
218
 
194
- if (docs[i].$__) {
219
+ if (isDoc) {
195
220
  markArraySubdocsPopulated(docs[i], [o.allOptions.options]);
196
221
  }
197
222
  }
@@ -233,11 +258,11 @@ function numDocs(v) {
233
258
  * background:
234
259
  * _ids are left in the query even when user excludes them so
235
260
  * that population mapping can occur.
236
- * @param {Any} val
237
- * @param {Object} assignmentOpts
238
- * @param {Object} populateOptions
261
+ * @param {any} val
262
+ * @param {object} assignmentOpts
263
+ * @param {object} populateOptions
239
264
  * @param {Function} [populateOptions.transform]
240
- * @param {Boolean} allIds
265
+ * @param {boolean} allIds
241
266
  * @api private
242
267
  */
243
268
 
@@ -304,7 +329,7 @@ function valueFilter(val, assignmentOpts, populateOptions, allIds) {
304
329
  /**
305
330
  * Remove _id from `subdoc` if user specified "lean" query option
306
331
  * @param {Document} subdoc
307
- * @param {Object} assignmentOpts
332
+ * @param {object} assignmentOpts
308
333
  * @api private
309
334
  */
310
335
 
@@ -321,7 +346,7 @@ function maybeRemoveId(subdoc, assignmentOpts) {
321
346
  /**
322
347
  * Determine if `obj` is something we can set a populated path to. Can be a
323
348
  * document, a lean document, or an array/map that contains docs.
324
- * @param {Any} obj
349
+ * @param {any} obj
325
350
  * @api private
326
351
  */
327
352
 
@@ -331,7 +356,7 @@ function isPopulatedObject(obj) {
331
356
  }
332
357
 
333
358
  return Array.isArray(obj) ||
334
- obj.$isMongooseMap ||
335
- obj.$__ != null ||
359
+ getInheritedProperty(obj, '$isMongooseMap') ||
360
+ isMongooseDocument(obj) ||
336
361
  leanPopulateMap.has(obj);
337
362
  }
@@ -1,6 +1,6 @@
1
1
  'use strict';
2
2
 
3
- const SkipPopulateValue = require('./SkipPopulateValue');
3
+ const SkipPopulateValue = require('./skipPopulateValue');
4
4
  const parentPaths = require('../path/parentPaths');
5
5
  const { trusted } = require('../query/trusted');
6
6
  const hasDollarKeys = require('../query/hasDollarKeys');
@@ -25,7 +25,15 @@ module.exports = function createPopulateQueryFilter(ids, _match, _foreignField,
25
25
  for (let i = 0; i < _parentPaths.length - 1; ++i) {
26
26
  const cur = _parentPaths[i];
27
27
  if (match[cur] != null && match[cur].$elemMatch != null) {
28
- match[cur].$elemMatch[foreignField.slice(cur.length + 1)] = trusted({ $in: ids });
28
+ // Copy rather than mutate so the user's `match` stays unchanged and split populate
29
+ // queries (gh-5890) each get their own `$in` rather than sharing one object
30
+ match[cur] = {
31
+ ...match[cur],
32
+ $elemMatch: {
33
+ ...match[cur].$elemMatch,
34
+ [foreignField.slice(cur.length + 1)]: trusted({ $in: ids })
35
+ }
36
+ };
29
37
  delete match[foreignField];
30
38
  break;
31
39
  }
@@ -60,7 +68,7 @@ module.exports = function createPopulateQueryFilter(ids, _match, _foreignField,
60
68
  * to avoid cast errors (gh-7706)
61
69
  * @param {Array} ids
62
70
  * @param {SchemaType} foreignSchemaType
63
- * @param {Boolean} [skipInvalidIds]
71
+ * @param {boolean} [skipInvalidIds]
64
72
  * @api private
65
73
  */
66
74
 
@@ -73,7 +81,7 @@ function _filterInvalidIds(ids, foreignSchemaType, skipInvalidIds) {
73
81
  try {
74
82
  foreignSchemaType.cast(id);
75
83
  return true;
76
- } catch (err) {
84
+ } catch {
77
85
  return false;
78
86
  }
79
87
  });
@@ -82,7 +90,7 @@ function _filterInvalidIds(ids, foreignSchemaType, skipInvalidIds) {
82
90
  /**
83
91
  * Format `mod.match` given that it may be an array that we need to $or if
84
92
  * the client has multiple docs with match functions
85
- * @param {Array|Any} match
93
+ * @param {Array|any} match
86
94
  * @api private
87
95
  */
88
96