@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
@@ -1,13 +1,16 @@
1
1
  'use strict';
2
2
 
3
3
  const MongooseError = require('../../error/index');
4
- const SkipPopulateValue = require('./SkipPopulateValue');
4
+ const SkipPopulateValue = require('./skipPopulateValue');
5
+ const clone = require('../clone');
5
6
  const get = require('../get');
6
7
  const getDiscriminatorByKey = require('../discriminator/getDiscriminatorByKey');
7
8
  const getDiscriminatorByValue = require('../discriminator/getDiscriminatorByValue');
8
9
  const getConstructorName = require('../getConstructorName');
10
+ const getOwnProperty = require('../getOwnProperty');
9
11
  const getSchemaTypes = require('./getSchemaTypes');
10
12
  const getVirtual = require('./getVirtual');
13
+ const isMongooseDocument = require('../isMongooseDocument');
11
14
  const lookupLocalFields = require('./lookupLocalFields');
12
15
  const mpath = require('mpath');
13
16
  const modelNamesFromRefPath = require('./modelNamesFromRefPath');
@@ -17,15 +20,19 @@ const modelSymbol = require('../symbols').modelSymbol;
17
20
  const populateModelSymbol = require('../symbols').populateModelSymbol;
18
21
  const schemaMixedSymbol = require('../../schema/symbols').schemaMixedSymbol;
19
22
  const StrictPopulate = require('../../error/strictPopulate');
23
+ const numericPathSegmentPattern = '\\.\\d+(?=\\.|$)';
24
+ const hasNumericPathSegmentRE = new RegExp(numericPathSegmentPattern);
25
+ const numericPathSegmentRE = new RegExp(numericPathSegmentPattern, 'g');
20
26
 
