@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
@@ -4,18 +4,23 @@
4
4
  * Module dependencies.
5
5
  */
6
6
 
7
- const ArrayType = require('./array');
7
+ const getDiscriminatorByKey = require('../helpers/discriminator/getDiscriminatorByKey');
8
8
  const CastError = require('../error/cast');
9
- const DocumentArrayElement = require('./DocumentArrayElement');
9
+ const DocumentArrayElement = require('./documentArrayElement');
10
10
  const EventEmitter = require('events').EventEmitter;
11
+ const SchemaArray = require('./array');
11
12
  const SchemaDocumentArrayOptions =
12
- require('../options/SchemaDocumentArrayOptions');
13
- const SchemaType = require('../schematype');
13
+ require('../options/schemaDocumentArrayOptions');
14
+ const SchemaType = require('../schemaType');
15
+ const cast = require('../cast');
14
16
  const discriminator = require('../helpers/model/discriminator');
15
17
  const handleIdOption = require('../helpers/schema/handleIdOption');
16
18
  const handleSpreadDoc = require('../helpers/document/handleSpreadDoc');
19
+ const isOperator = require('../helpers/query/isOperator');
17
20
  const utils = require('../utils');
18
21
  const getConstructor = require('../helpers/discriminator/getConstructor');
22
+ const idGetter = require('../helpers/schema/idGetter');
23
+ const InvalidSchemaOptionError = require('../error/invalidSchemaOption');
19
24
 
20
25
  const arrayAtomicsSymbol = require('../helpers/symbols').arrayAtomicsSymbol;
21
26
  const arrayPathSymbol = require('../helpers/symbols').arrayPathSymbol;
@@ -27,43 +32,54 @@ let Subdocument;
27
32
  /**
28
33
  * SubdocsArray SchemaType constructor
29
34
  *
30
- * @param {String} key
35
+ * @param {string} key
31
36
  * @param {Schema} schema
32
- * @param {Object} options
33
- * @param {Object} schemaOptions
37
+ * @param {object} options
38
+ * @param {object} schemaOptions
39
+ * @param {Schema} parentSchema
34
40
  * @inherits SchemaArray
35
41
  * @api public
36
42
  */
37
43
 
