@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
@@ -7,6 +7,7 @@
7
7
  const Mixed = require('../../schema/mixed');
8
8
  const get = require('../get');
9
9
  const getDiscriminatorByValue = require('../discriminator/getDiscriminatorByValue');
10
+ const isMongooseDocument = require('../isMongooseDocument');
10
11
  const leanPopulateMap = require('./leanPopulateMap');
11
12
  const mpath = require('mpath');
12
13
 
@@ -20,24 +21,24 @@ const populateModelSymbol = require('../symbols').populateModelSymbol;
20
21
  *
21
22
  * @param {Model} model
22
23
  * @param {Schema} schema
23
- * @param {Object} doc POJO
24
+ * @param {object} doc POJO
24
25
  * @param {string} path
26
+ * @param {string[]} [parts] pass in pre-split `path` to avoid extra splitting
25
27
  * @api private
26
28
  */
27
29
 
28
- module.exports = function getSchemaTypes(model, schema, doc, path) {
30
+ module.exports = function getSchemaTypes(model, schema, doc, path, parts) {
29
31
  const pathschema = schema.path(path);
30
32
  const topLevelDoc = doc;
31
33
  if (pathschema) {
32
34
  return pathschema;
33
35
  }
34
36
 
35
- const discriminatorKey = schema.discriminatorMapping &&
36
- schema.discriminatorMapping.key;
37
+ const discriminatorKey = schema.discriminatorMapping?.key;
37
38
  if (discriminatorKey && model != null) {
38
- if (doc != null && doc[discriminatorKey] != null) {
39
+ if (doc?.[discriminatorKey] != null) {
39
40
  const discriminator = getDiscriminatorByValue(model.discriminators, doc[discriminatorKey]);
40
- schema = discriminator ? discriminator.schema : schema;
41
+ schema = discriminator?.schema || schema;
41
42
  } else if (model.discriminators != null) {
42
43
  return Object.keys(model.discriminators).reduce((arr, name) => {
43
44
  const disc = model.discriminators[name];
@@ -58,14 +59,14 @@ module.exports = function getSchemaTypes(model, schema, doc, path) {
58
59
  continue;
59
60
  }
60
61
 
61
- if (foundschema.caster) {
62
+ if (foundschema.embeddedSchemaType || foundschema.schema) {
62
63
  // array of Mixed?
63
- if (foundschema.caster instanceof Mixed) {
64
- return foundschema.caster;
64
+ if (foundschema.embeddedSchemaType instanceof Mixed) {
65
+ return foundschema.embeddedSchemaType;
65
66
  }
66
67
 
67
68
  let schemas = null;
68
- if (foundschema.schema != null && foundschema.schema.discriminators != null) {
69
+ if (foundschema.schema?.discriminators != null) {
69
70
  const discriminators = foundschema.schema.discriminators;
70
71
  const discriminatorKeyPath = trypath + '.' +
71
72
  foundschema.schema.options.discriminatorKey;
@@ -101,8 +102,8 @@ module.exports = function getSchemaTypes(model, schema, doc, path) {
101
102
  nestedPath.concat(parts.slice(0, p))
102
103
  );
103
104
  if (ret) {
104
- ret.$isUnderneathDocArray = ret.$isUnderneathDocArray ||
105
- !foundschema.schema.$isSingleNested;
105
+ ret.$parentSchemaDocArray = ret.$parentSchemaDocArray ||
106
+ (foundschema.schema.$isSingleNested ? null : foundschema);
106
107
  }
107
108
  return ret;
108
109
  }
@@ -117,10 +118,10 @@ module.exports = function getSchemaTypes(model, schema, doc, path) {
117
118
  nestedPath.concat(parts.slice(0, p))
118
119
  );
119
120
  if (_ret != null) {
120
- _ret.$isUnderneathDocArray = _ret.$isUnderneathDocArray ||
121
- !foundschema.schema.$isSingleNested;
122
- if (_ret.$isUnderneathDocArray) {
123
- ret.$isUnderneathDocArray = true;
121
+ _ret.$parentSchemaDocArray = _ret.$parentSchemaDocArray ||
122
+ (foundschema.schema.$isSingleNested ? null : foundschema);
123
+ if (_ret.$parentSchemaDocArray) {
124
+ ret.$parentSchemaDocArray = _ret.$parentSchemaDocArray;
124
125
  }
125
126
  ret.push(_ret);
126
127
  }
@@ -135,18 +136,18 @@ module.exports = function getSchemaTypes(model, schema, doc, path) {
135
136
  );
136
137
 
137
138
  if (ret) {
138
- ret.$isUnderneathDocArray = ret.$isUnderneathDocArray ||
139
- !foundschema.schema.$isSingleNested;
139
+ ret.$parentSchemaDocArray = ret.$parentSchemaDocArray ||
140
+ (foundschema.schema.$isSingleNested ? null : foundschema);
140
141
  }
141
142
  return ret;
142
143
  }
143
144
  } else if (p !== parts.length &&
144
145
  foundschema.$isMongooseArray &&
145
- foundschema.casterConstructor.$isMongooseArray) {
146
+ foundschema.embeddedSchemaType.$isMongooseArray) {
146
147
  // Nested arrays. Drill down to the bottom of the nested array.
147
148
  let type = foundschema;
148
149
  while (type.$isMongooseArray && !type.$isMongooseDocumentArray) {
149
- type = type.casterConstructor;
150
+ type = type.embeddedSchemaType;
150
151
  }
151
152
 
152
153
  const ret = search(
@@ -178,8 +179,8 @@ module.exports = function getSchemaTypes(model, schema, doc, path) {
178
179
  }
179
180
 
180
181
  const fullPath = nestedPath.concat([trypath]).join('.');
181
- if (topLevelDoc != null && topLevelDoc.$__ && topLevelDoc.$populated(fullPath) && p < parts.length) {
182
- const model = doc.$__.populated[fullPath].options[populateModelSymbol];
182
+ if (isMongooseDocument(topLevelDoc) && topLevelDoc.$populated(fullPath, true) && p < parts.length) {
183
+ const model = topLevelDoc.$populated(fullPath, true).options[populateModelSymbol];
183
184
  if (model != null) {
184
185
  const ret = search(
185
186
  parts.slice(p),
@@ -188,10 +189,6 @@ module.exports = function getSchemaTypes(model, schema, doc, path) {
188
189
  nestedPath.concat(parts.slice(0, p))
189
190
  );
190
191
 
191
- if (ret) {
192
- ret.$isUnderneathDocArray = ret.$isUnderneathDocArray ||
193
- !model.schema.$isSingleNested;
194
- }
195
192
  return ret;
196
193
  }
197
194
  }
@@ -202,7 +199,7 @@ module.exports = function getSchemaTypes(model, schema, doc, path) {
202
199
  leanPopulateMap.get(_val[0]) :
203
200
  leanPopulateMap.get(_val);
204
201
  // Populated using lean, `leanPopulateMap` value is the foreign model
205
- const schema = model != null ? model.schema : null;
202
+ const schema = model?.schema ?? null;
206
203
  if (schema != null) {
207
204
  const ret = search(
208
205
  parts.slice(p),
@@ -212,8 +209,8 @@ module.exports = function getSchemaTypes(model, schema, doc, path) {
212
209
  );
213
210
 
214
211
  if (ret != null) {
215
- ret.$isUnderneathDocArray = ret.$isUnderneathDocArray ||
216
- !schema.$isSingleNested;
212
+ ret.$parentSchemaDocArray = ret.$parentSchemaDocArray ||
213
+ (schema.$isSingleNested ? null : schema);
217
214
  return ret;
218
215
  }
219
216
  }
@@ -222,7 +219,7 @@ module.exports = function getSchemaTypes(model, schema, doc, path) {
222
219
  }
223
220
  }
224
221
  // look for arrays
225
- const parts = path.split('.');
222
+ parts = parts || path.split('.');
226
223
  for (let i = 0; i < parts.length; ++i) {
227
224
  if (parts[i] === '$') {
228
225
  // Re: gh-5628, because `schema.path()` doesn't take $ into account.
@@ -58,6 +58,37 @@ function getVirtual(schema, name) {
58
58
  nestedSchemaPath += (nestedSchemaPath.length > 0 ? '.' : '') + cur;
59
59
  cur = '';
60
60
  continue;
61
+ } else if (schema.paths[cur]?.$isSchemaMap && schema.paths[cur].$__schemaType?.schema) {
62
+ schema = schema.paths[cur].$__schemaType.schema;
63
+ ++i;
64
+ const rest = parts.slice(i + 1).join('.');
65
+
66
+ if (schema.virtuals[rest]) {
67
+ if (i === parts.length - 2) {
68
+ return {
69
+ virtual: schema.virtuals[rest],
70
+ nestedSchemaPath: [nestedSchemaPath, cur, '$*'].filter(v => !!v).join('.')
71
+ };
72
+ }
73
+ continue;
74
+ }
75
+
76
+ if (i + 1 < parts.length && schema.discriminators) {
77
+ for (const key of Object.keys(schema.discriminators)) {
78
+ const res = getVirtual(schema.discriminators[key], rest);
79
+ if (res != null) {
80
+ const _path = [nestedSchemaPath, cur, res.nestedSchemaPath, '$*'].
81
+ filter(v => !!v).join('.');
82
+ return {
83
+ virtual: res.virtual,
84
+ nestedSchemaPath: _path
85
+ };
86
+ }
87
+ }
88
+ }
89
+
90
+ nestedSchemaPath += (nestedSchemaPath.length > 0 ? '.' : '') + '$*' + cur;
91
+ cur = '';
61
92
  }
62
93
 
63
94
  if (schema.discriminators) {
@@ -12,16 +12,16 @@ const utils = require('../../utils');
12
12
  * doc.comments[0].populated('author'); // Should be set
13
13
  *
14
14
  * @param {Document} doc
15
- * @param {Object} [populated]
15
+ * @param {object} [populated]
16
16
  * @api private
17
17
  */
18
18
 
19
19
  module.exports = function markArraySubdocsPopulated(doc, populated) {
20
- if (doc._id == null || populated == null || populated.length === 0) {
20
+ if (doc._doc._id == null || populated == null || populated.length === 0) {
21
21
  return;
22
22
  }
23
23
 
24
- const id = String(doc._id);
24
+ const id = String(doc._doc._id);
25
25
  for (const item of populated) {
26
26
  if (item.isVirtual) {
27
27
  continue;
@@ -38,7 +38,9 @@ module.exports = function markArraySubdocsPopulated(doc, populated) {
38
38
 
39
39
  if (utils.isMongooseDocumentArray(val)) {
40
40
  for (let j = 0; j < val.length; ++j) {
41
- val[j].populated(rest, item._docs[id] == null ? void 0 : item._docs[id][j], item);
41
+ if (val[j]) {
42
+ val[j].populated(rest, item._docs[id] == null ? void 0 : item._docs[id][j], item);
43
+ }
42
44
  }
43
45
  break;
44
46
  }
@@ -14,7 +14,11 @@ module.exports = function modelNamesFromRefPath(refPath, doc, populatedPath, mod
14
14
  return [];
15
15
  }
16
16
 
17
- if (typeof refPath === 'string' && queryProjection != null && isPathExcluded(queryProjection, refPath)) {
17
+ if (typeof refPath !== 'string') {
18
+ throw new MongooseError('`refPath` must be a string or a function that returns a string, got ' + util.inspect(refPath));
19
+ }
20
+
21
+ if (queryProjection != null && isPathExcluded(queryProjection, refPath)) {
18
22
  throw new MongooseError('refPath `' + refPath + '` must not be excluded in projection, got ' +
19
23
  util.inspect(queryProjection));
20
24
  }
@@ -35,7 +39,11 @@ module.exports = function modelNamesFromRefPath(refPath, doc, populatedPath, mod
35
39
  // 2nd, 4th, etc. will be numeric props. For example: `[ 'a', '.0.', 'b' ]`
36
40
  for (let i = 0; i < chunks.length; i += 2) {
37
41
  const chunk = chunks[i];
38
- if (_remaining.startsWith(chunk + '.')) {
42
+ if (
43
+ _remaining.length >= chunk.length + 1 &&
44
+ _remaining.charAt(chunk.length) === '.' &&
45
+ _remaining.slice(0, chunk.length) === chunk
46
+ ) {
39
47
  _refPath += _remaining.substring(0, chunk.length) + chunks[i + 1];
40
48
  _remaining = _remaining.substring(chunk.length + 1);
41
49
  } else if (i === chunks.length - 1) {
@@ -56,13 +64,11 @@ module.exports = function modelNamesFromRefPath(refPath, doc, populatedPath, mod
56
64
  const refValue = mpath.get(refPath, doc, lookupLocalFields);
57
65
 
58
66
  let modelNames;
59
- if (modelSchema != null && modelSchema.virtuals.hasOwnProperty(refPath)) {
67
+ if (modelSchema != null && Object.hasOwn(modelSchema.virtuals, refPath)) {
60
68
  modelNames = [modelSchema.virtuals[refPath].applyGetters(void 0, doc)];
61
69
  } else {
62
70
  modelNames = Array.isArray(refValue) ? refValue : [refValue];
63
71
  }
64
72
 
65
- modelNames = utils.array.flatten(modelNames);
66
-
67
73
  return modelNames;
68
74
  };
@@ -1,6 +1,7 @@
1
1
  'use strict';
2
2
 
3
3
  const get = require('../get');
4
+ const isMongooseDocument = require('../isMongooseDocument');
4
5
  const mpath = require('mpath');
5
6
  const parseProjection = require('../projection/parseProjection');
6
7
 
@@ -16,12 +17,12 @@ module.exports = function removeDeselectedForeignField(foreignFields, options, d
16
17
  return;
17
18
  }
18
19
  for (const foreignField of foreignFields) {
19
- if (!projection.hasOwnProperty('-' + foreignField)) {
20
+ if (!Object.hasOwn(projection, '-' + foreignField)) {
20
21
  continue;
21
22
  }
22
23
 
23
24
  for (const val of docs) {
24
- if (val.$__ != null) {
25
+ if (isMongooseDocument(val)) {
25
26
  mpath.unset(foreignField, val._doc);
26
27
  } else {
27
28
  mpath.unset(foreignField, val);
@@ -0,0 +1,21 @@
1
+ 'use strict';
2
+
3
+ /*!
4
+ * Store the read preference and read concern that the populate options `pops` inherit from
5
+ * `query`'s explicit settings. Schema-level `read` and `readConcern` defaults are not inherited:
6
+ * each populate query applies its own model's schema defaults. `_execPopulateQuery()` applies
7
+ * these unless the populate options set their own.
8
+ *
9
+ * Store them separately from `pop.options` because a query's clones share its populate options:
10
+ * inherited values written to `pop.options` would look like explicit settings to later executions.
11
+ */
12
+
13
+ module.exports = function setInheritedReadOptions(query, pops) {
14
+ const options = query.options;
15
+ const readPreference = 'readPreference' in options ? options.readPreference : undefined;
16
+
17
+ for (const pop of pops) {
18
+ pop._inheritedReadPreference = readPreference;
19
+ pop._inheritedReadConcern = options.readConcern;
20
+ }
21
+ };
@@ -0,0 +1,33 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * Set a populated virtual value on a document's `$$populatedVirtuals` value
5
+ *
6
+ * @param {object} populatedVirtuals A document's `$$populatedVirtuals`
7
+ * @param {string} name The virtual name
8
+ * @param {any} v The result of the populate query
9
+ * @param {object} options The populate options. This function handles `justOne` and `count` options.
10
+ * @returns {Document[]|Document|object|object[]} the populated virtual value that was set
11
+ */
12
+
13
+ module.exports = function setPopulatedVirtualValue(populatedVirtuals, name, v, options) {
14
+ if (options.justOne || options.count) {
15
+ populatedVirtuals[name] = Array.isArray(v) ?
16
+ v[0] :
17
+ v;
18
+
19
+ if (typeof populatedVirtuals[name] !== 'object') {
20
+ populatedVirtuals[name] = options.count ? v : null;
21
+ }
22
+ } else {
23
+ populatedVirtuals[name] = Array.isArray(v) ?
24
+ v :
25
+ v == null ? [] : [v];
26
+
27
+ populatedVirtuals[name] = populatedVirtuals[name].filter(function(doc) {
28
+ return doc && typeof doc === 'object';
29
+ });
30
+ }
31
+
32
+ return populatedVirtuals[name];
33
+ };
@@ -0,0 +1,81 @@
1
+ 'use strict';
2
+
3
+ const createPopulateQueryFilter = require('./createPopulateQueryFilter');
4
+ const get = require('../get');
5
+ const utils = require('../../utils');
6
+
7
+ module.exports = splitPopulateQuery;
8
+
9
+ /*!
10
+ * If a single populate query would have more than this many elements in its `$in` filter,
11
+ * Mongoose splits the populate into a separate query per document to avoid going over
12
+ * MongoDB's 16 MB BSON size limit on queries. Overwritable for testing purposes. See gh-5890.
13
+ */
14
+
15
+ splitPopulateQuery.maxInFilterLength = 50000;
16
+
17
+ /*!
18
+ * Split a populate models-map entry into a separate query per document if either:
19
+ *
20
+ * 1. The `perDocumentLimit` option is set, so each document needs its own query with its
21
+ * own `limit` (gh-7318), or
22
+ * 2. A single populate query for `mod` would have too many elements in its `$in` filter
23
+ * (gh-5890). With multiple foreign fields, `createPopulateQueryFilter()` repeats the ids
24
+ * under `$or` once per foreign field, so the threshold counts one copy of `ids` per
25
+ * foreign field.
26
+ *
27
+ * Returns a list of `[mod, match, select, assignmentOpts]` params, one per document, for
28
+ * `_execPopulateQuery()`. Returns `null` if the populate query doesn't need to be split.
29
+ * A `null` `match` means the document has no ids to query: `_execPopulateQuery()` skips
30
+ * executing a query, and `_assign()` just sets the document's populated path to the
31
+ * default value.
32
+ *
33
+ * Splitting on document boundaries means each document's populated value is the result of
34
+ * exactly one query, so split entries can typically be assigned from only their own query's
35
+ * results (`_assignFromOwnResults`) rather than scanning every populate query's results.
36
+ * refPath is the exception: a single document's array can contain ids for multiple models,
37
+ * so assigning refPath populate results relies on every query's results being available for
38
+ * every document. refPath entries are therefore only split when `perDocumentLimit` requires
39
+ * it, not to keep the `$in` filter small. A single document whose ids alone overflow the
40
+ * BSON size limit cannot be split.
41
+ */
42
+
43
+ function splitPopulateQuery(mod, ids, select, assignmentOpts) {
44
+ if (mod.docs.length <= 1) {
45
+ return null;
46
+ }
47
+ const perDocumentLimit = mod.options.perDocumentLimit == null ?
48
+ get(mod.options, 'options.perDocumentLimit', null) :
49
+ mod.options.perDocumentLimit;
50
+ const numInFilterElements = ids.length * mod.foreignField.size;
51
+ if (perDocumentLimit == null && (numInFilterElements <= splitPopulateQuery.maxInFilterLength || mod.isRefPath)) {
52
+ return null;
53
+ }
54
+
55
+ return mod.docs.map((doc, i) => {
56
+ const subMod = {
57
+ ...mod,
58
+ docs: [doc],
59
+ ids: [mod.ids[i]],
60
+ allIds: [mod.allIds[i]],
61
+ unpopulatedValues: [mod.unpopulatedValues[i]],
62
+ match: Array.isArray(mod.match) ? [mod.match[i]] : mod.match,
63
+ _assignFromOwnResults: !mod.isRefPath
64
+ };
65
+ let subIds = utils.array.flatten(subMod.ids, flatten);
66
+ subIds = utils.array.unique(subIds);
67
+ const match = subIds.length === 0 || subIds.every(utils.isNullOrUndefined) ?
68
+ null :
69
+ createPopulateQueryFilter(subIds, subMod.match, subMod.foreignField, subMod.model, subMod.options.skipInvalidIds);
70
+ return [subMod, match, select, assignmentOpts];
71
+ });
72
+ }
73
+
74
+ /*!
75
+ * ignore
76
+ */
77
+
78
+ function flatten(item) {
79
+ // no need to include undefined values in our query
80
+ return undefined !== item;
81
+ }
@@ -11,7 +11,7 @@ if (typeof jest !== 'undefined' && !process.env.SUPPRESS_JEST_WARNINGS) {
11
11
  'to hide this warning.');
12
12
  }
13
13
 
14
- if (setTimeout.clock != null && typeof setTimeout.clock.Date === 'function') {
14
+ if (typeof setTimeout.clock?.Date === 'function') {
15
15
  utils.warn('Mongoose: looks like you\'re trying to test a Mongoose app ' +
16
16
  'with Jest\'s mock timers enabled. Please make sure you read ' +
17
17
  'Mongoose\'s docs on configuring Jest to test Node.js apps: ' +
@@ -6,7 +6,7 @@ const MongooseError = require('../error/index');
6
6
  function processConnectionOptions(uri, options) {
7
7
  const opts = options ? options : {};
8
8
  const readPreference = opts.readPreference
9
- ? opts.readPreference
9
+ ? getReadPreferenceMode(opts.readPreference)
10
10
  : getUriReadPreference(uri);
11
11
 
12
12
  const clonedOpts = clone(opts);
@@ -31,7 +31,7 @@ function resolveOptsConflicts(pref, opts) {
31
31
  }
32
32
 
33
33
  function setsIndexOptions(opts) {
34
- const configIdx = opts.config && opts.config.autoIndex;
34
+ const configIdx = opts.config?.autoIndex;
35
35
  const { autoCreate, autoIndex } = opts;
36
36
  return !!(configIdx || autoCreate || autoIndex);
37
37
  }
@@ -40,6 +40,11 @@ function setsSecondaryRead(prefString) {
40
40
  return !!(prefString === 'secondary' || prefString === 'secondaryPreferred');
41
41
  }
42
42
 
43
+ function getReadPreferenceMode(readPreference) {
44
+ // the MongoDB driver also accepts a `ReadPreference` instance or a `{ mode }` object
45
+ return typeof readPreference === 'string' ? readPreference : readPreference.mode;
46
+ }
47
+
43
48
  function getUriReadPreference(connectionString) {
44
49
  const exp = /(?:&|\?)readPreference=(\w+)(?:&|$)/;
45
50
  const match = exp.exec(connectionString);
@@ -35,12 +35,15 @@ function applyExclusiveProjection(doc, projection, hasIncludedChildren, projecti
35
35
  if (doc == null || typeof doc !== 'object') {
36
36
  return doc;
37
37
  }
38
+ if (Array.isArray(doc)) {
39
+ return doc.map(el => applyExclusiveProjection(el, projection, hasIncludedChildren, projectionLimb, prefix));
40
+ }
38
41
  const ret = { ...doc };
39
42
  projectionLimb = prefix ? (projectionLimb || {}) : projection;
40
43
 
41
44
  for (const key of Object.keys(ret)) {
42
45
  const fullPath = prefix ? prefix + '.' + key : key;
43
- if (projection.hasOwnProperty(fullPath) || projectionLimb.hasOwnProperty(key)) {
46
+ if (Object.hasOwn(projection, fullPath) || Object.hasOwn(projectionLimb, key)) {
44
47
  if (isPOJO(projection[fullPath]) || isPOJO(projectionLimb[key])) {
45
48
  ret[key] = applyExclusiveProjection(ret[key], projection, hasIncludedChildren, projectionLimb[key], fullPath);
46
49
  } else {
@@ -57,12 +60,15 @@ function applyInclusiveProjection(doc, projection, hasIncludedChildren, projecti
57
60
  if (doc == null || typeof doc !== 'object') {
58
61
  return doc;
59
62
  }
63
+ if (Array.isArray(doc)) {
64
+ return doc.map(el => applyInclusiveProjection(el, projection, hasIncludedChildren, projectionLimb, prefix));
65
+ }
60
66
  const ret = { ...doc };
61
67
  projectionLimb = prefix ? (projectionLimb || {}) : projection;
62
68
 
63
69
  for (const key of Object.keys(ret)) {
64
70
  const fullPath = prefix ? prefix + '.' + key : key;
65
- if (projection.hasOwnProperty(fullPath) || projectionLimb.hasOwnProperty(key)) {
71
+ if (Object.hasOwn(projection, fullPath) || Object.hasOwn(projectionLimb, key)) {
66
72
  if (isPOJO(projection[fullPath]) || isPOJO(projectionLimb[key])) {
67
73
  ret[key] = applyInclusiveProjection(ret[key], projection, hasIncludedChildren, projectionLimb[key], fullPath);
68
74
  }
@@ -12,7 +12,7 @@
12
12
  * res['a.b.c']; // 1
13
13
  * res['a.c']; // undefined
14
14
  *
15
- * @param {Object} fields
15
+ * @param {object} fields
16
16
  * @api private
17
17
  */
18
18
 
@@ -1,6 +1,7 @@
1
1
  'use strict';
2
2
 
3
3
  const isDefiningProjection = require('./isDefiningProjection');
4
+ const isPOJO = require('../isPOJO');
4
5
 
5
6
  /*!
6
7
  * ignore
@@ -12,21 +13,22 @@ module.exports = function isExclusive(projection) {
12
13
  }
13
14
 
14
15
  const keys = Object.keys(projection);
15
- let ki = keys.length;
16
16
  let exclude = null;
17
17
 
18
- if (ki === 1 && keys[0] === '_id') {
18
+ if (keys.length === 1 && keys[0] === '_id') {
19
19
  exclude = !projection._id;
20
20
  } else {
21
- while (ki--) {
21
+ for (let ki = 0; ki < keys.length; ++ki) {
22
22
  // Does this projection explicitly define inclusion/exclusion?
23
23
  // Explicitly avoid `$meta` and `$slice`
24
24
  const key = keys[ki];
25
25
  if (key !== '_id' && isDefiningProjection(projection[key])) {
26
- exclude = (projection[key] != null && typeof projection[key] === 'object') ?
27
- isExclusive(projection[key]) :
26
+ exclude = isPOJO(projection[key]) ?
27
+ (isExclusive(projection[key]) ?? exclude) :
28
28
  !projection[key];
29
- break;
29
+ if (exclude != null) {
30
+ break;
31
+ }
30
32
  }
31
33
  }
32
34
  }
@@ -1,6 +1,7 @@
1
1
  'use strict';
2
2
 
3
3
  const isDefiningProjection = require('./isDefiningProjection');
4
+ const isPOJO = require('../isPOJO');
4
5
 
5
6
  /*!
6
7
  * ignore
@@ -26,7 +27,7 @@ module.exports = function isInclusive(projection) {
26
27
  // If field is truthy (1, true, etc.) and not an object, then this
27
28
  // projection must be inclusive. If object, assume its $meta, $slice, etc.
28
29
  if (isDefiningProjection(projection[prop]) && !!projection[prop]) {
29
- if (projection[prop] != null && typeof projection[prop] === 'object') {
30
+ if (isPOJO(projection[prop])) {
30
31
  return isInclusive(projection[prop]);
31
32
  } else {
32
33
  return !!projection[prop];
@@ -5,9 +5,9 @@ const isDefiningProjection = require('./isDefiningProjection');
5
5
  /**
6
6
  * Determines if `path` is excluded by `projection`
7
7
  *
8
- * @param {Object} projection
9
- * @param {String} path
10
- * @return {Boolean}
8
+ * @param {object} projection
9
+ * @param {string} path
10
+ * @return {boolean}
11
11
  * @api private
12
12
  */
13
13
 
@@ -7,19 +7,9 @@
7
7
  module.exports = function isPathSelectedInclusive(fields, path) {
8
8
  const chunks = path.split('.');
9
9
  let cur = '';
10
- let j;
11
- let keys;
12
- let numKeys;
13
10
  for (let i = 0; i < chunks.length; ++i) {
14
- cur += cur.length ? '.' : '' + chunks[i];
11
+ cur += cur.length ? '.' + chunks[i] : chunks[i];
15
12
  if (fields[cur]) {
16
- keys = Object.keys(fields);
17
- numKeys = keys.length;
18
- for (j = 0; j < numKeys; ++j) {
19
- if (keys[i].indexOf(cur + '.') === 0 && keys[i].indexOf(path) !== 0) {
20
- continue;
21
- }
22
- }
23
13
  return true;
24
14
  }
25
15
  }
@@ -5,7 +5,7 @@
5
5
  *
6
6
  * @param {string} path1
7
7
  * @param {string} path2
8
- * @return {Boolean}
8
+ * @return {boolean}
9
9
  * @api private
10
10
  */
11
11
 
@@ -1,8 +1,13 @@
1
1
  'use strict';
2
2
 
3
3
  /**
4
- * Convert a string or array into a projection object, retaining all
5
- * `-` and `+` paths.
4
+ * Convert a string or array into a projection object. Treats `-foo` as
5
+ * equivalent to `foo: 0` depending on `retainMinusPaths`. If `retainMinusPaths`
6
+ * is true, then `-foo` will be included in the projection as `'-foo': 0`.
7
+ *
8
+ * @param {object|string|string[]} v
9
+ * @param {boolean} [retainMinusPaths]
10
+ * @return {object}
6
11
  */
7
12
 
8
13
  module.exports = function parseProjection(v, retainMinusPaths) {
@@ -22,9 +27,9 @@ module.exports = function parseProjection(v, retainMinusPaths) {
22
27
  if (!field) {
23
28
  continue;
24
29
  }
25
- const include = '-' == field[0] ? 0 : 1;
30
+ const include = field.charAt(0) === '-' ? 0 : 1;
26
31
  if (!retainMinusPaths && include === 0) {
27
- field = field.substring(1);
32
+ field = field.slice(1);
28
33
  }
29
34
  ret[field] = include;
30
35
  }