21
27
  module.exports = function getModelsMapForPopulate(model, docs, options) {
22
28
  let doc;
23
29
  const len = docs.length;
24
30
  const map = [];
25
- const modelNameFromQuery = options.model && options.model.modelName || options.model;
31
+ const modelNameFromQuery = options.model?.modelName || options.model;
26
32
  let schema;
27
33
  let refPath;
28
34
  let modelNames;
35
+ let modelNamesSet;
29
36
  const available = {};
30
37
 
31
38
  const modelSchema = model.schema;
@@ -42,10 +49,12 @@ module.exports = function getModelsMapForPopulate(model, docs, options) {
42
49
  return _virtualPopulate(model, docs, options, _virtualRes);
43
50
  }
44
51
 
45
- let allSchemaTypes = getSchemaTypes(model, modelSchema, null, options.path);
52
+ const parts = modelSchema.paths[options.path]?.splitPath() ?? options.path.split('.');
53
+ let allSchemaTypes = getSchemaTypes(model, modelSchema, null, options.path, parts);
46
54
  allSchemaTypes = Array.isArray(allSchemaTypes) ? allSchemaTypes : [allSchemaTypes].filter(v => v != null);
47
55
 
48
- if (allSchemaTypes.length === 0 && options.strictPopulate !== false && options._localModel != null) {
56
+ const isStrictPopulateDisabled = options.strictPopulate === false || options.options?.strictPopulate === false;
57
+ if (!isStrictPopulateDisabled && allSchemaTypes.length === 0 && options._localModel != null) {
49
58
  return new StrictPopulate(options._fullPath || options.path);
50
59
  }
51
60
 
@@ -53,8 +62,15 @@ module.exports = function getModelsMapForPopulate(model, docs, options) {
53
62
  doc = docs[i];
54
63
  let justOne = null;
55
64
 
56
- const docSchema = doc != null && doc.$__ != null ? doc.$__schema : modelSchema;
57
- schema = getSchemaTypes(model, docSchema, doc, options.path);
65
+ if (isMongooseDocument(doc) && doc.populated(options.path)) {
66
+ const forceRepopulate = options.forceRepopulate ?? doc.constructor.base.options.forceRepopulate;
67
+ if (forceRepopulate === false) {
68
+ continue;
69
+ }
70
+ }
71
+
72
+ const docSchema = isMongooseDocument(doc) ? doc.$__schema : modelSchema;
73
+ schema = getSchemaTypes(model, docSchema, doc, options.path, parts);
58
74
 
59
75
  // Special case: populating a path that's a DocumentArray unless
60
76
  // there's an explicit `ref` or `refPath` re: gh-8946
@@ -64,7 +80,7 @@ module.exports = function getModelsMapForPopulate(model, docs, options) {
64
80
  schema.options.refPath == null) {
65
81
  continue;
66
82
  }
67
- const isUnderneathDocArray = schema && schema.$isUnderneathDocArray;
83
+ const isUnderneathDocArray = schema?.$parentSchemaDocArray;
68
84
  if (isUnderneathDocArray && get(options, 'options.sort') != null) {
69
85
  return new MongooseError('Cannot populate with `sort` on path ' + options.path +
70
86
  ' because it is a subproperty of a document array');
@@ -76,7 +92,7 @@ module.exports = function getModelsMapForPopulate(model, docs, options) {
76
92
  let schemaOptions = null;
77
93
  let modelNamesInOrder = null;
78
94
 
79
- if (schema != null && schema.instance === 'Embedded') {
95
+ if (schema?.instance === 'Embedded') {
80
96
  if (schema.options.ref) {
81
97
  const data = {
82
98
  localField: options.path + '._id',
@@ -115,8 +131,10 @@ module.exports = function getModelsMapForPopulate(model, docs, options) {
115
131
  continue;
116
132
  }
117
133
  modelNames = modelNames || [];
134
+ modelNamesSet = modelNamesSet || new Set();
118
135
  for (const modelName of _modelNames) {
119
- if (modelNames.indexOf(modelName) === -1) {
136
+ if (modelNamesSet.has(modelName) === false) {
137
+ modelNamesSet.add(modelName);
120
138
  modelNames.push(modelName);
121
139
  }
122
140
  }
@@ -190,8 +208,11 @@ module.exports = function getModelsMapForPopulate(model, docs, options) {
190
208
  data.modelNamesInOrder = modelNamesInOrder;
191
209
 
192
210
  if (isRefPath) {
211
+ const normalizedRefPathForDiscriminators = typeof normalizedRefPath === 'string' ?
212
+ normalizedRefPath.replace(numericPathSegmentRE, '') :
213
+ normalizedRefPath;
193
214
  const embeddedDiscriminatorModelNames = _findRefPathForDiscriminators(doc,
194
- modelSchema, data, options, normalizedRefPath, ret);
215
+ modelSchema, data, options, normalizedRefPathForDiscriminators, ret);
195
216
 
196
217
  modelNames = embeddedDiscriminatorModelNames || modelNames;
197
218
  }
@@ -204,23 +225,23 @@ module.exports = function getModelsMapForPopulate(model, docs, options) {
204
225
  }
205
226
  return map;
206
227
 
207
- function _getModelNames(doc, schema, modelNameFromQuery, model) {
228
+ function _getModelNames(doc, schemaType, modelNameFromQuery, model) {
208
229
  let modelNames;
209
230
  let isRefPath = false;
210
231
  let justOne = null;
211
232
 
212
- const originalSchema = schema;
213
- if (schema && schema.instance === 'Array') {
214
- schema = schema.caster;
233
+ const originalSchema = schemaType;
234
+ if (schemaType?.instance === 'Array') {
235
+ schemaType = schemaType.embeddedSchemaType;
215
236
  }
216
- if (schema && schema.$isSchemaMap) {
217
- schema = schema.$__schemaType;
237
+ if (schemaType?.$isSchemaMap) {
238
+ schemaType = schemaType.$__schemaType;
218
239
  }
219
240
 
220
- const ref = schema && schema.options && schema.options.ref;
221
- refPath = schema && schema.options && schema.options.refPath;
222
- if (schema != null &&
223
- schema[schemaMixedSymbol] &&
241
+ const ref = schemaType?.options?.ref;
242
+ refPath = schemaType?.options?.refPath;
243
+ if (schemaType != null &&
244
+ schemaType[schemaMixedSymbol] &&
224
245
  !ref &&
225
246
  !refPath &&
226
247
  !modelNameFromQuery) {
@@ -231,19 +252,9 @@ module.exports = function getModelsMapForPopulate(model, docs, options) {
231
252
  modelNames = [modelNameFromQuery]; // query options
232
253
  } else if (refPath != null) {
233
254
  if (typeof refPath === 'function') {
234
- const subdocPath = options.path.slice(0, options.path.length - schema.path.length - 1);
235
- const vals = mpath.get(subdocPath, doc, lookupLocalFields);
236
- const subdocsBeingPopulated = Array.isArray(vals) ?
237
- utils.array.flatten(vals) :
238
- (vals ? [vals] : []);
239
-
240
- modelNames = new Set();
241
- for (const subdoc of subdocsBeingPopulated) {
242
- refPath = refPath.call(subdoc, subdoc, options.path);
243
- modelNamesFromRefPath(refPath, doc, options.path, modelSchema, options._queryProjection).
244
- forEach(name => modelNames.add(name));
245
- }
246
- modelNames = Array.from(modelNames);
255
+ const res = _getModelNamesFromFunctionRefPath(refPath, doc, schemaType, options.path, modelSchema, options._queryProjection);
256
+ modelNames = res.modelNames;
257
+ refPath = res.refPath;
247
258
  } else {
248
259
  modelNames = modelNamesFromRefPath(refPath, doc, options.path, modelSchema, options._queryProjection);
249
260
  }
@@ -257,7 +268,7 @@ module.exports = function getModelsMapForPopulate(model, docs, options) {
257
268
  let modelForCurrentDoc = model;
258
269
  const discriminatorKey = model.schema.options.discriminatorKey;
259
270
 
260
- if (!schema && discriminatorKey && (discriminatorValue = utils.getValue(discriminatorKey, doc))) {
271
+ if (!schemaType && discriminatorKey && (discriminatorValue = utils.getValue(discriminatorKey, doc))) {
261
272
  // `modelNameForFind` is the discriminator value, so we might need
262
273
  // find the discriminated model name
263
274
  const discriminatorModel = getDiscriminatorByValue(model.discriminators, discriminatorValue) || model;
@@ -273,11 +284,11 @@ module.exports = function getModelsMapForPopulate(model, docs, options) {
273
284
 
274
285
  schemaForCurrentDoc = modelForCurrentDoc.schema._getSchema(options.path);
275
286
 
276
- if (schemaForCurrentDoc && schemaForCurrentDoc.caster) {
277
- schemaForCurrentDoc = schemaForCurrentDoc.caster;
287
+ if (schemaForCurrentDoc?.embeddedSchemaType) {
288
+ schemaForCurrentDoc = schemaForCurrentDoc.embeddedSchemaType;
278
289
  }
279
290
  } else {
280
- schemaForCurrentDoc = schema;
291
+ schemaForCurrentDoc = schemaType;
281
292
  }
282
293
 
283
294
  if (originalSchema && originalSchema.path.endsWith('.$*')) {
@@ -311,22 +322,12 @@ module.exports = function getModelsMapForPopulate(model, docs, options) {
311
322
  ref = handleRefFunction(ref, doc);
312
323
  modelNames = [ref];
313
324
  }
314
- } else if ((schemaForCurrentDoc = get(schema, 'options.refPath')) != null) {
325
+ } else if ((refPath = get(schemaForCurrentDoc, 'options.refPath')) != null) {
315
326
  isRefPath = true;
316
327
  if (typeof refPath === 'function') {
317
- const subdocPath = options.path.slice(0, options.path.length - schemaForCurrentDoc.path.length - 1);
318
- const vals = mpath.get(subdocPath, doc, lookupLocalFields);
319
- const subdocsBeingPopulated = Array.isArray(vals) ?
320
- utils.array.flatten(vals) :
321
- (vals ? [vals] : []);
322
-
323
- modelNames = new Set();
324
- for (const subdoc of subdocsBeingPopulated) {
325
- refPath = refPath.call(subdoc, subdoc, options.path);
326
- modelNamesFromRefPath(refPath, doc, options.path, modelSchema, options._queryProjection).
327
- forEach(name => modelNames.add(name));
328
- }
329
- modelNames = Array.from(modelNames);
328
+ const res = _getModelNamesFromFunctionRefPath(refPath, doc, schemaForCurrentDoc, options.path, modelSchema, options._queryProjection);
329
+ modelNames = res.modelNames;
330
+ refPath = res.refPath;
330
331
  } else {
331
332
  modelNames = modelNamesFromRefPath(refPath, doc, options.path, modelSchema, options._queryProjection);
332
333
  }
@@ -350,6 +351,137 @@ module.exports = function getModelsMapForPopulate(model, docs, options) {
350
351
  }
351
352
  };
352
353
 
354
+ /**
355
+ * Resolve model names for function-style `refPath` and return the first
356
+ * resolved refPath value so discriminator handling can inspect it later.
357
+ *
358
+ * @param {Function} refPath
359
+ * @param {Document|object} doc
360
+ * @param {SchemaType} schema
361
+ * @param {string} populatePath
362
+ * @param {Schema} modelSchema
363
+ * @param {object} queryProjection
364
+ * @returns {{modelNames: string[], refPath: string|null}}
365
+ * @private
366
+ */
367
+ function _getModelNamesFromFunctionRefPath(refPath, doc, schemaType, populatePath, modelSchema, queryProjection) {
368
+ const modelNames = [];
369
+ let normalizedRefPath = null;
370
+ const schemaPath = schemaType?.path;
371
+
372
+ if (schemaPath != null &&
373
+ populatePath.length > schemaPath.length + 1 &&
374
+ populatePath.charAt(populatePath.length - schemaPath.length - 1) === '.' &&
375
+ populatePath.slice(populatePath.length - schemaPath.length) === schemaPath
376
+ ) {
377
+ const subdocPath = populatePath.slice(0, populatePath.length - schemaPath.length - 1);
378
+ const segments = subdocPath.indexOf('.') === -1 ? [subdocPath] : subdocPath.split('.');
379
+ let hasSubdoc = false;
380
+
381
+ walkSubdocs(doc, '', 0);
382
+ if (hasSubdoc) {
383
+ return { modelNames, refPath: normalizedRefPath };
384
+ }
385
+
386
+ function walkSubdocs(currentSubdoc, indexedPathPrefix, segmentIndex) {
387
+ if (currentSubdoc == null) {
388
+ return;
389
+ }
390
+
391
+ if (segmentIndex >= segments.length) {
392
+ hasSubdoc = true;
393
+ const indexedPath = indexedPathPrefix + '.' + schemaPath;
394
+ const subdocRefPath = refPath.call(currentSubdoc, currentSubdoc, indexedPath);
395
+ normalizedRefPath = normalizedRefPath || subdocRefPath;
396
+ modelNames.push(..._getModelNamesFromRefPath(subdocRefPath, doc, populatePath, indexedPath, modelSchema, queryProjection));
397
+ return;
398
+ }
399
+
400
+ const segment = segments[segmentIndex];
401
+ const source = currentSubdoc?._doc ?? currentSubdoc;
402
+
403
+ if (segment === '$*') {
404
+ if (source instanceof Map) {
405
+ for (const [key, value] of source.entries()) {
406
+ if (value != null) {
407
+ const valuePath = indexedPathPrefix.length === 0 ?
408
+ key :
409
+ indexedPathPrefix + '.' + key;
410
+ walkSubdocs(value, valuePath, segmentIndex + 1);
411
+ }
412
+ }
413
+ return;
414
+ }
415
+
416
+ if (source != null && typeof source === 'object') {
417
+ for (const key of Object.keys(source)) {
418
+ const value = source[key];
419
+ if (value != null) {
420
+ const valuePath = indexedPathPrefix.length === 0 ?
421
+ key :
422
+ indexedPathPrefix + '.' + key;
423
+ walkSubdocs(value, valuePath, segmentIndex + 1);
424
+ }
425
+ }
426
+ }
427
+ return;
428
+ }
429
+
430
+ const child = source[segment];
431
+ const childPath = indexedPathPrefix.length === 0 ?
432
+ segment :
433
+ indexedPathPrefix + '.' + segment;
434
+
435
+ if (Array.isArray(child)) {
436
+ for (let i = 0; i < child.length; ++i) {
437
+ if (child[i] != null) {
438
+ walkSubdocs(child[i], childPath + '.' + i, segmentIndex + 1);
439
+ }
440
+ }
441
+ } else if (child != null) {
442
+ walkSubdocs(child, childPath, segmentIndex + 1);
443
+ }
444
+ }
445
+ }
446
+
447
+ const topLevelRefPath = refPath.call(doc, doc, populatePath);
448
+ normalizedRefPath = normalizedRefPath || topLevelRefPath;
449
+ modelNames.push(...modelNamesFromRefPath(topLevelRefPath, doc, populatePath, modelSchema, queryProjection));
450
+
451
+ return { modelNames, refPath: normalizedRefPath };
452
+ }
453
+
454
+ /**
455
+ * Resolve model names from a refPath, preferring the indexed populated path
456
+ * for array subdocuments and falling back to the original populate path if
457
+ * normalization fails.
458
+ *
459
+ * @param {string|Function} refPath
460
+ * @param {Document|object} doc
461
+ * @param {string} populatePath
462
+ * @param {string} indexedPath
463
+ * @param {Schema} modelSchema
464
+ * @param {object} queryProjection
465
+ * @returns {string[]}
466
+ * @private
467
+ */
468
+ function _getModelNamesFromRefPath(refPath, doc, populatePath, indexedPath, modelSchema, queryProjection) {
469
+ const populatedPath = typeof refPath === 'string' && hasNumericPathSegmentRE.test(refPath) ?
470
+ populatePath :
471
+ indexedPath;
472
+
473
+ try {
474
+ return modelNamesFromRefPath(refPath, doc, populatedPath, modelSchema, queryProjection);
475
+ } catch (error) {
476
+ if (populatedPath === indexedPath &&
477
+ typeof error?.message === 'string' &&
478
+ error.message.startsWith('Could not normalize ref path')) {
479
+ return modelNamesFromRefPath(refPath, doc, populatePath, modelSchema, queryProjection);
480
+ }
481
+ throw error;
482
+ }
483
+ }
484
+
353
485
  /*!
354
486
  * ignore
355
487
  */
@@ -378,20 +510,19 @@ function _virtualPopulate(model, docs, options, _virtualRes) {
378
510
  }
379
511
  data.count = virtual.options.count;
380
512
 
381
- if (virtual.options.skip != null && !options.hasOwnProperty('skip')) {
513
+ if (virtual.options.skip != null && !Object.hasOwn(options, 'skip')) {
382
514
  options.skip = virtual.options.skip;
383
515
  }
384
- if (virtual.options.limit != null && !options.hasOwnProperty('limit')) {
516
+ if (virtual.options.limit != null && !Object.hasOwn(options, 'limit')) {
385
517
  options.limit = virtual.options.limit;
386
518
  }
387
- if (virtual.options.perDocumentLimit != null && !options.hasOwnProperty('perDocumentLimit')) {
519
+ if (virtual.options.perDocumentLimit != null && !Object.hasOwn(options, 'perDocumentLimit')) {
388
520
  options.perDocumentLimit = virtual.options.perDocumentLimit;
389
521
  }
390
522
  let foreignField = virtual.options.foreignField;
391
523
 
392
524
  if (!localField || !foreignField) {
393
- return new MongooseError('If you are populating a virtual, you must set the ' +
394
- 'localField and foreignField options');
525
+ return new MongooseError(`Cannot populate virtual \`${options.path}\` on model \`${model.modelName}\`, because options \`localField\` and / or \`foreignField\` are missing`);
395
526
  }
396
527
 
397
528
  if (typeof localField === 'function') {
@@ -411,26 +542,20 @@ function _virtualPopulate(model, docs, options, _virtualRes) {
411
542
  justOne = options.justOne;
412
543
  }
413
544
 
545
+ // Use the correct target doc/sub-doc for dynamic ref on nested schema. See gh-12363
546
+ if (_virtualRes.nestedSchemaPath && typeof virtual.options.ref === 'function') {
547
+ const subdocs = utils.getValue(_virtualRes.nestedSchemaPath, doc);
548
+ modelNames = Array.isArray(subdocs)
549
+ ? subdocs.flatMap(subdoc => virtual._getModelNamesForPopulate(subdoc))
550
+ : virtual._getModelNamesForPopulate(subdocs);
551
+ } else {
552
+ modelNames = virtual._getModelNamesForPopulate(doc);
553
+ }
414
554
  if (virtual.options.refPath) {
415
- modelNames =
416
- modelNamesFromRefPath(virtual.options.refPath, doc, options.path);
417
555
  justOne = !!virtual.options.justOne;
418
556
  data.isRefPath = true;
419
557
  } else if (virtual.options.ref) {
420
- let normalizedRef;
421
- if (typeof virtual.options.ref === 'function' && !virtual.options.ref[modelSymbol]) {
422
- normalizedRef = virtual.options.ref.call(doc, doc);
423
- } else {
424
- normalizedRef = virtual.options.ref;
425
- }
426
558
  justOne = !!virtual.options.justOne;
427
- // When referencing nested arrays, the ref should be an Array
428
- // of modelNames.
429
- if (Array.isArray(normalizedRef)) {
430
- modelNames = normalizedRef;
431
- } else {
432
- modelNames = [normalizedRef];
433
- }
434
559
  }
435
560
 
436
561
  data.isVirtual = true;
@@ -438,13 +563,13 @@ function _virtualPopulate(model, docs, options, _virtualRes) {
438
563
  data.justOne = justOne;
439
564
 
440
565
  // `match`
441
- let match = get(options, 'match', null) ||
442
- get(data, 'virtual.options.match', null) ||
566
+ const baseMatch = get(data, 'virtual.options.match', null) ||
443
567
  get(data, 'virtual.options.options.match', null);
568
+ let match = get(options, 'match', null) || baseMatch;
444
569
 
445
570
  let hasMatchFunction = typeof match === 'function';
446
571
  if (hasMatchFunction) {
447
- match = match.call(doc, doc);
572
+ match = match.call(doc, doc, data.virtual);
448
573
  }
449
574
 
450
575
  if (Array.isArray(localField) && Array.isArray(foreignField) && localField.length === foreignField.length) {
@@ -484,7 +609,7 @@ function _virtualPopulate(model, docs, options, _virtualRes) {
484
609
  function addModelNamesToMap(model, map, available, modelNames, options, data, ret, doc, schemaOptions, unpopulatedValue) {
485
610
  // `PopulateOptions#connection`: if the model is passed as a string, the
486
611
  // connection matters because different connections have different models.
487
- const connection = options.connection != null ? options.connection : model.db;
612
+ const connection = options.connection ?? model.db;
488
613
 
489
614
  unpopulatedValue = unpopulatedValue === void 0 ? ret : unpopulatedValue;
490
615
  if (Array.isArray(unpopulatedValue)) {
@@ -495,9 +620,10 @@ function addModelNamesToMap(model, map, available, modelNames, options, data, re
495
620
  return;
496
621
  }
497
622
 
498
- let k = modelNames.length;
623
+ const flatModelNames = utils.array.flatten(modelNames);
624
+ let k = flatModelNames.length;
499
625
  while (k--) {
500
- const modelName = modelNames[k];
626
+ let modelName = flatModelNames[k];
501
627
  if (modelName == null) {
502
628
  continue;
503
629
  }
@@ -507,6 +633,7 @@ function addModelNamesToMap(model, map, available, modelNames, options, data, re
507
633
  Model = options.model;
508
634
  } else if (modelName[modelSymbol]) {
509
635
  Model = modelName;
636
+ modelName = Model.modelName;
510
637
  } else {
511
638
  try {
512
639
  Model = _getModelFromConn(connection, modelName);
@@ -519,23 +646,18 @@ function addModelNamesToMap(model, map, available, modelNames, options, data, re
519
646
  }
520
647
 
521
648
  let ids = ret;
522
- const flat = Array.isArray(ret) ? utils.array.flatten(ret) : [];
523
649
 
524
- const modelNamesForRefPath = data.modelNamesInOrder ? data.modelNamesInOrder : modelNames;
525
- if (data.isRefPath && Array.isArray(ret) && flat.length === modelNamesForRefPath.length) {
526
- ids = flat.filter((val, i) => modelNamesForRefPath[i] === modelName);
650
+ const modelNamesForRefPath = data.modelNamesInOrder || modelNames;
651
+ if (data.isRefPath && Array.isArray(ret) && ret.length === modelNamesForRefPath.length) {
652
+ ids = matchIdsToRefPaths(ret, modelNamesForRefPath, modelName);
527
653
  }
528
654
 
529
- const perDocumentLimit = options.perDocumentLimit == null ?
530
- get(options, 'options.perDocumentLimit', null) :
531
- options.perDocumentLimit;
532
-
533
- if (!available[modelName] || perDocumentLimit != null) {
655
+ if (!getOwnProperty(available, modelName)) {
534
656
  const currentOptions = {
535
657
  model: Model
536
658
  };
537
659
  if (data.isVirtual && get(data.virtual, 'options.options')) {
538
- currentOptions.options = utils.clone(data.virtual.options.options);
660
+ currentOptions.options = clone(data.virtual.options.options);
539
661
  } else if (schemaOptions != null) {
540
662
  currentOptions.options = Object.assign({}, schemaOptions);
541
663
  }
@@ -544,6 +666,7 @@ function addModelNamesToMap(model, map, available, modelNames, options, data, re
544
666
  // Used internally for checking what model was used to populate this
545
667
  // path.
546
668
  options[populateModelSymbol] = Model;
669
+ currentOptions[populateModelSymbol] = Model;
547
670
  available[modelName] = {
548
671
  model: Model,
549
672
  options: currentOptions,
@@ -558,6 +681,7 @@ function addModelNamesToMap(model, map, available, modelNames, options, data, re
558
681
  isVirtual: data.isVirtual,
559
682
  virtual: data.virtual,
560
683
  count: data.count,
684
+ isRefPath: !!data.isRefPath,
561
685
  [populateModelSymbol]: Model
562
686
  };
563
687
  map.push(available[modelName]);
@@ -568,6 +692,7 @@ function addModelNamesToMap(model, map, available, modelNames, options, data, re
568
692
  available[modelName].ids.push(ids);
569
693
  available[modelName].allIds.push(ret);
570
694
  available[modelName].unpopulatedValues.push(unpopulatedValue);
695
+ available[modelName].isRefPath = available[modelName].isRefPath || !!data.isRefPath;
571
696
  if (data.hasMatchFunction) {
572
697
  available[modelName].match.push(data.match);
573
698
  }
@@ -577,13 +702,27 @@ function addModelNamesToMap(model, map, available, modelNames, options, data, re
577
702
 
578
703
  function _getModelFromConn(conn, modelName) {
579
704
  /* If this connection has a parent from `useDb()`, bubble up to parent's models */
580
- if (conn.models[modelName] == null && conn._parent != null) {
705
+ if (getOwnProperty(conn.models, modelName) == null && conn._parent != null) {
581
706
  return _getModelFromConn(conn._parent, modelName);
582
707
  }
583
708
 
584
709
  return conn.model(modelName);
585
710
  }
586
711
 
712
+ function matchIdsToRefPaths(ids, refPaths, refPathToFind) {
713
+ if (!Array.isArray(refPaths)) {
714
+ return refPaths === refPathToFind
715
+ ? Array.isArray(ids)
716
+ ? utils.array.flatten(ids)
717
+ : [ids]
718
+ : [];
719
+ }
720
+ if (Array.isArray(ids) && Array.isArray(refPaths)) {
721
+ return ids.flatMap((id, index) => matchIdsToRefPaths(id, refPaths[index], refPathToFind));
722
+ }
723
+ return [];
724
+ }
725
+
587
726
  /*!
588
727
  * ignore
589
728
  */
@@ -605,10 +744,9 @@ function _getLocalFieldValues(doc, localField, model, options, virtual, schema)
605
744
  const localFieldPath = localFieldPathType === 'real' ?
606
745
  model.schema.path(localField) :
607
746
  localFieldPathType.schema;
608
- const localFieldGetters = localFieldPath && localFieldPath.getters ?
609
- localFieldPath.getters : [];
747
+ const localFieldGetters = localFieldPath?.getters || [];
610
748
 
611
- localField = localFieldPath != null && localFieldPath.instance === 'Embedded' ? localField + '._id' : localField;
749
+ localField = localFieldPath?.instance === 'Embedded' ? localField + '._id' : localField;
612
750
 
613
751
  const _populateOptions = get(options, 'options', {});
614
752
 
@@ -616,7 +754,7 @@ function _getLocalFieldValues(doc, localField, model, options, virtual, schema)
616
754
  _populateOptions.getters :
617
755
  get(virtual, 'options.getters', false);
618
756
  if (localFieldGetters.length !== 0 && getters) {
619
- const hydratedDoc = (doc.$__ != null) ? doc : model.hydrate(doc);
757
+ const hydratedDoc = isMongooseDocument(doc) ? doc : model.hydrate(doc);
620
758
  const localFieldValue = utils.getValue(localField, doc);
621
759
  if (Array.isArray(localFieldValue)) {
622
760
  const localFieldHydratedValue = utils.getValue(localField.split('.').slice(0, -1), hydratedDoc);
@@ -633,25 +771,25 @@ function _getLocalFieldValues(doc, localField, model, options, virtual, schema)
633
771
  /**
634
772
  * Retrieve the _id of `val` if a Document or Array of Documents.
635
773
  *
636
- * @param {Array|Document|Any} val
774
+ * @param {Array|Document|any} val
637
775
  * @param {Schema} schema
638
- * @return {Array|Document|Any}
776
+ * @return {Array|Document|any}
639
777
  * @api private
640
778
  */
641
779
 
642
780
  function convertTo_id(val, schema) {
643
- if (val != null && val.$__ != null) {
644
- return val._id;
781
+ if (isMongooseDocument(val)) {
782
+ return val._doc._id;
645
783
  }
646
- if (val != null && val._id != null && (schema == null || !schema.$isSchemaMap)) {
784
+ if (val?._id != null && !schema?.$isSchemaMap) {
647
785
  return val._id;
648
786
  }
649
787
 
650
788
  if (Array.isArray(val)) {
651
- const rawVal = val.__array != null ? val.__array : val;
789
+ const rawVal = val.__array ?? val;
652
790
  for (let i = 0; i < rawVal.length; ++i) {
653
- if (rawVal[i] != null && rawVal[i].$__ != null) {
654
- rawVal[i] = rawVal[i]._id;
791
+ if (isMongooseDocument(rawVal[i])) {
792
+ rawVal[i] = rawVal[i]._doc._id;
655
793
  }
656
794
  }
657
795
  if (utils.isMongooseArray(val) && val.$schema()) {
@@ -666,7 +804,7 @@ function convertTo_id(val, schema) {
666
804
  if (getConstructorName(val) === 'Object' &&
667
805
  // The intent here is we should only flatten the object if we expect
668
806
  // to get a Map in the end. Avoid doing this for mixed types.
669
- (schema == null || schema[schemaMixedSymbol] == null)) {
807
+ schema?.[schemaMixedSymbol] == null) {
670
808
  const ret = [];
671
809
  for (const key of Object.keys(val)) {
672
810
  ret.push(val[key]);
@@ -702,17 +840,17 @@ function _findRefPathForDiscriminators(doc, modelSchema, data, options, normaliz
702
840
  cur = cur + (cur.length === 0 ? '' : '.') + piece;
703
841
  const schematype = modelSchema.path(cur);
704
842
  if (schematype != null &&
705
- schematype.$isMongooseArray &&
706
- schematype.caster.discriminators != null &&
707
- Object.keys(schematype.caster.discriminators).length !== 0) {
843
+ schematype.$isMongooseDocumentArray &&
844
+ schematype.Constructor.discriminators != null &&
845
+ utils.hasOwnKeys(schematype.Constructor.discriminators)) {
708
846
  const subdocs = utils.getValue(cur, doc);
709
847
  const remnant = options.path.substring(cur.length + 1);
710
- const discriminatorKey = schematype.caster.schema.options.discriminatorKey;
848
+ const discriminatorKey = schematype.Constructor.schema.options.discriminatorKey;
711
849
  modelNames = [];
712
850
  for (const subdoc of subdocs) {
713
851
  const discriminatorName = utils.getValue(discriminatorKey, subdoc);
714
- const discriminator = getDiscriminatorByKey(schematype.caster.discriminators, discriminatorName);
715
- const discriminatorSchema = discriminator && discriminator.schema;
852
+ const discriminator = getDiscriminatorByKey(schematype.Constructor.discriminators, discriminatorName);
853
+ const discriminatorSchema = discriminator?.schema;
716
854
  if (discriminatorSchema == null) {
717
855
  continue;
718
856
  }
@@ -736,7 +874,11 @@ function _findRefPathForDiscriminators(doc, modelSchema, data, options, normaliz
736
874
  }
737
875
 
738
876
  /**
739
- * Throw an error if there are any $where keys
877
+ * Throw an error if there are any $where keys to defend against [CVE-2024-53900](https://nvd.nist.gov/vuln/detail/CVE-2024-53900)
878
+ *
879
+ * Note that this is ONLY for $where because sift executes $where in Node.js memory.
880
+ * Other forms of MongoDB server-side execution, like $expr, are NOT filtered out.
881
+ * This function is not meant to protect against server-side execution in MongoDB.
740
882
  */
741
883
 
742
884
  function throwOn$where(match) {