38
- function DocumentArrayPath(key, schema, options, schemaOptions) {
39
- const schemaTypeIdOption = DocumentArrayPath.defaultOptions &&
40
- DocumentArrayPath.defaultOptions._id;
44
+ function SchemaDocumentArray(key, schema, options, schemaOptions, parentSchema) {
45
+ if (schema.options?.timeseries) {
46
+ throw new InvalidSchemaOptionError(key, 'timeseries');
47
+ }
48
+ const schemaTypeIdOption = SchemaDocumentArray.defaultOptions?._id;
41
49
  if (schemaTypeIdOption != null) {
42
50
  schemaOptions = schemaOptions || {};
43
51
  schemaOptions._id = schemaTypeIdOption;
44
52
  }
45
53
 
46
- if (schemaOptions != null && schemaOptions._id != null) {
54
+ if (schemaOptions?._id != null) {
47
55
  schema = handleIdOption(schema, schemaOptions);
48
- } else if (options != null && options._id != null) {
56
+ } else if (options?._id != null) {
49
57
  schema = handleIdOption(schema, options);
50
58
  }
51
59
 
52
- const EmbeddedDocument = _createConstructor(schema, options);
53
- EmbeddedDocument.prototype.$basePath = key;
60
+ const Constructor = _createConstructor(schema, options);
61
+ Constructor.prototype.$basePath = key;
62
+ Constructor.path = key;
54
63
 
55
- ArrayType.call(this, key, EmbeddedDocument, options);
64
+ const $parentSchemaType = this;
65
+ const embeddedSchemaType = new DocumentArrayElement(key + '.$', schema, {
66
+ ...(schemaOptions || {}),
67
+ $parentSchemaType,
68
+ Constructor
69
+ });
70
+ SchemaArray.call(this, key, embeddedSchemaType, options, null, parentSchema);
56
71
 
57
72
  this.schema = schema;
73
+ // EmbeddedDocument schematype options
58
74
  this.schemaOptions = schemaOptions || {};
59
75
  this.$isMongooseDocumentArray = true;
60
- this.Constructor = EmbeddedDocument;
76
+ this.Constructor = Constructor;
61
77
 
62
- EmbeddedDocument.base = schema.base;
78
+ Constructor.base = schema.base;
63
79
 
64
80
  const fn = this.defaultValue;
65
81
 
66
- if (!('defaultValue' in this) || fn !== void 0) {
82
+ if (!('defaultValue' in this) || fn != null) {
67
83
  this.default(function() {
68
84
  let arr = fn.call(this);
69
85
  if (arr != null && !Array.isArray(arr)) {
@@ -73,17 +89,6 @@ function DocumentArrayPath(key, schema, options, schemaOptions) {
73
89
  return arr;
74
90
  });
75
91
  }
76
-
77
- const $parentSchemaType = this;
78
- this.$embeddedSchemaType = new DocumentArrayElement(key + '.$', {
79
- required: this &&
80
- this.schemaOptions &&
81
- this.schemaOptions.required || false,
82
- $parentSchemaType
83
- });
84
-
85
- this.$embeddedSchemaType.caster = this.Constructor;
86
- this.$embeddedSchemaType.schema = this.schema;
87
92
  }
88
93
 
89
94
  /**
@@ -92,7 +97,7 @@ function DocumentArrayPath(key, schema, options, schemaOptions) {
92
97
  *
93
98
  * @api public
94
99
  */
95
- DocumentArrayPath.schemaName = 'DocumentArray';
100
+ SchemaDocumentArray.schemaName = 'DocumentArray';
96
101
 
97
102
  /**
98
103
  * Options for all document arrays.
@@ -102,34 +107,53 @@ DocumentArrayPath.schemaName = 'DocumentArray';
102
107
  * @api public
103
108
  */
104
109
 
105
- DocumentArrayPath.options = { castNonArrays: true };
110
+ SchemaDocumentArray.options = { castNonArrays: true };
106
111
 
107
112
  /*!
108
- * Inherits from ArrayType.
113
+ * Inherits from SchemaArray.
109
114
  */
110
- DocumentArrayPath.prototype = Object.create(ArrayType.prototype);
111
- DocumentArrayPath.prototype.constructor = DocumentArrayPath;
112
- DocumentArrayPath.prototype.OptionsConstructor = SchemaDocumentArrayOptions;
115
+ SchemaDocumentArray.prototype = Object.create(SchemaArray.prototype);
116
+ SchemaDocumentArray.prototype.constructor = SchemaDocumentArray;
117
+ SchemaDocumentArray.prototype.OptionsConstructor = SchemaDocumentArrayOptions;
118
+
119
+ /**
120
+ * Contains the handlers for different query operators for this schema type.
121
+ * For example, `$conditionalHandlers.$size` is the function Mongoose calls to cast `$size` filter operators.
122
+ *
123
+ * @property $conditionalHandlers
124
+ * @memberOf SchemaDocumentArray
125
+ * @instance
126
+ * @api public
127
+ */
128
+
129
+ Object.defineProperty(SchemaDocumentArray.prototype, '$conditionalHandlers', {
130
+ enumerable: false,
131
+ value: { ...SchemaArray.prototype.$conditionalHandlers }
132
+ });
113
133
 
114
134
  /*!
115
135
  * ignore
116
136
  */
117
137
 
118
138
  function _createConstructor(schema, options, baseClass) {
119
- Subdocument || (Subdocument = require('../types/ArraySubdocument'));
139
+ Subdocument || (Subdocument = require('../types/arraySubdocument'));
120
140
 
121
141
  // compile an embedded document for this schema
122
142
  function EmbeddedDocument() {
123
143
  Subdocument.apply(this, arguments);
124
- if (this.__parentArray == null || this.__parentArray.getArrayParent() == null) {
144
+ // `ArraySubdocument` already looked up the parent array's parent doc, so
145
+ // reuse it rather than going through the document array proxy again.
146
+ const parent = this[documentArrayParent];
147
+ if (parent == null) {
125
148
  return;
126
149
  }
127
- this.$session(this.__parentArray.getArrayParent().$session());
150
+ this.$session(parent.$session());
128
151
  }
129
152
 
130
- schema._preCompile();
153
+ // Must run before `$__setSchema()`, which compiles virtuals onto the prototype
154
+ schema.plugin(idGetter, { deduplicate: true });
131
155
 
132
- const proto = baseClass != null ? baseClass.prototype : Subdocument.prototype;
156
+ const proto = baseClass?.prototype ?? Subdocument.prototype;
133
157
  EmbeddedDocument.prototype = Object.create(proto);
134
158
  EmbeddedDocument.prototype.$__setSchema(schema);
135
159
  EmbeddedDocument.schema = schema;
@@ -168,17 +192,17 @@ function _createConstructor(schema, options, baseClass) {
168
192
  * const docArrayPath = parentSchema.path('shapes');
169
193
  * docArrayPath.discriminator('Circle', Schema({ radius: Number }));
170
194
  *
171
- * @param {String} name
195
+ * @param {string} name
172
196
  * @param {Schema} schema fields to add to the schema for instances of this sub-class
173
- * @param {Object|string} [options] If string, same as `options.value`.
174
- * @param {String} [options.value] the string stored in the `discriminatorKey` property. If not specified, Mongoose uses the `name` parameter.
175
- * @param {Boolean} [options.clone=true] By default, `discriminator()` clones the given `schema`. Set to `false` to skip cloning.
176
- * @see discriminators /docs/discriminators.html
197
+ * @param {object|string} [options] If string, same as `options.value`.
198
+ * @param {string} [options.value] the string stored in the `discriminatorKey` property. If not specified, Mongoose uses the `name` parameter.
199
+ * @param {boolean} [options.clone=true] By default, `discriminator()` clones the given `schema`. Set to `false` to skip cloning.
200
+ * @see discriminators https://mongoosejs.com/docs/discriminators.html
177
201
  * @return {Function} the constructor Mongoose will use for creating instances of this discriminator model
178
202
  * @api public
179
203
  */
180
204
 
181
- DocumentArrayPath.prototype.discriminator = function(name, schema, options) {
205
+ SchemaDocumentArray.prototype.discriminator = function(name, schema, options) {
182
206
  if (typeof name === 'function') {
183
207
  name = utils.getFunctionName(name);
184
208
  }
@@ -191,92 +215,90 @@ DocumentArrayPath.prototype.discriminator = function(name, schema, options) {
191
215
  schema = schema.clone();
192
216
  }
193
217
 
194
- schema = discriminator(this.casterConstructor, name, schema, tiedValue);
195
-
196
- const EmbeddedDocument = _createConstructor(schema, null, this.casterConstructor);
197
- EmbeddedDocument.baseCasterConstructor = this.casterConstructor;
218
+ schema = discriminator(this.Constructor, name, schema, tiedValue, null, null, options?.overwriteExisting);
198
219
 
199
- try {
200
- Object.defineProperty(EmbeddedDocument, 'name', {
201
- value: name
202
- });
203
- } catch (error) {
204
- // Ignore error, only happens on old versions of node
220
+ // The discriminator key has `select: true`, so `applyPaths()` needs to walk
221
+ // the parent schema even if the parent schema is already compiled.
222
+ if (this.parentSchema != null) {
223
+ this.parentSchema._hasSelectedPaths = true;
205
224
  }
206
225
 
207
- this.casterConstructor.discriminators[name] = EmbeddedDocument;
226
+ const EmbeddedDocument = _createConstructor(schema, null, this.Constructor);
227
+ EmbeddedDocument.baseCasterConstructor = this.Constructor;
208
228
 
209
- return this.casterConstructor.discriminators[name];
229
+ Object.defineProperty(EmbeddedDocument, 'name', {
230
+ value: name
231
+ });
232
+
233
+ this.Constructor.discriminators[name] = EmbeddedDocument;
234
+
235
+ return this.Constructor.discriminators[name];
210
236
  };
211
237
 
212
238
  /**
213
239
  * Performs local validations first, then validations on each embedded doc
214
240
  *
215
- * @api private
241
+ * @api public
216
242
  */
217
243
 
218
- DocumentArrayPath.prototype.doValidate = function(array, fn, scope, options) {
244
+ SchemaDocumentArray.prototype.doValidate = async function doValidate(array, scope, options) {
219
245
  // lazy load
220
- MongooseDocumentArray || (MongooseDocumentArray = require('../types/DocumentArray'));
246
+ MongooseDocumentArray || (MongooseDocumentArray = require('../types/documentArray'));
221
247
 
222
- const _this = this;
248
+ let schemaTypeError;
223
249
  try {
224
- SchemaType.prototype.doValidate.call(this, array, cb, scope);
250
+ await SchemaType.prototype.doValidate.call(this, array, scope);
225
251
  } catch (err) {
226
- return fn(err);
252
+ schemaTypeError = err;
227
253
  }
228
-
229
- function cb(err) {
230
- if (err) {
231
- return fn(err);
232
- }
233
-
234
- let count = array && array.length;
235
- let error;
236
-
237
- if (!count) {
238
- return fn();
239
- }
240
- if (options && options.updateValidator) {
241
- return fn();
242
- }
243
- if (!utils.isMongooseDocumentArray(array)) {
244
- array = new MongooseDocumentArray(array, _this.path, scope);
254
+ if (options?.updateValidator) {
255
+ if (schemaTypeError != null) {
256
+ throw schemaTypeError;
245
257
  }
258
+ return;
259
+ }
260
+ if (!utils.isMongooseDocumentArray(array)) {
261
+ array = new MongooseDocumentArray(array, this.path, scope);
262
+ }
246
263
 
264
+ const promises = [];
265
+ for (let i = 0; i < array.length; ++i) {
247
266
  // handle sparse arrays, do not use array.forEach which does not
248
267
  // iterate over sparse elements yet reports array.length including
249
268
  // them :(
250
-
251
- function callback(err) {
252
- if (err != null) {
253
- error = err;
254
- }
255
- --count || fn(error);
269
+ let doc = array[i];
270
+ if (doc == null) {
271
+ continue;
272
+ }
273
+ // If you set the array index directly, the doc might not yet be
274
+ // a full fledged mongoose subdoc, so make it into one.
275
+ if (!(doc instanceof Subdocument)) {
276
+ const Constructor = getConstructor(this.Constructor, array[i]);
277
+ doc = array[i] = new Constructor(doc, array, undefined, undefined, i);
256
278
  }
257
279
 
258
- for (let i = 0, len = count; i < len; ++i) {
259
- // sidestep sparse entries
260
- let doc = array[i];
261
- if (doc == null) {
262
- --count || fn(error);
263
- continue;
264
- }
280
+ if (options?.validateModifiedOnly && !doc.$isNew && !doc.$isModified()) {
281
+ continue;
282
+ }
265
283
 
266
- // If you set the array index directly, the doc might not yet be
267
- // a full fledged mongoose subdoc, so make it into one.
268
- if (!(doc instanceof Subdocument)) {
269
- const Constructor = getConstructor(_this.casterConstructor, array[i]);
270
- doc = array[i] = new Constructor(doc, array, undefined, undefined, i);
271
- }
284
+ const subdocOptions = doc.$isNew && options?.validateModifiedOnly ?
285
+ { ...options, validateModifiedOnly: false } :
286
+ options;
287
+ promises.push(doc.validate(null, subdocOptions));
288
+ }
272
289
 
273
- if (options != null && options.validateModifiedOnly && !doc.$isModified()) {
274
- --count || fn(error);
275
- continue;
276
- }
290
+ let subdocumentError;
291
+ try {
292
+ await Promise.all(promises);
293
+ } catch (err) {
294
+ subdocumentError = err;
295
+ }
277
296
 
278
- doc.$__validate(callback);
279
- }
297
+ if (schemaTypeError != null) {
298
+ throw schemaTypeError;
299
+ }
300
+ if (subdocumentError != null) {
301
+ throw subdocumentError;
280
302
  }
281
303
  };
282
304
 
@@ -291,17 +313,13 @@ DocumentArrayPath.prototype.doValidate = function(array, fn, scope, options) {
291
313
  * @api private
292
314
  */
293
315
 
294
- DocumentArrayPath.prototype.doValidateSync = function(array, scope, options) {
316
+ SchemaDocumentArray.prototype.doValidateSync = function(array, scope, options) {
295
317
  const schemaTypeError = SchemaType.prototype.doValidateSync.call(this, array, scope);
296
- if (schemaTypeError != null) {
297
- return schemaTypeError;
298
- }
299
-
300
- const count = array && array.length;
301
- let resultError = null;
318
+ const count = array?.length;
319
+ let resultError = schemaTypeError;
302
320
 
303
321
  if (!count) {
304
- return;
322
+ return resultError;
305
323
  }
306
324
 
307
325
  // handle sparse arrays, do not use array.forEach which does not
@@ -318,15 +336,18 @@ DocumentArrayPath.prototype.doValidateSync = function(array, scope, options) {
318
336
  // If you set the array index directly, the doc might not yet be
319
337
  // a full fledged mongoose subdoc, so make it into one.
320
338
  if (!(doc instanceof Subdocument)) {
321
- const Constructor = getConstructor(this.casterConstructor, array[i]);
339
+ const Constructor = getConstructor(this.Constructor, array[i]);
322
340
  doc = array[i] = new Constructor(doc, array, undefined, undefined, i);
323
341
  }
324
342
 
325
- if (options != null && options.validateModifiedOnly && !doc.$isModified()) {
343
+ if (options?.validateModifiedOnly && !doc.$isNew && !doc.$isModified()) {
326
344
  continue;
327
345
  }
328
346
 
329
- const subdocValidateError = doc.validateSync();
347
+ const subdocOptions = doc.$isNew && options?.validateModifiedOnly ?
348
+ { ...options, validateModifiedOnly: false } :
349
+ options;
350
+ const subdocValidateError = doc.$__validateSync(subdocOptions);
330
351
 
331
352
  if (subdocValidateError && resultError == null) {
332
353
  resultError = subdocValidateError;
@@ -340,7 +361,7 @@ DocumentArrayPath.prototype.doValidateSync = function(array, scope, options) {
340
361
  * ignore
341
362
  */
342
363
 
343
- DocumentArrayPath.prototype.getDefault = function(scope, init, options) {
364
+ SchemaDocumentArray.prototype.getDefault = function(scope, init, options) {
344
365
  let ret = typeof this.defaultValue === 'function'
345
366
  ? this.defaultValue.call(scope)
346
367
  : this.defaultValue;
@@ -349,12 +370,12 @@ DocumentArrayPath.prototype.getDefault = function(scope, init, options) {
349
370
  return ret;
350
371
  }
351
372
 
352
- if (options && options.skipCast) {
373
+ if (options?.skipCast) {
353
374
  return ret;
354
375
  }
355
376
 
356
377
  // lazy load
357
- MongooseDocumentArray || (MongooseDocumentArray = require('../types/DocumentArray'));
378
+ MongooseDocumentArray || (MongooseDocumentArray = require('../types/documentArray'));
358
379
 
359
380
  if (!Array.isArray(ret)) {
360
381
  ret = [ret];
@@ -363,7 +384,7 @@ DocumentArrayPath.prototype.getDefault = function(scope, init, options) {
363
384
  ret = new MongooseDocumentArray(ret, this.path, scope);
364
385
 
365
386
  for (let i = 0; i < ret.length; ++i) {
366
- const Constructor = getConstructor(this.casterConstructor, ret[i]);
387
+ const Constructor = getConstructor(this.Constructor, ret[i]);
367
388
  const _subdoc = new Constructor({}, ret, undefined,
368
389
  undefined, i);
369
390
  _subdoc.$init(ret[i]);
@@ -386,17 +407,17 @@ const initDocumentOptions = Object.freeze({ skipId: false, willInit: true });
386
407
  /**
387
408
  * Casts contents
388
409
  *
389
- * @param {Object} value
410
+ * @param {object} value
390
411
  * @param {Document} document that triggers the casting
391
412
  * @api private
392
413
  */
393
414
 
394
- DocumentArrayPath.prototype.cast = function(value, doc, init, prev, options) {
415
+ SchemaDocumentArray.prototype.cast = function(value, doc, init, prev, options) {
395
416
  // lazy load
396
- MongooseDocumentArray || (MongooseDocumentArray = require('../types/DocumentArray'));
417
+ MongooseDocumentArray || (MongooseDocumentArray = require('../types/documentArray'));
397
418
 
398
419
  // Skip casting if `value` is the same as the previous value, no need to cast. See gh-9266
399
- if (value != null && value[arrayPathSymbol] != null && value === prev) {
420
+ if (value?.[arrayPathSymbol] != null && value === prev) {
400
421
  return value;
401
422
  }
402
423
 
@@ -408,7 +429,8 @@ DocumentArrayPath.prototype.cast = function(value, doc, init, prev, options) {
408
429
  const path = options.path || this.path;
409
430
 
410
431
  if (!Array.isArray(value)) {
411
- if (!init && !DocumentArrayPath.options.castNonArrays) {
432
+ const castNonArraysOption = this.options.castNonArrays ?? SchemaDocumentArray.options.castNonArrays;
433
+ if (!init && !castNonArraysOption) {
412
434
  throw new CastError('DocumentArray', value, this.path, null, this);
413
435
  }
414
436
  // gh-2442 mark whole array as modified if we're initializing a doc from
@@ -422,7 +444,7 @@ DocumentArrayPath.prototype.cast = function(value, doc, init, prev, options) {
422
444
  // We need to create a new array, otherwise change tracking will
423
445
  // update the old doc (gh-4449)
424
446
  if (!options.skipDocumentArrayCast || utils.isMongooseDocumentArray(value)) {
425
- value = new MongooseDocumentArray(value, path, doc);
447
+ value = new MongooseDocumentArray(value, path, doc, this);
426
448
  }
427
449
 
428
450
  if (prev != null) {
@@ -441,7 +463,7 @@ DocumentArrayPath.prototype.cast = function(value, doc, init, prev, options) {
441
463
  continue;
442
464
  }
443
465
 
444
- const Constructor = getConstructor(this.casterConstructor, rawArray[i]);
466
+ const Constructor = getConstructor(this.Constructor, rawArray[i]);
445
467
 
446
468
  const spreadDoc = handleSpreadDoc(rawArray[i], true);
447
469
  if (rawArray[i] !== spreadDoc) {
@@ -449,7 +471,11 @@ DocumentArrayPath.prototype.cast = function(value, doc, init, prev, options) {
449
471
  }
450
472
 
451
473
  if (rawArray[i] instanceof Subdocument) {
452
- if (rawArray[i][documentArrayParent] !== doc) {
474
+ // gh-15973: Clone if subdocument has a different parent, or if it already has a
475
+ // different __index (e.g. reordered or duplicated in the array). If __index is null,
476
+ // we can safely set it without cloning.
477
+ if (rawArray[i][documentArrayParent] !== doc ||
478
+ (rawArray[i].__index != null && rawArray[i].__index !== i)) {
453
479
  if (init) {
454
480
  const subdoc = new Constructor(null, value, initDocumentOptions, selected, i);
455
481
  rawArray[i] = subdoc.$init(rawArray[i]);
@@ -471,17 +497,20 @@ DocumentArrayPath.prototype.cast = function(value, doc, init, prev, options) {
471
497
  }
472
498
 
473
499
  subdoc = new Constructor(null, value, initDocumentOptions, selected, i);
474
- rawArray[i] = subdoc.$init(rawArray[i]);
475
- } else {
476
- if (prev && typeof prev.id === 'function') {
477
- subdoc = prev.id(rawArray[i]._id);
500
+ // Don't pass `path` or `arrayPathIndex` to $init - they're only for this DocumentArray itself,
501
+ // not its element fields. Element subdocuments use relative paths internally for change tracking.
502
+ if (options.path != null || options.arrayPathIndex != null) {
503
+ const { path, arrayPathIndex, ...initOptions } = options;
504
+ options = initOptions;
478
505
  }
479
-
480
- if (prev && subdoc && utils.deepEqual(subdoc.toObject(_toObjectOptions), rawArray[i])) {
481
- // handle resetting doc with existing id and same data
482
- subdoc.set(rawArray[i]);
483
- // if set() is hooked it will have no return value
484
- // see gh-746
506
+ rawArray[i] = subdoc.$init(rawArray[i], options);
507
+ } else {
508
+ // Reuse the existing subdoc at the same index if it has the same `_id` and data, so
509
+ // references to it stay valid. Only checking the same index keeps this O(n) (gh-16673).
510
+ subdoc = prev?.[i];
511
+ if (subdoc?._doc != null && rawArray[i]._id != null &&
512
+ utils.deepEqual(rawArray[i]._id, subdoc._doc._id) &&
513
+ utils.deepEqual(subdoc.toObject(_toObjectOptions), rawArray[i])) {
485
514
  rawArray[i] = subdoc;
486
515
  } else {
487
516
  try {
@@ -499,6 +528,16 @@ DocumentArrayPath.prototype.cast = function(value, doc, init, prev, options) {
499
528
  }
500
529
  }
501
530
 
531
+ // A subdoc can only belong to one array, so subdocs reused from `prev` move to the new array,
532
+ // like gh-5189. Only do this after casting succeeded, so a CastError leaves `prev` consistent.
533
+ if (utils.isMongooseDocumentArray(prev)) {
534
+ for (let i = 0; i < len; ++i) {
535
+ if (rawArray[i] != null && rawArray[i] === prev[i]) {
536
+ rawArray[i].__parentArray = value;
537
+ }
538
+ }
539
+ }
540
+
502
541
  return value;
503
542
  };
504
543
 
@@ -506,15 +545,22 @@ DocumentArrayPath.prototype.cast = function(value, doc, init, prev, options) {
506
545
  * ignore
507
546
  */
508
547
 
509
- DocumentArrayPath.prototype.clone = function() {
548
+ SchemaDocumentArray.prototype.clone = function() {
510
549
  const options = Object.assign({}, this.options);
511
- const schematype = new this.constructor(this.path, this.schema, options, this.schemaOptions);
550
+ const schematype = new this.constructor(
551
+ this.path,
552
+ this.schema,
553
+ options,
554
+ this.schemaOptions,
555
+ this.parentSchema
556
+ );
512
557
  schematype.validators = this.validators.slice();
513
558
  if (this.requiredValidator !== undefined) {
514
559
  schematype.requiredValidator = this.requiredValidator;
515
560
  }
516
561
  schematype.Constructor.discriminators = Object.assign({},
517
562
  this.Constructor.discriminators);
563
+ schematype._appliedDiscriminators = this._appliedDiscriminators;
518
564
  return schematype;
519
565
  };
520
566
 
@@ -522,7 +568,7 @@ DocumentArrayPath.prototype.clone = function() {
522
568
  * ignore
523
569
  */
524
570
 
525
- DocumentArrayPath.prototype.applyGetters = function(value, scope) {
571
+ SchemaDocumentArray.prototype.applyGetters = function(value, scope) {
526
572
  return SchemaType.prototype.applyGetters.call(this, value, scope);
527
573
  };
528
574
 
@@ -531,8 +577,8 @@ DocumentArrayPath.prototype.applyGetters = function(value, scope) {
531
577
  * Necessary for proper default application of subdocument values.
532
578
  *
533
579
  * @param {DocumentArrayPath} array the array to scope `fields` paths
534
- * @param {Object|undefined} fields the root fields selected in the query
535
- * @param {Boolean|undefined} init if we are being created part of a query result
580
+ * @param {object|undefined} fields the root fields selected in the query
581
+ * @param {boolean|undefined} init if we are being created part of a query result
536
582
  * @api private
537
583
  */
538
584
 
@@ -571,28 +617,90 @@ function scopePaths(array, fields, init) {
571
617
  * ignore
572
618
  */
573
619
 
574
- DocumentArrayPath.defaultOptions = {};
620
+ SchemaDocumentArray.defaultOptions = {};
575
621
 
576
622
  /**
577
623
  * Sets a default option for all DocumentArray instances.
578
624
  *
579
625
  * #### Example:
580
626
  *
581
- * // Make all numbers have option `min` equal to 0.
582
- * mongoose.Schema.DocumentArray.set('_id', false);
627
+ * // Make all document arrays not have `_id` by default.
628
+ * mongoose.Schema.Types.DocumentArray.set('_id', false);
583
629
  *
584
- * @param {String} option The name of the option you'd like to set (e.g. trim, lowercase, etc...)
585
- * @param {Any} value The value of the option you'd like to set.
630
+ * @param {string} option The name of the option you'd like to set (e.g. trim, lowercase, etc...)
631
+ * @param {any} value The value of the option you'd like to set.
586
632
  * @return {void}
587
633
  * @function set
588
634
  * @static
589
635
  * @api public
590
636
  */
591
637
 
592
- DocumentArrayPath.set = SchemaType.set;
638
+ SchemaDocumentArray.set = SchemaType.set;
639
+
640
+ SchemaDocumentArray.setters = [];
641
+
642
+ /**
643
+ * Attaches a getter for all DocumentArrayPath instances
644
+ *
645
+ * @param {Function} getter
646
+ * @return {this}
647
+ * @function get
648
+ * @static
649
+ * @api public
650
+ */
651
+
652
+ SchemaDocumentArray.get = SchemaType.get;
653
+
654
+ /*!
655
+ * Handle casting $elemMatch operators
656
+ */
657
+
658
+ SchemaDocumentArray.prototype.$conditionalHandlers.$elemMatch = cast$elemMatch;
659
+
660
+ function cast$elemMatch(val, context) {
661
+ const keys = Object.keys(val);
662
+ const numKeys = keys.length;
663
+ for (let i = 0; i < numKeys; ++i) {
664
+ const key = keys[i];
665
+ const value = val[key];
666
+ if (isOperator(key) && value != null) {
667
+ val[key] = this.castForQuery(key, value, context);
668
+ }
669
+ }
670
+
671
+ // Is this an embedded discriminator and is the discriminator key set?
672
+ // If so, use the discriminator schema. See gh-7449
673
+ const discriminatorKey = this?.Constructor?.schema?.options?.discriminatorKey;
674
+ const discriminators = this?.Constructor?.schema?.discriminators || {};
675
+ const discriminator = discriminatorKey != null && val[discriminatorKey] != null ?
676
+ getDiscriminatorByKey(discriminators, val[discriminatorKey]) :
677
+ null;
678
+ if (discriminator != null) {
679
+ return cast(discriminator, val, null, this?.$$context);
680
+ }
681
+
682
+ const schema = this.Constructor.schema ?? context.schema;
683
+ return cast(schema, val, null, this?.$$context);
684
+ }
685
+
686
+ /**
687
+ * Returns this schema type's representation in a JSON schema.
688
+ *
689
+ * @param {object} [options]
690
+ * @param {boolean} [options.useBsonType=false] If true, return a representation with `bsonType` for use with MongoDB's `$jsonSchema`.
691
+ * @returns {object} JSON schema properties
692
+ */
693
+
694
+ SchemaDocumentArray.prototype.toJSONSchema = function toJSONSchema(options) {
695
+ const itemsTypeDefinition = this._createJSONSchemaTypeDefinition('object', 'object', { ...options, _overrideRequired: false });
696
+ return {
697
+ ...this._createJSONSchemaTypeDefinition('array', 'array', options),
698
+ items: { ...itemsTypeDefinition, ...this.schema.toJSONSchema(options) }
699
+ };
700
+ };
593
701
 
594
702
  /*!
595
703
  * Module exports.
596
704
  */
597
705
 
598
- module.exports = DocumentArrayPath;
706
+ module.exports = SchemaDocumentArray;