@datanimbus/mongoose 9.13.1 → 9.13.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (302) hide show
  1. package/README.md +80 -70
  2. package/eslint.config.mjs +202 -0
  3. package/index.js +2 -1
  4. package/lib/aggregate.js +276 -174
  5. package/lib/cast/bigint.js +46 -0
  6. package/lib/cast/boolean.js +3 -3
  7. package/lib/cast/decimal128.js +4 -1
  8. package/lib/cast/double.js +56 -0
  9. package/lib/cast/int32.js +42 -0
  10. package/lib/cast/number.js +6 -6
  11. package/lib/cast/objectid.js +3 -3
  12. package/lib/cast/string.js +3 -3
  13. package/lib/cast/uuid.js +35 -0
  14. package/lib/cast.js +100 -92
  15. package/lib/collection.js +31 -22
  16. package/lib/connection.js +792 -507
  17. package/lib/constants.js +73 -0
  18. package/lib/cursor/{AggregationCursor.js → aggregationCursor.js} +205 -52
  19. package/lib/cursor/changeStream.js +218 -0
  20. package/lib/cursor/queryCursor.js +676 -0
  21. package/lib/defaults/schemaDefaultsCache.js +62 -0
  22. package/lib/document.js +2419 -1306
  23. package/lib/drivers/node-mongodb-native/bulkWriteResult.js +5 -0
  24. package/lib/drivers/node-mongodb-native/collection.js +101 -135
  25. package/lib/drivers/node-mongodb-native/connection.js +386 -28
  26. package/lib/drivers/node-mongodb-native/index.js +3 -5
  27. package/lib/error/browserMissingSchema.js +5 -4
  28. package/lib/error/bulkSaveIncompleteError.js +44 -0
  29. package/lib/error/cast.js +30 -21
  30. package/lib/error/createCollectionsError.js +26 -0
  31. package/lib/error/divergentArray.js +11 -9
  32. package/lib/error/eachAsyncMultiError.js +2 -2
  33. package/lib/error/index.js +38 -29
  34. package/lib/error/invalidSchemaOption.js +32 -0
  35. package/lib/error/messages.js +4 -3
  36. package/lib/error/missingSchema.js +8 -6
  37. package/lib/error/notFound.js +7 -5
  38. package/lib/error/objectExpected.js +9 -8
  39. package/lib/error/objectParameter.js +12 -11
  40. package/lib/error/overwriteModel.js +7 -6
  41. package/lib/error/parallelSave.js +11 -8
  42. package/lib/error/parallelValidate.js +9 -7
  43. package/lib/error/serverSelection.js +1 -0
  44. package/lib/error/setOptionError.js +11 -9
  45. package/lib/error/strict.js +12 -10
  46. package/lib/error/strictPopulate.js +11 -9
  47. package/lib/error/syncIndexes.js +2 -2
  48. package/lib/error/validation.js +11 -17
  49. package/lib/error/validator.js +9 -8
  50. package/lib/error/version.js +12 -10
  51. package/lib/filters/operators.js +8 -0
  52. package/lib/helpers/aggregate/prepareDiscriminatorPipeline.js +4 -4
  53. package/lib/helpers/buildMiddlewareFilter.js +42 -0
  54. package/lib/helpers/clone.js +121 -35
  55. package/lib/helpers/common.js +7 -7
  56. package/lib/helpers/cursor/eachAsync.js +14 -11
  57. package/lib/helpers/cursor/waitForInitialization.js +17 -0
  58. package/lib/helpers/discriminator/applyEmbeddedDiscriminators.js +36 -0
  59. package/lib/helpers/discriminator/areDiscriminatorValuesEqual.js +1 -1
  60. package/lib/helpers/discriminator/getConstructor.js +9 -6
  61. package/lib/helpers/discriminator/getDiscriminatorByKey.js +1 -1
  62. package/lib/helpers/discriminator/getDiscriminatorByValue.js +1 -1
  63. package/lib/helpers/discriminator/getDiscriminatorValueFromFilter.js +30 -0
  64. package/lib/helpers/discriminator/getSchemaDiscriminatorByValue.js +1 -1
  65. package/lib/helpers/discriminator/mergeDiscriminatorSchema.js +41 -9
  66. package/lib/helpers/document/applyDefaults.js +82 -14
  67. package/lib/helpers/document/applyTimestamps.js +106 -0
  68. package/lib/helpers/document/applyVirtuals.js +147 -0
  69. package/lib/helpers/document/cleanModifiedSubpaths.js +14 -4
  70. package/lib/helpers/document/compile.js +20 -15
  71. package/lib/helpers/document/getDeepestSubdocumentForPath.js +38 -0
  72. package/lib/helpers/document/getEmbeddedDiscriminatorPath.js +6 -3
  73. package/lib/helpers/document/handleSpreadDoc.js +2 -1
  74. package/lib/helpers/document/isInPathsToSave.js +24 -0
  75. package/lib/helpers/document/toObjectRecursive.js +49 -0
  76. package/lib/helpers/get.js +1 -1
  77. package/lib/helpers/getDefaultBulkwriteResult.js +11 -20
  78. package/lib/helpers/getInheritedProperty.js +28 -0
  79. package/lib/helpers/getOwnProperty.js +19 -0
  80. package/lib/helpers/indexes/applySchemaCollation.js +1 -1
  81. package/lib/helpers/indexes/decorateDiscriminatorIndexOptions.js +1 -1
  82. package/lib/helpers/indexes/getRelatedIndexes.js +8 -4
  83. package/lib/helpers/indexes/isDefaultIdIndex.js +1 -1
  84. package/lib/helpers/indexes/isIndexEqual.js +13 -12
  85. package/lib/helpers/indexes/isIndexSpecEqual.js +32 -0
  86. package/lib/helpers/indexes/isTimeseriesIndex.js +16 -0
  87. package/lib/helpers/isBsonType.js +3 -6
  88. package/lib/helpers/isMongooseDocument.js +24 -0
  89. package/lib/helpers/isMongooseObject.js +6 -4
  90. package/lib/helpers/isObject.js +2 -2
  91. package/lib/helpers/isPOJO.js +12 -0
  92. package/lib/helpers/isSimpleValidator.js +2 -2
  93. package/lib/helpers/minimize.js +41 -0
  94. package/lib/helpers/model/applyDefaultsToPOJO.js +2 -2
  95. package/lib/helpers/model/applyHooks.js +72 -54
  96. package/lib/helpers/model/applyMethods.js +3 -3
  97. package/lib/helpers/model/applyStaticHooks.js +20 -50
  98. package/lib/helpers/model/castBulkWrite.js +278 -172
  99. package/lib/helpers/model/decorateBulkWriteResult.js +8 -0
  100. package/lib/helpers/model/discriminator.js +77 -21
  101. package/lib/helpers/omitUndefined.js +20 -0
  102. package/lib/helpers/parallelLimit.js +61 -34
  103. package/lib/helpers/path/setDottedPath.js +1 -1
  104. package/lib/helpers/pathTrie.js +167 -0
  105. package/lib/helpers/pluralize.js +5 -4
  106. package/lib/helpers/populate/assignRawDocsToIdStructure.js +12 -7
  107. package/lib/helpers/populate/assignVals.js +46 -21
  108. package/lib/helpers/populate/createPopulateQueryFilter.js +13 -5
  109. package/lib/helpers/populate/getModelsMapForPopulate.js +250 -108
  110. package/lib/helpers/populate/getSchemaTypes.js +27 -30
  111. package/lib/helpers/populate/getVirtual.js +31 -0
  112. package/lib/helpers/populate/markArraySubdocsPopulated.js +6 -4
  113. package/lib/helpers/populate/modelNamesFromRefPath.js +11 -5
  114. package/lib/helpers/populate/removeDeselectedForeignField.js +3 -2
  115. package/lib/helpers/populate/setInheritedReadOptions.js +21 -0
  116. package/lib/helpers/populate/setPopulatedVirtualValue.js +33 -0
  117. package/lib/helpers/populate/splitPopulateQuery.js +81 -0
  118. package/lib/helpers/printJestWarning.js +1 -1
  119. package/lib/helpers/processConnectionOptions.js +7 -2
  120. package/lib/helpers/projection/applyProjection.js +8 -2
  121. package/lib/helpers/projection/hasIncludedChildren.js +1 -1
  122. package/lib/helpers/projection/isExclusive.js +8 -6
  123. package/lib/helpers/projection/isInclusive.js +2 -1
  124. package/lib/helpers/projection/isPathExcluded.js +3 -3
  125. package/lib/helpers/projection/isPathSelectedInclusive.js +1 -11
  126. package/lib/helpers/projection/isSubpath.js +1 -1
  127. package/lib/helpers/projection/parseProjection.js +9 -4
  128. package/lib/helpers/query/applyGlobalOption.js +9 -9
  129. package/lib/helpers/query/cast$expr.js +52 -23
  130. package/lib/helpers/query/castFilterPath.js +22 -22
  131. package/lib/helpers/query/castUpdate.js +207 -79
  132. package/lib/helpers/query/cloneMongooseOptions.js +44 -0
  133. package/lib/helpers/query/getEmbeddedDiscriminatorPath.js +27 -13
  134. package/lib/helpers/query/handleImmutable.js +18 -2
  135. package/lib/helpers/query/handleReadPreferenceAliases.js +23 -0
  136. package/lib/helpers/query/sanitizeFilter.js +3 -2
  137. package/lib/helpers/query/selectPopulatedFields.js +13 -0
  138. package/lib/helpers/query/validOps.js +1 -22
  139. package/lib/helpers/schema/applyPlugins.js +2 -2
  140. package/lib/helpers/schema/applyReadConcern.js +20 -0
  141. package/lib/helpers/schema/applyWriteConcern.js +12 -3
  142. package/lib/helpers/schema/cleanPositionalOperators.js +5 -3
  143. package/lib/helpers/schema/getIndexes.js +20 -13
  144. package/lib/helpers/schema/getKeysInSchemaOrder.js +13 -16
  145. package/lib/helpers/schema/getPath.js +11 -3
  146. package/lib/helpers/schema/getSubdocumentStrictValue.js +32 -0
  147. package/lib/helpers/schema/handleIdOption.js +1 -1
  148. package/lib/helpers/schema/idGetter.js +7 -2
  149. package/lib/helpers/schema/merge.js +9 -1
  150. package/lib/helpers/schematype/getConditionalHandler.js +23 -0
  151. package/lib/helpers/schematype/handleImmutable.js +1 -1
  152. package/lib/helpers/setDefaultsOnInsert.js +85 -43
  153. package/lib/helpers/symbols.js +4 -4
  154. package/lib/helpers/timestamps/setDocumentTimestamps.js +2 -2
  155. package/lib/helpers/timestamps/setupTimestamps.js +69 -37
  156. package/lib/helpers/update/applyTimestampsToChildren.js +1 -1
  157. package/lib/helpers/update/applyTimestampsToUpdate.js +53 -37
  158. package/lib/helpers/update/castArrayFilters.js +68 -29
  159. package/lib/helpers/update/decorateUpdateWithVersionKey.js +35 -0
  160. package/lib/helpers/update/modifiedPaths.js +2 -2
  161. package/lib/helpers/update/removeUnusedArrayFilters.js +11 -2
  162. package/lib/helpers/updateValidators.js +87 -128
  163. package/lib/index.js +6 -1320
  164. package/lib/internal.js +7 -1
  165. package/lib/model.js +2587 -2618
  166. package/lib/modifiedPathsSnapshot.js +9 -0
  167. package/lib/mongoose.js +1456 -0
  168. package/lib/options/saveOptions.js +2 -0
  169. package/lib/options/{SchemaArrayOptions.js → schemaArrayOptions.js} +16 -5
  170. package/lib/options/{SchemaBufferOptions.js → schemaBufferOptions.js} +2 -2
  171. package/lib/options/{SchemaDateOptions.js → schemaDateOptions.js} +1 -1
  172. package/lib/options/{SchemaDocumentArrayOptions.js → schemaDocumentArrayOptions.js} +24 -1
  173. package/lib/options/{SchemaMapOptions.js → schemaMapOptions.js} +1 -1
  174. package/lib/options/{SchemaNumberOptions.js → schemaNumberOptions.js} +5 -5
  175. package/lib/options/{SchemaObjectIdOptions.js → schemaObjectIdOptions.js} +4 -4
  176. package/lib/options/{SchemaStringOptions.js → schemaStringOptions.js} +10 -10
  177. package/lib/options/schemaSubdocumentOptions.js +89 -0
  178. package/lib/options/{SchemaTypeOptions.js → schemaTypeOptions.js} +28 -14
  179. package/lib/options/schemaUnionOptions.js +32 -0
  180. package/lib/options/{VirtualOptions.js → virtualOptions.js} +13 -13
  181. package/lib/options.js +4 -1
  182. package/lib/plugins/index.js +0 -2
  183. package/lib/plugins/saveSubdocs.js +85 -50
  184. package/lib/plugins/sharding.js +43 -15
  185. package/lib/plugins/trackTransaction.js +46 -34
  186. package/lib/query.js +1844 -1909
  187. package/lib/{queryhelpers.js → queryHelpers.js} +184 -81
  188. package/lib/schema/array.js +229 -169
  189. package/lib/schema/bigint.js +281 -0
  190. package/lib/schema/boolean.js +90 -26
  191. package/lib/schema/buffer.js +119 -50
  192. package/lib/schema/date.js +102 -38
  193. package/lib/schema/decimal128.js +88 -37
  194. package/lib/schema/{documentarray.js → documentArray.js} +259 -151
  195. package/lib/schema/documentArrayElement.js +180 -0
  196. package/lib/schema/double.js +244 -0
  197. package/lib/schema/index.js +12 -19
  198. package/lib/schema/int32.js +288 -0
  199. package/lib/schema/map.js +129 -20
  200. package/lib/schema/mixed.js +40 -26
  201. package/lib/schema/number.js +128 -51
  202. package/lib/schema/{objectid.js → objectId.js} +89 -47
  203. package/lib/schema/operators/exists.js +1 -1
  204. package/lib/schema/operators/geospatial.js +2 -2
  205. package/lib/schema/operators/text.js +4 -4
  206. package/lib/schema/string.js +125 -66
  207. package/lib/schema/subdocument.js +443 -0
  208. package/lib/schema/symbols.js +2 -0
  209. package/lib/schema/union.js +167 -0
  210. package/lib/schema/uuid.js +90 -120
  211. package/lib/schema.js +1267 -388
  212. package/lib/{schematype.js → schemaType.js} +481 -246
  213. package/lib/standardSchema/convertErrorToIssues.js +20 -0
  214. package/lib/{statemachine.js → stateMachine.js} +66 -17
  215. package/lib/tracing.js +38 -0
  216. package/lib/types/array/index.js +13 -10
  217. package/lib/types/array/methods/index.js +243 -63
  218. package/lib/types/{ArraySubdocument.js → arraySubdocument.js} +35 -14
  219. package/lib/types/buffer.js +31 -14
  220. package/lib/types/decimal128.js +1 -1
  221. package/lib/types/{DocumentArray → documentArray}/index.js +13 -13
  222. package/lib/types/{DocumentArray → documentArray}/methods/index.js +197 -31
  223. package/lib/types/double.js +13 -0
  224. package/lib/types/index.js +5 -2
  225. package/lib/types/map.js +62 -25
  226. package/lib/types/objectid.js +2 -2
  227. package/lib/types/subdocument.js +79 -58
  228. package/lib/types/uuid.js +13 -0
  229. package/lib/utils.js +201 -155
  230. package/lib/{validoptions.js → validOptions.js} +10 -2
  231. package/lib/{virtualtype.js → virtualType.js} +47 -18
  232. package/package.json +75 -92
  233. package/types/aggregate.d.ts +31 -7
  234. package/types/augmentations.d.ts +2 -2
  235. package/types/collection.d.ts +21 -16
  236. package/types/connection.d.ts +82 -27
  237. package/types/cursor.d.ts +15 -10
  238. package/types/document.d.ts +137 -56
  239. package/types/error.d.ts +11 -6
  240. package/types/expressions.d.ts +33 -2
  241. package/types/index.d.ts +805 -190
  242. package/types/indexes.d.ts +85 -13
  243. package/types/inferhydrateddoctype.d.ts +151 -0
  244. package/types/inferrawdoctype.d.ts +201 -0
  245. package/types/inferschematype.d.ts +287 -128
  246. package/types/middlewares.d.ts +50 -7
  247. package/types/models.d.ts +1555 -268
  248. package/types/mongooseoptions.d.ts +56 -7
  249. package/types/pipelinestage.d.ts +42 -3
  250. package/types/populate.d.ts +63 -1
  251. package/types/query.d.ts +592 -255
  252. package/types/schemaoptions.d.ts +78 -12
  253. package/types/schematypes.d.ts +254 -65
  254. package/types/session.d.ts +0 -4
  255. package/types/tracing.d.ts +10 -0
  256. package/types/types.d.ts +25 -8
  257. package/types/utility.d.ts +329 -30
  258. package/types/validation.d.ts +19 -14
  259. package/types/virtuals.d.ts +10 -10
  260. package/.eslintrc.js +0 -232
  261. package/.mocharc.yml +0 -4
  262. package/browser.js +0 -8
  263. package/lgtm.yml +0 -12
  264. package/lib/browser.js +0 -158
  265. package/lib/browserDocument.js +0 -101
  266. package/lib/cursor/ChangeStream.js +0 -154
  267. package/lib/cursor/QueryCursor.js +0 -545
  268. package/lib/document_provider.js +0 -30
  269. package/lib/drivers/browser/ReadPreference.js +0 -7
  270. package/lib/drivers/browser/binary.js +0 -14
  271. package/lib/drivers/browser/decimal128.js +0 -7
  272. package/lib/drivers/browser/index.js +0 -16
  273. package/lib/drivers/browser/objectid.js +0 -29
  274. package/lib/drivers/node-mongodb-native/ReadPreference.js +0 -47
  275. package/lib/drivers/node-mongodb-native/binary.js +0 -10
  276. package/lib/drivers/node-mongodb-native/decimal128.js +0 -7
  277. package/lib/drivers/node-mongodb-native/objectid.js +0 -16
  278. package/lib/error/disconnected.js +0 -33
  279. package/lib/helpers/printStrictQueryWarning.js +0 -11
  280. package/lib/helpers/promiseOrCallback.js +0 -55
  281. package/lib/helpers/query/applyQueryMiddleware.js +0 -79
  282. package/lib/helpers/query/completeMany.js +0 -52
  283. package/lib/helpers/query/wrapThunk.js +0 -36
  284. package/lib/options/SchemaSubdocumentOptions.js +0 -42
  285. package/lib/options/removeOptions.js +0 -14
  286. package/lib/plugins/removeSubdocs.js +0 -31
  287. package/lib/plugins/validateBeforeSave.js +0 -45
  288. package/lib/promise_provider.js +0 -49
  289. package/lib/schema/DocumentArrayElement.js +0 -100
  290. package/lib/schema/SubdocumentPath.js +0 -369
  291. package/scripts/build-browser.js +0 -18
  292. package/scripts/create-tarball.js +0 -7
  293. package/scripts/generateSearch.js +0 -154
  294. package/scripts/tsc-diagnostics-check.js +0 -15
  295. package/tools/auth.js +0 -31
  296. package/tools/repl.js +0 -35
  297. package/tools/sharded.js +0 -46
  298. package/tsconfig.json +0 -9
  299. /package/lib/{connectionstate.js → connectionState.js} +0 -0
  300. /package/lib/helpers/populate/{SkipPopulateValue.js → skipPopulateValue.js} +0 -0
  301. /package/lib/options/{PopulateOptions.js → populateOptions.js} +0 -0
  302. /package/lib/types/{DocumentArray → documentArray}/isMongooseDocumentArray.js +0 -0
package/lib/schema.js CHANGED
@@ -7,30 +7,35 @@
7
7
  const EventEmitter = require('events').EventEmitter;
8
8
  const Kareem = require('kareem');
9
9
  const MongooseError = require('./error/mongooseError');
10
- const SchemaType = require('./schematype');
11
- const SchemaTypeOptions = require('./options/SchemaTypeOptions');
12
- const VirtualOptions = require('./options/VirtualOptions');
13
- const VirtualType = require('./virtualtype');
10
+ const PathTrie = require('./helpers/pathTrie');
11
+ const SchemaDefaultsCache = require('./defaults/schemaDefaultsCache');
12
+ const SchemaType = require('./schemaType');
13
+ const SchemaTypeOptions = require('./options/schemaTypeOptions');
14
+ const VirtualOptions = require('./options/virtualOptions');
15
+ const VirtualType = require('./virtualType');
14
16
  const addAutoId = require('./helpers/schema/addAutoId');
17
+ const clone = require('./helpers/clone');
15
18
  const get = require('./helpers/get');
16
19
  const getConstructorName = require('./helpers/getConstructorName');
17
20
  const getIndexes = require('./helpers/schema/getIndexes');
21
+ const handleReadPreferenceAliases = require('./helpers/query/handleReadPreferenceAliases');
18
22
  const idGetter = require('./helpers/schema/idGetter');
23
+ const isMongooseDocument = require('./helpers/isMongooseDocument');
24
+ const isIndexSpecEqual = require('./helpers/indexes/isIndexSpecEqual');
19
25
  const merge = require('./helpers/schema/merge');
20
26
  const mpath = require('mpath');
21
- const readPref = require('./driver').get().ReadPreference;
27
+ const setPopulatedVirtualValue = require('./helpers/populate/setPopulatedVirtualValue');
22
28
  const setupTimestamps = require('./helpers/timestamps/setupTimestamps');
29
+ const symbols = require('./schema/symbols');
23
30
  const utils = require('./utils');
24
31
  const validateRef = require('./helpers/populate/validateRef');
25
- const util = require('util');
26
32
 
27
33
  const hasNumericSubpathRegex = /\.\d+(\.|$)/;
28
34
 
29
35
  let MongooseTypes;
30
36
 
31
- const queryHooks = require('./helpers/query/applyQueryMiddleware').
32
- middlewareFunctions;
33
- const documentHooks = require('./helpers/model/applyHooks').middlewareFunctions;
37
+ const queryHooks = require('./constants').queryMiddlewareFunctions;
38
+ const documentHooks = require('./constants').documentMiddlewareFunctions;
34
39
  const hookNames = queryHooks.concat(documentHooks).
35
40
  reduce((s, hook) => s.add(hook), new Set());
36
41
 
@@ -38,6 +43,8 @@ const isPOJO = utils.isPOJO;
38
43
 
39
44
  let id = 0;
40
45
 
46
+ const numberRE = /^\d+$/;
47
+
41
48
  /**
42
49
  * Schema constructor.
43
50
  *
@@ -48,37 +55,45 @@ let id = 0;
48
55
  * const Tree = mongoose.model('Tree', schema);
49
56
  *
50
57
  * // setting schema options
51
- * new Schema({ name: String }, { _id: false, autoIndex: false })
58
+ * new Schema({ name: String }, { id: false, autoIndex: false })
52
59
  *
53
60
  * #### Options:
54
61
  *
55
- * - [autoIndex](/docs/guide.html#autoIndex): bool - defaults to null (which means use the connection's autoIndex option)
56
- * - [autoCreate](/docs/guide.html#autoCreate): bool - defaults to null (which means use the connection's autoCreate option)
57
- * - [bufferCommands](/docs/guide.html#bufferCommands): bool - defaults to true
58
- * - [bufferTimeoutMS](/docs/guide.html#bufferTimeoutMS): number - defaults to 10000 (10 seconds). If `bufferCommands` is enabled, the amount of time Mongoose will wait for connectivity to be restablished before erroring out.
59
- * - [capped](/docs/guide.html#capped): bool | number | object - defaults to false
60
- * - [collection](/docs/guide.html#collection): string - no default
61
- * - [discriminatorKey](/docs/guide.html#discriminatorKey): string - defaults to `__t`
62
- * - [id](/docs/guide.html#id): bool - defaults to true
63
- * - [_id](/docs/guide.html#_id): bool - defaults to true
64
- * - [minimize](/docs/guide.html#minimize): bool - controls [document#toObject](#document_Document-toObject) behavior when called manually - defaults to true
65
- * - [read](/docs/guide.html#read): string
66
- * - [writeConcern](/docs/guide.html#writeConcern): object - defaults to null, use to override [the MongoDB server's default write concern settings](https://www.mongodb.com/docs/manual/reference/write-concern/)
67
- * - [shardKey](/docs/guide.html#shardKey): object - defaults to `null`
68
- * - [strict](/docs/guide.html#strict): bool - defaults to true
69
- * - [strictQuery](/docs/guide.html#strictQuery): bool - defaults to false
70
- * - [toJSON](/docs/guide.html#toJSON) - object - no default
71
- * - [toObject](/docs/guide.html#toObject) - object - no default
72
- * - [typeKey](/docs/guide.html#typeKey) - string - defaults to 'type'
73
- * - [validateBeforeSave](/docs/guide.html#validateBeforeSave) - bool - defaults to `true`
74
- * - [versionKey](/docs/guide.html#versionKey): string or object - defaults to "__v"
75
- * - [optimisticConcurrency](/docs/guide.html#optimisticConcurrency): bool - defaults to false. Set to true to enable [optimistic concurrency](https://thecodebarbarian.com/whats-new-in-mongoose-5-10-optimistic-concurrency.html).
76
- * - [collation](/docs/guide.html#collation): object - defaults to null (which means use no collation)
77
- * - [timeseries](/docs/guide.html#timeseries): object - defaults to null (which means this schema's collection won't be a timeseries collection)
78
- * - [selectPopulatedPaths](/docs/guide.html#selectPopulatedPaths): boolean - defaults to `true`
79
- * - [skipVersioning](/docs/guide.html#skipVersioning): object - paths to exclude from versioning
80
- * - [timestamps](/docs/guide.html#timestamps): object or boolean - defaults to `false`. If true, Mongoose adds `createdAt` and `updatedAt` properties to your schema and manages those properties for you.
81
- * - [pluginTags](/docs/guide.html#pluginTags): array of strings - defaults to `undefined`. If set and plugin called with `tags` option, will only apply that plugin to schemas with a matching tag.
62
+ * - [autoIndex](https://mongoosejs.com/docs/guide.html#autoIndex): bool - defaults to null (which means use the connection's autoIndex option)
63
+ * - [autoCreate](https://mongoosejs.com/docs/guide.html#autoCreate): bool - defaults to null (which means use the connection's autoCreate option)
64
+ * - [bufferCommands](https://mongoosejs.com/docs/guide.html#bufferCommands): bool - defaults to true
65
+ * - [bufferTimeoutMS](https://mongoosejs.com/docs/guide.html#bufferTimeoutMS): number - defaults to 10000 (10 seconds). If `bufferCommands` is enabled, the amount of time Mongoose will wait for connectivity to be established before erroring out.
66
+ * - [capped](https://mongoosejs.com/docs/guide.html#capped): bool | number | object - defaults to false
67
+ * - [collection](https://mongoosejs.com/docs/guide.html#collection): string - no default
68
+ * - [discriminatorKey](https://mongoosejs.com/docs/guide.html#discriminatorKey): string - defaults to `__t`
69
+ * - [id](https://mongoosejs.com/docs/guide.html#id): bool - defaults to true
70
+ * - [_id](https://mongoosejs.com/docs/guide.html#_id): bool - defaults to true
71
+ * - [minimize](https://mongoosejs.com/docs/guide.html#minimize): bool - controls [document#toObject](https://mongoosejs.com/docs/api/document.html#Document.prototype.toObject()) behavior when called manually - defaults to true
72
+ * - [read](https://mongoosejs.com/docs/guide.html#read): string
73
+ * - [readConcern](https://mongoosejs.com/docs/guide.html#readConcern): object - defaults to null, use to set a default [read concern](https://www.mongodb.com/docs/manual/reference/read-concern/) for all queries.
74
+ * - [writeConcern](https://mongoosejs.com/docs/guide.html#writeConcern): object - defaults to null, use to override [the MongoDB server's default write concern settings](https://www.mongodb.com/docs/manual/reference/write-concern/)
75
+ * - [shardKey](https://mongoosejs.com/docs/guide.html#shardKey): object - defaults to `null`
76
+ * - [strict](https://mongoosejs.com/docs/guide.html#strict): bool - defaults to true
77
+ * - [strictQuery](https://mongoosejs.com/docs/guide.html#strictQuery): bool - defaults to false
78
+ * - [strictRead](https://mongoosejs.com/docs/guide.html#strictRead): bool or 'throw' - defaults to false. If set to `true`, fields not in the schema will be stripped when hydrating documents from MongoDB. If set to `'throw'`, an error will be thrown when a field not in the schema is encountered during document hydration.
79
+ * - [toJSON](https://mongoosejs.com/docs/guide.html#toJSON) - object - no default
80
+ * - [toObject](https://mongoosejs.com/docs/guide.html#toObject) - object - no default
81
+ * - [typeKey](https://mongoosejs.com/docs/guide.html#typeKey) - string - defaults to 'type'
82
+ * - [validateBeforeSave](https://mongoosejs.com/docs/guide.html#validateBeforeSave) - bool - defaults to `true`
83
+ * - [validateModifiedOnly](https://mongoosejs.com/docs/api/document.html#Document.prototype.validate()) - bool - defaults to `false`
84
+ * - [versionKey](https://mongoosejs.com/docs/guide.html#versionKey): string or object - defaults to "__v"
85
+ * - [optimisticConcurrency](https://mongoosejs.com/docs/guide.html#optimisticConcurrency): bool or string[] or { exclude: string[] } - defaults to false. Set to true to enable [optimistic concurrency](https://thecodebarbarian.com/whats-new-in-mongoose-5-10-optimistic-concurrency.html) for all fields. Set to a string array to enable optimistic concurrency only for the specified fields; note that this **replaces** the default array versioning behavior. Set to `{ exclude: string[] }` to enable optimistic concurrency for all fields except the specified ones; this also replaces the default array versioning. Paths may include the map wildcard `$*`, like `'settings.$*'`, to match all keys of a map.
86
+ * - [collation](https://mongoosejs.com/docs/guide.html#collation): object - defaults to null (which means use no collation)
87
+ * - [timeseries](https://mongoosejs.com/docs/guide.html#timeseries): object - defaults to null (which means this schema's collection won't be a timeseries collection)
88
+ * - [selectPopulatedPaths](https://mongoosejs.com/docs/guide.html#selectPopulatedPaths): boolean - defaults to `true`
89
+ * - [skipVersioning](https://mongoosejs.com/docs/guide.html#skipVersioning): object - paths to exclude from versioning
90
+ * - [timestamps](https://mongoosejs.com/docs/guide.html#timestamps): object or boolean - defaults to `false`. If true, Mongoose adds `createdAt` and `updatedAt` properties to your schema and manages those properties for you.
91
+ * - [pluginTags](https://mongoosejs.com/docs/guide.html#pluginTags): array of strings - defaults to `undefined`. If set and plugin called with `tags` option, will only apply that plugin to schemas with a matching tag.
92
+ * - [virtuals](https://mongoosejs.com/docs/tutorials/virtuals.html#virtuals-via-schema-options): object - virtuals to define, alias for [`.virtual`](https://mongoosejs.com/docs/api/schema.html#Schema.prototype.virtual())
93
+ * - [collectionOptions]: object with options passed to [`createCollection()`](https://www.mongodb.com/docs/manual/reference/method/db.createCollection/) when calling `Model.createCollection()` or `autoCreate` set to true.
94
+ * - [encryptionType]: the encryption type for the schema. Valid options are `csfle` or `queryableEncryption`. See https://mongoosejs.com/docs/field-level-encryption.html.
95
+ * - [lean]: boolean - set to true to make all queries use [lean](https://mongoosejs.com/docs/tutorials/lean.html) by default. Defaults to false.
96
+ * - [defaultSort](https://mongoosejs.com/docs/guide.html#defaultSort): string, object, array, or map - defaults to `undefined`. The sort to use for queries that don't specify a sort, like `find()`, `findOne()`, and `findOneAndUpdate()`. Does not apply to `updateOne()` and `replaceOne()` for compatibility with MongoDB < 8.0.
82
97
  *
83
98
  * #### Options for Nested Schemas:
84
99
  *
@@ -88,8 +103,8 @@ let id = 0;
88
103
  *
89
104
  * _When nesting schemas, (`children` in the example above), always declare the child schema first before passing it into its parent._
90
105
  *
91
- * @param {Object|Schema|Array} [definition] Can be one of: object describing schema paths, or schema to copy, or array of objects and schemas
92
- * @param {Object} [options]
106
+ * @param {object|Schema|Array} [definition] Can be one of: object describing schema paths, or schema to copy, or array of objects and schemas
107
+ * @param {object} [options]
93
108
  * @inherits NodeJS EventEmitter https://nodejs.org/api/events.html#class-eventemitter
94
109
  * @event `init`: Emitted after the schema is compiled into a `Model`.
95
110
  * @api public
@@ -110,16 +125,18 @@ function Schema(obj, options) {
110
125
  this.inherits = {};
111
126
  this.callQueue = [];
112
127
  this._indexes = [];
113
- this.methods = (options && options.methods) || {};
128
+ this._searchIndexes = [];
129
+ this.methods = options?.methods || {};
114
130
  this.methodOptions = {};
115
- this.statics = (options && options.statics) || {};
131
+ this.statics = options?.statics || {};
116
132
  this.tree = {};
117
- this.query = (options && options.query) || {};
133
+ this.query = options?.query || {};
118
134
  this.childSchemas = [];
119
135
  this.plugins = [];
120
136
  // For internal debugging. Do not use this to try to save a schema in MDB.
121
137
  this.$id = ++id;
122
138
  this.mapPaths = [];
139
+ this.encryptedFields = {};
123
140
 
124
141
  this.s = {
125
142
  hooks: new Kareem()
@@ -136,7 +153,7 @@ function Schema(obj, options) {
136
153
  }
137
154
 
138
155
  // build virtual paths
139
- if (options && options.virtuals) {
156
+ if (options?.virtuals) {
140
157
  const virtuals = options.virtuals;
141
158
  const pathNames = Object.keys(virtuals);
142
159
  for (const pathName of pathNames) {
@@ -154,7 +171,7 @@ function Schema(obj, options) {
154
171
  }
155
172
 
156
173
  // check if _id's value is a subdocument (gh-2276)
157
- const _idSubDoc = obj && obj._id && utils.isObject(obj._id);
174
+ const _idSubDoc = obj?._id && utils.isObject(obj._id);
158
175
 
159
176
  // ensure the documents get an auto _id unless disabled
160
177
  const auto_id = !this.paths['_id'] &&
@@ -193,7 +210,7 @@ function aliasFields(schema, paths) {
193
210
  if (Array.isArray(alias)) {
194
211
  for (const a of alias) {
195
212
  if (typeof a !== 'string') {
196
- throw new Error('Invalid value for alias option on ' + prop + ', got ' + a);
213
+ throw new MongooseError('Invalid value for alias option on ' + prop + ', got ' + a);
197
214
  }
198
215
 
199
216
  schema.aliases[a] = prop;
@@ -219,7 +236,7 @@ function aliasFields(schema, paths) {
219
236
  }
220
237
 
221
238
  if (typeof alias !== 'string') {
222
- throw new Error('Invalid value for alias option on ' + prop + ', got ' + alias);
239
+ throw new MongooseError('Invalid value for alias option on ' + prop + ', got ' + alias);
223
240
  }
224
241
 
225
242
  schema.aliases[alias] = prop;
@@ -362,6 +379,29 @@ Schema.prototype.paths;
362
379
 
363
380
  Schema.prototype.tree;
364
381
 
382
+ /**
383
+ * Creates a new schema with the given definition and options. Equivalent to `new Schema(definition, options)`.
384
+ *
385
+ * `Schema.create()` is primarily useful for automatic schema type inference in TypeScript.
386
+ *
387
+ * #### Example:
388
+ *
389
+ * const schema = Schema.create({ name: String }, { toObject: { virtuals: true } });
390
+ * // Equivalent:
391
+ * const schema2 = new Schema({ name: String }, { toObject: { virtuals: true } });
392
+ *
393
+ * @param {object} definition
394
+ * @param {object} [options]
395
+ * @return {Schema} the new schema
396
+ * @api public
397
+ * @memberOf Schema
398
+ * @static
399
+ */
400
+
401
+ Schema.create = function create(definition, options) {
402
+ return new Schema(definition, options);
403
+ };
404
+
365
405
  /**
366
406
  * Returns a deep copy of the schema
367
407
  *
@@ -397,20 +437,33 @@ Schema.prototype._clone = function _clone(Constructor) {
397
437
  const s = new Constructor({}, this._userProvidedOptions);
398
438
  s.base = this.base;
399
439
  s.obj = this.obj;
400
- s.options = utils.clone(this.options);
440
+ s.options = clone(this.options);
401
441
  s.callQueue = this.callQueue.map(function(f) { return f; });
402
- s.methods = utils.clone(this.methods);
403
- s.methodOptions = utils.clone(this.methodOptions);
404
- s.statics = utils.clone(this.statics);
405
- s.query = utils.clone(this.query);
442
+ s.methods = clone(this.methods);
443
+ s.methodOptions = clone(this.methodOptions);
444
+ s.statics = clone(this.statics);
445
+ s.query = clone(this.query);
406
446
  s.plugins = Array.prototype.slice.call(this.plugins);
407
- s._indexes = utils.clone(this._indexes);
447
+ s._indexes = clone(this._indexes);
448
+ s._searchIndexes = clone(this._searchIndexes);
408
449
  s.s.hooks = this.s.hooks.clone();
409
450
 
410
- s.tree = utils.clone(this.tree);
411
- s.paths = utils.clone(this.paths);
412
- s.nested = utils.clone(this.nested);
413
- s.subpaths = utils.clone(this.subpaths);
451
+ s.tree = clone(this.tree);
452
+ s.paths = Object.fromEntries(
453
+ Object.entries(this.paths).map(([key, value]) => ([key, value.clone()]))
454
+ );
455
+ s.nested = clone(this.nested);
456
+ s.subpaths = clone(this.subpaths);
457
+
458
+ s.mapPaths = [];
459
+ for (const [path, schemaType] of Object.entries(s.paths)) {
460
+ const mapPath = path + '.$*';
461
+ if (!schemaType.$isSchemaMap || !Object.hasOwn(s.paths, mapPath)) {
462
+ continue;
463
+ }
464
+ s.paths[mapPath] = schemaType.$__schemaType;
465
+ s.mapPaths.push(s.paths[mapPath]);
466
+ }
414
467
  for (const schemaType of Object.values(s.paths)) {
415
468
  if (schemaType.$isSingleNested) {
416
469
  const path = schemaType.path;
@@ -430,15 +483,17 @@ Schema.prototype._clone = function _clone(Constructor) {
430
483
  }
431
484
  }
432
485
  }
433
- s.childSchemas = gatherChildSchemas(s);
486
+ s._gatherChildSchemas();
434
487
 
435
- s.virtuals = utils.clone(this.virtuals);
488
+ s.virtuals = clone(this.virtuals);
436
489
  s.$globalPluginsApplied = this.$globalPluginsApplied;
437
490
  s.$isRootDiscriminator = this.$isRootDiscriminator;
438
491
  s.$implicitlyCreated = this.$implicitlyCreated;
492
+ if (this.$timestamps != null) {
493
+ s.$timestamps = Object.assign({}, this.$timestamps);
494
+ }
439
495
  s.$id = ++id;
440
496
  s.$originalSchemaId = this.$id;
441
- s.mapPaths = [].concat(this.mapPaths);
442
497
 
443
498
  if (this.discriminatorMapping != null) {
444
499
  s.discriminatorMapping = Object.assign({}, this.discriminatorMapping);
@@ -447,11 +502,13 @@ Schema.prototype._clone = function _clone(Constructor) {
447
502
  s.discriminators = Object.assign({}, this.discriminators);
448
503
  }
449
504
  if (this._applyDiscriminators != null) {
450
- s._applyDiscriminators = Object.assign({}, this._applyDiscriminators);
505
+ s._applyDiscriminators = new Map(this._applyDiscriminators);
451
506
  }
452
507
 
453
508
  s.aliases = Object.assign({}, this.aliases);
454
509
 
510
+ s.encryptedFields = clone(this.encryptedFields);
511
+
455
512
  return s;
456
513
  };
457
514
 
@@ -470,8 +527,8 @@ Schema.prototype._clone = function _clone(Constructor) {
470
527
  * newSchema.path('name'); // SchemaString { ... }
471
528
  * newSchema.path('age'); // undefined
472
529
  *
473
- * @param {String[]} paths List of Paths to pick for the new Schema
474
- * @param {Object} [options] Options to pass to the new Schema Constructor (same as `new Schema(.., Options)`). Defaults to `this.options` if not set.
530
+ * @param {string[]} paths List of Paths to pick for the new Schema
531
+ * @param {object} [options] Options to pass to the new Schema Constructor (same as `new Schema(.., Options)`). Defaults to `this.options` if not set.
475
532
  * @return {Schema}
476
533
  * @api public
477
534
  */
@@ -484,7 +541,16 @@ Schema.prototype.pick = function(paths, options) {
484
541
  }
485
542
 
486
543
  for (const path of paths) {
487
- if (this.nested[path]) {
544
+ if (this._hasEncryptedField(path)) {
545
+ const encrypt = this.encryptedFields[path];
546
+ const schemaType = this.path(path);
547
+ newSchema.add({
548
+ [path]: {
549
+ encrypt,
550
+ [this.options.typeKey]: schemaType
551
+ }
552
+ });
553
+ } else if (this.nested[path]) {
488
554
  newSchema.add({ [path]: get(this.tree, path) });
489
555
  } else {
490
556
  const schematype = this.path(path);
@@ -495,6 +561,10 @@ Schema.prototype.pick = function(paths, options) {
495
561
  }
496
562
  }
497
563
 
564
+ if (!this._hasEncryptedFields()) {
565
+ newSchema.options.encryptionType = null;
566
+ }
567
+
498
568
  return newSchema;
499
569
  };
500
570
 
@@ -512,8 +582,8 @@ Schema.prototype.pick = function(paths, options) {
512
582
  * newSchema.path('name'); // SchemaString { ... }
513
583
  * newSchema.path('age'); // undefined
514
584
  *
515
- * @param {String[]} paths List of Paths to omit for the new Schema
516
- * @param {Object} [options] Options to pass to the new Schema Constructor (same as `new Schema(.., Options)`). Defaults to `this.options` if not set.
585
+ * @param {string[]} paths List of Paths to omit for the new Schema
586
+ * @param {object} [options] Options to pass to the new Schema Constructor (same as `new Schema(.., Options)`). Defaults to `this.options` if not set.
517
587
  * @return {Schema}
518
588
  * @api public
519
589
  */
@@ -531,34 +601,28 @@ Schema.prototype.omit = function(paths, options) {
531
601
 
532
602
  newSchema.remove(paths);
533
603
 
534
- for (const nested in newSchema.singleNestedPaths) {
535
- if (paths.includes(nested)) {
536
- delete newSchema.singleNestedPaths[nested];
537
- }
538
- }
539
-
540
604
  return newSchema;
541
605
  };
542
606
 
543
607
  /**
544
608
  * Returns default options for this schema, merged with `options`.
545
609
  *
546
- * @param {Object} [options] Options to overwrite the default options
547
- * @return {Object} The merged options of `options` and the default options
610
+ * @param {object} [options] Options to overwrite the default options
611
+ * @return {object} The merged options of `options` and the default options
548
612
  * @api private
549
613
  */
550
614
 
551
615
  Schema.prototype.defaultOptions = function(options) {
552
- this._userProvidedOptions = options == null ? {} : utils.clone(options);
553
- const baseOptions = this.base && this.base.options || {};
554
- const strict = 'strict' in baseOptions ? baseOptions.strict : true;
555
- const id = 'id' in baseOptions ? baseOptions.id : true;
556
- options = utils.options({
557
- strict: strict,
558
- strictQuery: 'strict' in this._userProvidedOptions ?
559
- this._userProvidedOptions.strict :
560
- 'strictQuery' in baseOptions ?
561
- baseOptions.strictQuery : strict,
616
+ this._userProvidedOptions = options == null ? {} : clone(options);
617
+ const baseOptions = this.base?.options || {};
618
+ const defaultStrict = baseOptions.strict ?? true;
619
+ const defaultStrictQuery = baseOptions.strictQuery ?? false;
620
+ const defaultStrictRead = baseOptions.strictRead ?? false;
621
+ const defaultId = baseOptions.id ?? true;
622
+ options = {
623
+ strict: defaultStrict,
624
+ strictQuery: defaultStrictQuery,
625
+ strictRead: defaultStrictRead,
562
626
  bufferCommands: true,
563
627
  capped: false, // { size, max, autoIndexId }
564
628
  versionKey: '__v',
@@ -569,20 +633,34 @@ Schema.prototype.defaultOptions = function(options) {
569
633
  shardKey: null,
570
634
  read: null,
571
635
  validateBeforeSave: true,
636
+ validateModifiedOnly: false,
572
637
  // the following are only applied at construction time
573
638
  _id: true,
574
- id: id,
575
- typeKey: 'type'
576
- }, utils.clone(options));
639
+ id: defaultId,
640
+ typeKey: 'type',
641
+ ...options
642
+ };
577
643
 
578
- if (options.read) {
579
- options.read = readPref(options.read);
580
- }
644
+ // Treat `undefined` as "not provided" for these options
645
+ options.strict ??= defaultStrict;
646
+ options.strictQuery ??= defaultStrictQuery;
647
+ options.id ??= defaultId;
581
648
 
582
649
  if (options.versionKey && typeof options.versionKey !== 'string') {
583
650
  throw new MongooseError('`versionKey` must be falsy or string, got `' + (typeof options.versionKey) + '`');
584
651
  }
585
652
 
653
+ _validateDefaultSort(options.defaultSort);
654
+
655
+ if (typeof options.read === 'string') {
656
+ options.read = handleReadPreferenceAliases(options.read);
657
+ } else if (Array.isArray(options.read) && typeof options.read[0] === 'string') {
658
+ options.read = {
659
+ mode: handleReadPreferenceAliases(options.read[0]),
660
+ tags: options.read[1]
661
+ };
662
+ }
663
+
586
664
  if (options.optimisticConcurrency && !options.versionKey) {
587
665
  throw new MongooseError('Must set `versionKey` if using `optimisticConcurrency`');
588
666
  }
@@ -609,17 +687,98 @@ Schema.prototype.defaultOptions = function(options) {
609
687
  * doc.element; // '#hero'
610
688
  * doc instanceof ClickedModel; // true
611
689
  *
612
- * @param {String} name the name of the discriminator
690
+ * @param {string} name the name of the discriminator
613
691
  * @param {Schema} schema the discriminated Schema
692
+ * @param {object} [options] discriminator options
693
+ * @param {string} [options.value] the string stored in the `discriminatorKey` property. If not specified, Mongoose uses the `name` parameter.
694
+ * @param {boolean} [options.clone=true] By default, `discriminator()` clones the given `schema`. Set to `false` to skip cloning.
695
+ * @param {boolean} [options.overwriteModels=false] by default, Mongoose does not allow you to define a discriminator with the same name as another discriminator. Set this to allow overwriting discriminators with the same name.
696
+ * @param {boolean} [options.mergeHooks=true] By default, Mongoose merges the base schema's hooks with the discriminator schema's hooks. Set this option to `false` to make Mongoose use the discriminator schema's hooks instead.
697
+ * @param {boolean} [options.mergePlugins=true] By default, Mongoose merges the base schema's plugins with the discriminator schema's plugins. Set this option to `false` to make Mongoose use the discriminator schema's plugins instead.
614
698
  * @return {Schema} the Schema instance
615
699
  * @api public
616
700
  */
617
- Schema.prototype.discriminator = function(name, schema) {
618
- this._applyDiscriminators = Object.assign(this._applyDiscriminators || {}, { [name]: schema });
701
+ Schema.prototype.discriminator = function(name, schema, options) {
702
+ this._applyDiscriminators = this._applyDiscriminators || new Map();
703
+ this._applyDiscriminators.set(name, { schema, options });
619
704
 
620
705
  return this;
621
706
  };
622
707
 
708
+ /*!
709
+ * Get the document middleware for this schema, filtering out any hooks that are specific to queries.
710
+ */
711
+ Schema.prototype._getDocumentMiddleware = function _getDocumentMiddleware(isSubdocument) {
712
+ // Check `shardKey` at compile time rather than when the sharding plugin is applied, because
713
+ // discriminators apply plugins before inheriting the base schema's options.
714
+ const hasShardKey = !!(this.options.shardKey || this.options.shardkey);
715
+ return this.s.hooks.
716
+ filter(hook => {
717
+ if (isSubdocument && hook.fn[symbols.skipOnSubdocuments]) {
718
+ return false;
719
+ }
720
+ if (!hasShardKey && hook.fn[symbols.requiresShardKey]) {
721
+ return false;
722
+ }
723
+ if (hook.name === 'updateOne' || hook.name === 'deleteOne') {
724
+ return !!hook['document'];
725
+ }
726
+ if (hook.name === 'remove' || hook.name === 'init') {
727
+ return hook['document'] == null || !!hook['document'];
728
+ }
729
+ if (hook.query != null || hook.document != null) {
730
+ return hook.document !== false;
731
+ }
732
+ return true;
733
+ }).
734
+ filter(hook => {
735
+ // If user has overwritten the method, don't apply built-in middleware
736
+ if (this.methods[hook.name]) {
737
+ return !hook.fn[symbols.builtInMiddleware];
738
+ }
739
+
740
+ return true;
741
+ });
742
+ };
743
+
744
+ /*!
745
+ * Get this schema's default toObject/toJSON options, including Mongoose global
746
+ * options.
747
+ */
748
+
749
+ Schema.prototype._defaultToObjectOptions = function(json) {
750
+ const path = json ? 'toJSON' : 'toObject';
751
+ if (this._defaultToObjectOptionsMap && path in this._defaultToObjectOptionsMap) {
752
+ return this._defaultToObjectOptionsMap[path];
753
+ }
754
+
755
+ const baseOptions = this.base?.options?.[path] || {};
756
+ const schemaOptions = this.options[path] || {};
757
+ // merge base default options with Schema's set default options if available.
758
+ // `clone` is necessary here because `utils.options` directly modifies the second input.
759
+ const defaultOptions = Object.assign({}, baseOptions, schemaOptions);
760
+
761
+ this._defaultToObjectOptionsMap = this._defaultToObjectOptionsMap || {};
762
+ this._defaultToObjectOptionsMap[path] = utils.hasOwnKeys(defaultOptions) ? defaultOptions : null;
763
+ return defaultOptions;
764
+ };
765
+
766
+ /**
767
+ * Sets the encryption type of the schema, if a value is provided, otherwise
768
+ * returns the encryption type.
769
+ *
770
+ * @param {'csfle' | 'queryableEncryption' | null | undefined} encryptionType plain object with paths to add, or another schema
771
+ */
772
+ Schema.prototype.encryptionType = function encryptionType(encryptionType) {
773
+ if (arguments.length === 0) {
774
+ return this.options.encryptionType;
775
+ }
776
+ if (!(typeof encryptionType === 'string' || encryptionType === null)) {
777
+ throw new MongooseError(`invalid \`encryptionType\`: ${encryptionType}`);
778
+ }
779
+ this.options.encryptionType = encryptionType;
780
+ };
781
+
623
782
  /**
624
783
  * Adds key path / schema type pairs to this schema.
625
784
  *
@@ -633,16 +792,15 @@ Schema.prototype.discriminator = function(name, schema) {
633
792
  * // getters, setters, indexes, methods, and statics.
634
793
  * TurboManSchema.add(ToySchema).add({ year: Number });
635
794
  *
636
- * @param {Object|Schema} obj plain object with paths to add, or another schema
637
- * @param {String} [prefix] path to prefix the newly added paths with
795
+ * @param {object|Schema} obj plain object with paths to add, or another schema
796
+ * @param {string} [prefix] path to prefix the newly added paths with
638
797
  * @return {Schema} the Schema instance
639
798
  * @api public
640
799
  */
641
800
 
642
801
  Schema.prototype.add = function add(obj, prefix) {
643
- if (obj instanceof Schema || (obj != null && obj.instanceOfSchema)) {
802
+ if (obj instanceof Schema || obj?.instanceOfSchema) {
644
803
  merge(this, obj);
645
-
646
804
  return this;
647
805
  }
648
806
 
@@ -677,7 +835,24 @@ Schema.prototype.add = function add(obj, prefix) {
677
835
  if (key === '_id' && val === false) {
678
836
  continue;
679
837
  }
680
- if (val instanceof VirtualType || (val.constructor && val.constructor.name || null) === 'VirtualType') {
838
+ // Deprecate setting schema paths to primitive types (gh-7558)
839
+ let isMongooseTypeString = false;
840
+ if (typeof val === 'string') {
841
+ // Handle the case in which the type is specified as a string (eg. 'date', 'oid', ...)
842
+ const MongooseTypes = this.base?.Schema.Types ?? Schema.Types;
843
+ const upperVal = val.charAt(0).toUpperCase() + val.substring(1);
844
+ isMongooseTypeString = MongooseTypes[upperVal] != null;
845
+ }
846
+ if (
847
+ key !== '_id' &&
848
+ ((typeof val !== 'object' && typeof val !== 'function' && !isMongooseTypeString) ||
849
+ val == null)
850
+ ) {
851
+ throw new TypeError(`Invalid schema configuration: \`${val}\` is not ` +
852
+ `a valid type at path \`${key}\`. See ` +
853
+ 'https://bit.ly/mongoose-schematypes for a list of valid schema types.');
854
+ }
855
+ if (val instanceof VirtualType || (val.constructor?.name ?? null) === 'VirtualType') {
681
856
  this.virtual(val);
682
857
  continue;
683
858
  }
@@ -694,26 +869,13 @@ Schema.prototype.add = function add(obj, prefix) {
694
869
  this.nested[prefix.substring(0, prefix.length - 1)] = true;
695
870
  }
696
871
  this.path(prefix + key, val);
697
- if (val[0] != null && !(val[0].instanceOfSchema) && utils.isPOJO(val[0].discriminators)) {
872
+ if (!val[0]?.instanceOfSchema && utils.isPOJO(val[0]?.discriminators)) {
698
873
  const schemaType = this.path(prefix + key);
699
874
  for (const key in val[0].discriminators) {
700
875
  schemaType.discriminator(key, val[0].discriminators[key]);
701
876
  }
702
- } else if (val[0] != null && val[0].instanceOfSchema && utils.isPOJO(val[0]._applyDiscriminators)) {
703
- const applyDiscriminators = val[0]._applyDiscriminators || [];
704
- const schemaType = this.path(prefix + key);
705
- for (const disc in applyDiscriminators) {
706
- schemaType.discriminator(disc, applyDiscriminators[disc]);
707
- }
708
- }
709
- else if (val != null && val.instanceOfSchema && utils.isPOJO(val._applyDiscriminators)) {
710
- const applyDiscriminators = val._applyDiscriminators || [];
711
- const schemaType = this.path(prefix + key);
712
- for (const disc in applyDiscriminators) {
713
- schemaType.discriminator(disc, applyDiscriminators[disc]);
714
- }
715
877
  }
716
- } else if (Object.keys(val).length < 1) {
878
+ } else if (utils.hasOwnKeys(val) === false) {
717
879
  // Special-case: {} always interpreted as Mixed path so leaf at this node
718
880
  if (prefix) {
719
881
  this.nested[prefix.substring(0, prefix.length - 1)] = true;
@@ -728,13 +890,30 @@ Schema.prototype.add = function add(obj, prefix) {
728
890
  } else {
729
891
  // There IS a bona-fide type key that may also be a POJO
730
892
  const _typeDef = val[typeKey];
731
- if (isPOJO(_typeDef) && Object.keys(_typeDef).length > 0) {
893
+ if (isPOJO(_typeDef) && utils.hasOwnKeys(_typeDef)) {
732
894
  // If a POJO is the value of a type key, make it a subdocument
733
895
  if (prefix) {
734
896
  this.nested[prefix.substring(0, prefix.length - 1)] = true;
735
897
  }
736
- const _schema = new Schema(_typeDef);
737
- const schemaWrappedPath = Object.assign({}, val, { type: _schema });
898
+
899
+ const childSchemaOptions = {};
900
+ if (this._userProvidedOptions.typeKey) {
901
+ childSchemaOptions.typeKey = this._userProvidedOptions.typeKey;
902
+ }
903
+ // propagate 'strict' option to child schema
904
+ if (this._userProvidedOptions.strict != null) {
905
+ childSchemaOptions.strict = this._userProvidedOptions.strict;
906
+ }
907
+ if (this._userProvidedOptions.toObject != null) {
908
+ childSchemaOptions.toObject = utils.omit(this._userProvidedOptions.toObject, ['transform']);
909
+ }
910
+ if (this._userProvidedOptions.toJSON != null) {
911
+ childSchemaOptions.toJSON = utils.omit(this._userProvidedOptions.toJSON, ['transform']);
912
+ }
913
+
914
+ const _schema = new Schema(_typeDef, childSchemaOptions);
915
+ _schema.$implicitlyCreated = true;
916
+ const schemaWrappedPath = Object.assign({}, val, { [typeKey]: _schema });
738
917
  this.path(prefix + key, schemaWrappedPath);
739
918
  } else {
740
919
  // Either the type is non-POJO or we interpret it as Mixed anyway
@@ -742,7 +921,7 @@ Schema.prototype.add = function add(obj, prefix) {
742
921
  this.nested[prefix.substring(0, prefix.length - 1)] = true;
743
922
  }
744
923
  this.path(prefix + key, val);
745
- if (val != null && !(val.instanceOfSchema) && utils.isPOJO(val.discriminators)) {
924
+ if (!val?.instanceOfSchema && utils.isPOJO(val?.discriminators)) {
746
925
  const schemaType = this.path(prefix + key);
747
926
  for (const key in val.discriminators) {
748
927
  schemaType.discriminator(key, val.discriminators[key]);
@@ -750,6 +929,31 @@ Schema.prototype.add = function add(obj, prefix) {
750
929
  }
751
930
  }
752
931
  }
932
+
933
+ if (val.instanceOfSchema && val.encryptionType() != null) {
934
+ // schema.add({ field: <instance of encrypted schema> })
935
+ if (this.encryptionType() != val.encryptionType()) {
936
+ throw new MongooseError('encryptionType of a nested schema must match the encryption type of the parent schema.');
937
+ }
938
+
939
+ for (const [encryptedField, encryptedFieldConfig] of Object.entries(val.encryptedFields)) {
940
+ const path = fullPath + '.' + encryptedField;
941
+ this._addEncryptedField(path, encryptedFieldConfig);
942
+ }
943
+ } else if (typeof val === 'object' && 'encrypt' in val) {
944
+ // schema.add({ field: { type: <schema type>, encrypt: { ... }}})
945
+ const { encrypt } = val;
946
+
947
+ if (this.encryptionType() == null) {
948
+ throw new MongooseError('encryptionType must be provided');
949
+ }
950
+
951
+ this._addEncryptedField(fullPath, encrypt);
952
+ } else {
953
+ // if the field was already encrypted and we re-configure it to be unencrypted, remove
954
+ // the encrypted field configuration
955
+ this._removeEncryptedField(fullPath);
956
+ }
753
957
  }
754
958
 
755
959
  const aliasObj = Object.fromEntries(
@@ -759,6 +963,117 @@ Schema.prototype.add = function add(obj, prefix) {
759
963
  return this;
760
964
  };
761
965
 
966
+ /**
967
+ * @param {string} path
968
+ * @param {object} fieldConfig
969
+ *
970
+ * @api private
971
+ */
972
+ Schema.prototype._addEncryptedField = function _addEncryptedField(path, fieldConfig) {
973
+ const type = this.path(path).autoEncryptionType();
974
+ if (type == null) {
975
+ throw new MongooseError(`Invalid BSON type for FLE field: '${path}'`);
976
+ }
977
+
978
+ this.encryptedFields[path] = clone(fieldConfig);
979
+ };
980
+
981
+ /**
982
+ * @param {string} path
983
+ *
984
+ * @api private
985
+ */
986
+ Schema.prototype._removeEncryptedField = function _removeEncryptedField(path) {
987
+ delete this.encryptedFields[path];
988
+ };
989
+
990
+ /**
991
+ * @api private
992
+ *
993
+ * @returns {boolean}
994
+ */
995
+ Schema.prototype._hasEncryptedFields = function _hasEncryptedFields() {
996
+ return utils.hasOwnKeys(this.encryptedFields);
997
+ };
998
+
999
+ /**
1000
+ * @param {string} path
1001
+ * @returns {boolean}
1002
+ *
1003
+ * @api private
1004
+ */
1005
+ Schema.prototype._hasEncryptedField = function _hasEncryptedField(path) {
1006
+ return path in this.encryptedFields;
1007
+ };
1008
+
1009
+
1010
+ /**
1011
+ * Builds an encryptedFieldsMap for the schema.
1012
+ *
1013
+ * @api private
1014
+ */
1015
+ Schema.prototype._buildEncryptedFields = function() {
1016
+ const fields = Object.entries(this.encryptedFields).map(
1017
+ ([path, config]) => {
1018
+ const bsonType = this.path(path).autoEncryptionType();
1019
+ // { path, bsonType, keyId, queries? }
1020
+ return { path, bsonType, ...config };
1021
+ });
1022
+
1023
+ return { fields };
1024
+ };
1025
+
1026
+ /**
1027
+ * Builds a schemaMap for the schema, if the schema is configured for client-side field level encryption.
1028
+ *
1029
+ * @api private
1030
+ */
1031
+ Schema.prototype._buildSchemaMap = function() {
1032
+ /**
1033
+ * `schemaMap`s are JSON schemas, which use the following structure to represent objects:
1034
+ * { field: { bsonType: 'object', properties: { ... } } }
1035
+ *
1036
+ * for example, a schema that looks like this `{ a: { b: int32 } }` would be encoded as
1037
+ * `{ a: { bsonType: 'object', properties: { b: < encryption configuration > } } }`
1038
+ *
1039
+ * This function takes an array of path segments, an output object (that gets mutated) and
1040
+ * a value to be associated with the full path, and constructs a valid CSFLE JSON schema path for
1041
+ * the object. This works for deeply nested properties as well.
1042
+ *
1043
+ * @param {string[]} path array of path components
1044
+ * @param {object} object the object in which to build a JSON schema of `path`'s properties
1045
+ * @param {object} value the value to associate with the path in object
1046
+ */
1047
+ function buildNestedPath(path, object, value) {
1048
+ let i = 0, component = path[i];
1049
+ for (; i < path.length - 1; ++i, component = path[i]) {
1050
+ object[component] = object[component] == null ? {
1051
+ bsonType: 'object',
1052
+ properties: {}
1053
+ } : object[component];
1054
+ object = object[component].properties;
1055
+ }
1056
+ object[component] = value;
1057
+ }
1058
+
1059
+ const schemaMapPropertyReducer = (accum, [path, propertyConfig]) => {
1060
+ const bsonType = this.path(path).autoEncryptionType();
1061
+ const pathComponents = path.split('.');
1062
+ const configuration = { encrypt: { ...propertyConfig, bsonType } };
1063
+ buildNestedPath(pathComponents, accum, configuration);
1064
+ return accum;
1065
+ };
1066
+
1067
+ const properties = Object.entries(this.encryptedFields).reduce(
1068
+ schemaMapPropertyReducer,
1069
+ {});
1070
+
1071
+ return {
1072
+ bsonType: 'object',
1073
+ properties
1074
+ };
1075
+ };
1076
+
762
1077
  /**
763
1078
  * Add an alias for `path`. This means getting or setting the `alias`
764
1079
  * is equivalent to getting or setting the `path`.
@@ -782,8 +1097,8 @@ Schema.prototype.add = function add(obj, prefix) {
782
1097
  * await turboMan.save(); // Saves { _id: ..., n: 'Turbo Man Action Figure' }
783
1098
  *
784
1099
  *
785
- * @param {String} path real path to alias
786
- * @param {String|String[]} alias the path(s) to use as an alias for `path`
1100
+ * @param {string} path real path to alias
1101
+ * @param {string|string[]} alias the path(s) to use as an alias for `path`
787
1102
  * @return {Schema} the Schema instance
788
1103
  * @api public
789
1104
  */
@@ -815,23 +1130,23 @@ Schema.prototype.alias = function alias(path, alias) {
815
1130
  * // Remove index by name
816
1131
  * ToySchema.removeIndex('my custom index name');
817
1132
  *
818
- * @param {Object|string} index name or index specification
1133
+ * @param {object|string} index name or index specification
819
1134
  * @return {Schema} the Schema instance
820
1135
  * @api public
821
1136
  */
822
1137
 
823
1138
  Schema.prototype.removeIndex = function removeIndex(index) {
824
1139
  if (arguments.length > 1) {
825
- throw new Error('removeIndex() takes only 1 argument');
1140
+ throw new MongooseError('removeIndex() takes only 1 argument');
826
1141
  }
827
1142
 
828
1143
  if (typeof index !== 'object' && typeof index !== 'string') {
829
- throw new Error('removeIndex() may only take either an object or a string as an argument');
1144
+ throw new MongooseError('removeIndex() may only take either an object or a string as an argument');
830
1145
  }
831
1146
 
832
1147
  if (typeof index === 'object') {
833
1148
  for (let i = this._indexes.length - 1; i >= 0; --i) {
834
- if (util.isDeepStrictEqual(this._indexes[i][0], index)) {
1149
+ if (isIndexSpecEqual(this._indexes[i][0], index)) {
835
1150
  this._indexes.splice(i, 1);
836
1151
  }
837
1152
  }
@@ -873,6 +1188,28 @@ Schema.prototype.clearIndexes = function clearIndexes() {
873
1188
  return this;
874
1189
  };
875
1190
 
1191
+ /**
1192
+ * Add an [Atlas search index](https://www.mongodb.com/docs/atlas/atlas-search/create-index/) that Mongoose will create using `Model.createSearchIndex()`.
1193
+ * This function only works when connected to MongoDB Atlas.
1194
+ *
1195
+ * #### Example:
1196
+ *
1197
+ * const ToySchema = new Schema({ name: String, color: String, price: Number });
1198
+ * ToySchema.searchIndex({ name: 'test', definition: { mappings: { dynamic: true } } });
1199
+ *
1200
+ * @param {object} description index options, including `name` and `definition`
1201
+ * @param {string} description.name
1202
+ * @param {object} description.definition
1203
+ * @return {Schema} the Schema instance
1204
+ * @api public
1205
+ */
1206
+
1207
+ Schema.prototype.searchIndex = function searchIndex(description) {
1208
+ this._searchIndexes.push(description);
1209
+
1210
+ return this;
1211
+ };
1212
+
876
1213
  /**
877
1214
  * Reserved document keys.
878
1215
  *
@@ -948,14 +1285,14 @@ reserved.collection = 1;
948
1285
  * schema.path('name') // returns a SchemaType
949
1286
  * schema.path('name', Number) // changes the schemaType of `name` to Number
950
1287
  *
951
- * @param {String} path The name of the Path to get / set
952
- * @param {Object} [obj] The Type to set the path to, if provided the path will be SET, otherwise the path will be GET
1288
+ * @param {string} path The name of the Path to get / set
1289
+ * @param {object} [obj] The Type to set the path to, if provided the path will be SET, otherwise the path will be GET
953
1290
  * @api public
954
1291
  */
955
1292
 
956
1293
  Schema.prototype.path = function(path, obj) {
957
1294
  if (obj === undefined) {
958
- if (Object.prototype.hasOwnProperty.call(this.paths, path)) {
1295
+ if (Object.hasOwn(this.paths, path)) {
959
1296
  return this.paths[path];
960
1297
  }
961
1298
  // Convert to '.$' to check subpaths re: gh-6405
@@ -979,22 +1316,22 @@ Schema.prototype.path = function(path, obj) {
979
1316
 
980
1317
  // subpaths?
981
1318
  return hasNumericSubpathRegex.test(path)
982
- ? getPositionalPath(this, path)
1319
+ ? getPositionalPath(this, path, cleanPath)
983
1320
  : undefined;
984
1321
  }
985
1322
 
986
1323
  const subpaths = path.indexOf('.') === -1 ? [path] : path.split('.');
987
1324
  const last = subpaths.pop();
988
1325
  if (utils.specialProperties.has(last)) {
989
- throw new Error('Cannot set special property `' + last + '` on a schema');
1326
+ throw new MongooseError('Cannot set special property `' + last + '` on a schema');
990
1327
  }
991
1328
 
992
1329
  // some path names conflict with document methods
993
1330
  const firstPieceOfPath = subpaths.length === 0 ? last : subpaths[0];
994
- if (Object.prototype.hasOwnProperty.call(reserved, firstPieceOfPath) && !this.options.supressReservedKeysWarning) {
1331
+ if (Object.hasOwn(reserved, firstPieceOfPath) && !this.options.suppressReservedKeysWarning) {
995
1332
  const errorMessage = `\`${firstPieceOfPath}\` is a reserved schema pathname and may break some functionality. ` +
996
1333
  'You are allowed to use it, but use at your own risk. ' +
997
- 'To disable this warning pass `supressReservedKeysWarning` as a schema option.';
1334
+ 'To disable this warning pass `suppressReservedKeysWarning` as a schema option.';
998
1335
 
999
1336
  utils.warn(errorMessage);
1000
1337
  }
@@ -1009,7 +1346,7 @@ Schema.prototype.path = function(path, obj) {
1009
1346
 
1010
1347
  for (const sub of subpaths) {
1011
1348
  if (utils.specialProperties.has(sub)) {
1012
- throw new Error('Cannot set special property `' + sub + '` on a schema');
1349
+ throw new MongooseError('Cannot set special property `' + sub + '` on a schema');
1013
1350
  }
1014
1351
  fullPath = fullPath += (fullPath.length > 0 ? '.' : '') + sub;
1015
1352
  if (!branch[sub]) {
@@ -1022,16 +1359,21 @@ Schema.prototype.path = function(path, obj) {
1022
1359
  + fullPath
1023
1360
  + '` already set to type ' + branch[sub].name
1024
1361
  + '.';
1025
- throw new Error(msg);
1362
+ throw new MongooseError(msg);
1026
1363
  }
1027
1364
  branch = branch[sub];
1028
1365
  }
1029
1366
 
1030
- branch[last] = utils.clone(obj);
1367
+ branch[last] = clone(obj);
1031
1368
 
1032
1369
  this.paths[path] = this.interpretAsType(path, obj, this.options);
1370
+ this._defaultsCache = null;
1371
+ this._hasSelectedPaths = undefined;
1033
1372
  const schemaType = this.paths[path];
1034
1373
 
1374
+ // If overwriting an existing path, make sure to clear the childSchemas
1375
+ this.childSchemas = this.childSchemas.filter(childSchema => childSchema.path !== path);
1376
+
1035
1377
  if (schemaType.$isSchemaMap) {
1036
1378
  // Maps can have arbitrary keys, so `$*` is internal shorthand for "any key"
1037
1379
  // The '$' is to imply this path should never be stored in MongoDB so we
@@ -1040,6 +1382,13 @@ Schema.prototype.path = function(path, obj) {
1040
1382
 
1041
1383
  this.paths[mapPath] = schemaType.$__schemaType;
1042
1384
  this.mapPaths.push(this.paths[mapPath]);
1385
+ if (schemaType.$__schemaType.$isSingleNested) {
1386
+ this.childSchemas.push({
1387
+ schema: schemaType.$__schemaType.schema,
1388
+ model: schemaType.$__schemaType.Constructor,
1389
+ path: path
1390
+ });
1391
+ }
1043
1392
  }
1044
1393
 
1045
1394
  if (schemaType.$isSingleNested) {
@@ -1065,10 +1414,11 @@ Schema.prototype.path = function(path, obj) {
1065
1414
  value: this.base
1066
1415
  });
1067
1416
 
1068
- schemaType.caster.base = this.base;
1417
+ schemaType.Constructor.base = this.base;
1069
1418
  this.childSchemas.push({
1070
1419
  schema: schemaType.schema,
1071
- model: schemaType.caster
1420
+ model: schemaType.Constructor,
1421
+ path: path
1072
1422
  });
1073
1423
  } else if (schemaType.$isMongooseDocumentArray) {
1074
1424
  Object.defineProperty(schemaType.schema, 'base', {
@@ -1078,14 +1428,15 @@ Schema.prototype.path = function(path, obj) {
1078
1428
  value: this.base
1079
1429
  });
1080
1430
 
1081
- schemaType.casterConstructor.base = this.base;
1431
+ schemaType.Constructor.base = this.base;
1082
1432
  this.childSchemas.push({
1083
1433
  schema: schemaType.schema,
1084
- model: schemaType.casterConstructor
1434
+ model: schemaType.Constructor,
1435
+ path: path
1085
1436
  });
1086
1437
  }
1087
1438
 
1088
- if (schemaType.$isMongooseArray && schemaType.caster instanceof SchemaType) {
1439
+ if (schemaType.$isMongooseArray && !schemaType.$isMongooseDocumentArray) {
1089
1440
  let arrayPath = path;
1090
1441
  let _schemaType = schemaType;
1091
1442
 
@@ -1093,19 +1444,11 @@ Schema.prototype.path = function(path, obj) {
1093
1444
  while (_schemaType.$isMongooseArray) {
1094
1445
  arrayPath = arrayPath + '.$';
1095
1446
 
1096
- // Skip arrays of document arrays
1097
- if (_schemaType.$isMongooseDocumentArray) {
1098
- _schemaType.$embeddedSchemaType._arrayPath = arrayPath;
1099
- _schemaType.$embeddedSchemaType._arrayParentPath = path;
1100
- _schemaType = _schemaType.$embeddedSchemaType.clone();
1101
- } else {
1102
- _schemaType.caster._arrayPath = arrayPath;
1103
- _schemaType.caster._arrayParentPath = path;
1104
- _schemaType = _schemaType.caster.clone();
1105
- }
1447
+ _schemaType.embeddedSchemaType._arrayPath = arrayPath;
1448
+ _schemaType.embeddedSchemaType._arrayParentPath = path;
1449
+ _schemaType = _schemaType.embeddedSchemaType;
1106
1450
 
1107
- _schemaType.path = arrayPath;
1108
- toAdd.push(_schemaType);
1451
+ this.subpaths[arrayPath] = _schemaType;
1109
1452
  }
1110
1453
 
1111
1454
  for (const _schemaType of toAdd) {
@@ -1117,22 +1460,22 @@ Schema.prototype.path = function(path, obj) {
1117
1460
  for (const key of Object.keys(schemaType.schema.paths)) {
1118
1461
  const _schemaType = schemaType.schema.paths[key];
1119
1462
  this.subpaths[path + '.' + key] = _schemaType;
1120
- if (typeof _schemaType === 'object' && _schemaType != null) {
1121
- _schemaType.$isUnderneathDocArray = true;
1463
+ if (typeof _schemaType === 'object' && _schemaType != null && _schemaType.$parentSchemaDocArray == null) {
1464
+ _schemaType.$parentSchemaDocArray = schemaType;
1122
1465
  }
1123
1466
  }
1124
1467
  for (const key of Object.keys(schemaType.schema.subpaths)) {
1125
1468
  const _schemaType = schemaType.schema.subpaths[key];
1126
1469
  this.subpaths[path + '.' + key] = _schemaType;
1127
- if (typeof _schemaType === 'object' && _schemaType != null) {
1128
- _schemaType.$isUnderneathDocArray = true;
1470
+ if (typeof _schemaType === 'object' && _schemaType != null && _schemaType.$parentSchemaDocArray == null) {
1471
+ _schemaType.$parentSchemaDocArray = schemaType;
1129
1472
  }
1130
1473
  }
1131
1474
  for (const key of Object.keys(schemaType.schema.singleNestedPaths)) {
1132
1475
  const _schemaType = schemaType.schema.singleNestedPaths[key];
1133
1476
  this.subpaths[path + '.' + key] = _schemaType;
1134
- if (typeof _schemaType === 'object' && _schemaType != null) {
1135
- _schemaType.$isUnderneathDocArray = true;
1477
+ if (typeof _schemaType === 'object' && _schemaType != null && _schemaType.$parentSchemaDocArray == null) {
1478
+ _schemaType.$parentSchemaDocArray = schemaType;
1136
1479
  }
1137
1480
  }
1138
1481
  }
@@ -1144,32 +1487,54 @@ Schema.prototype.path = function(path, obj) {
1144
1487
  * ignore
1145
1488
  */
1146
1489
 
1147
- function gatherChildSchemas(schema) {
1490
+ Schema.prototype._gatherChildSchemas = function _gatherChildSchemas() {
1148
1491
  const childSchemas = [];
1149
1492
 
1150
- for (const path of Object.keys(schema.paths)) {
1151
- const schematype = schema.paths[path];
1493
+ for (const path of Object.keys(this.paths)) {
1494
+ if (typeof path !== 'string') {
1495
+ continue;
1496
+ }
1497
+ const schematype = this.paths[path];
1152
1498
  if (schematype.$isMongooseDocumentArray || schematype.$isSingleNested) {
1153
- childSchemas.push({ schema: schematype.schema, model: schematype.caster });
1499
+ childSchemas.push({
1500
+ schema: schematype.schema,
1501
+ model: schematype.Constructor,
1502
+ path: path
1503
+ });
1504
+ } else if (schematype.$isSchemaMap && schematype.$__schemaType.$isSingleNested) {
1505
+ childSchemas.push({
1506
+ schema: schematype.$__schemaType.schema,
1507
+ model: schematype.$__schemaType.Constructor,
1508
+ path: path
1509
+ });
1154
1510
  }
1155
1511
  }
1156
1512
 
1513
+ this.childSchemas = childSchemas;
1157
1514
  return childSchemas;
1158
- }
1515
+ };
1159
1516
 
1160
1517
  /*!
1161
1518
  * ignore
1162
1519
  */
1163
1520
 
1164
1521
  function _getPath(schema, path, cleanPath) {
1165
- if (schema.paths.hasOwnProperty(path)) {
1522
+ if (Object.hasOwn(schema.paths, path)) {
1166
1523
  return schema.paths[path];
1167
1524
  }
1168
- if (schema.subpaths.hasOwnProperty(cleanPath)) {
1169
- return schema.subpaths[cleanPath];
1525
+ if (Object.hasOwn(schema.subpaths, cleanPath)) {
1526
+ const subpath = schema.subpaths[cleanPath];
1527
+ if (subpath === 'nested') {
1528
+ return undefined;
1529
+ }
1530
+ return subpath;
1170
1531
  }
1171
- if (schema.singleNestedPaths.hasOwnProperty(cleanPath) && typeof schema.singleNestedPaths[cleanPath] === 'object') {
1172
- return schema.singleNestedPaths[cleanPath];
1532
+ if (Object.hasOwn(schema.singleNestedPaths, cleanPath) && typeof schema.singleNestedPaths[cleanPath] === 'object') {
1533
+ const singleNestedPath = schema.singleNestedPaths[cleanPath];
1534
+ if (singleNestedPath === 'nested') {
1535
+ return undefined;
1536
+ }
1537
+ return singleNestedPath;
1173
1538
  }
1174
1539
 
1175
1540
  return null;
@@ -1195,10 +1560,24 @@ function getMapPath(schema, path) {
1195
1560
  return null;
1196
1561
  }
1197
1562
  for (const val of schema.mapPaths) {
1198
- const _path = val.path;
1199
- const re = new RegExp('^' + _path.replace(/\.\$\*/g, '\\.[^.]+') + '$');
1200
- if (re.test(path)) {
1201
- return schema.paths[_path];
1563
+ const cleanPath = val.path.replace(/\.\$\*/g, '');
1564
+ if (path === cleanPath || (path.startsWith(cleanPath + '.') && path.slice(cleanPath.length + 1).indexOf('.') === -1)) {
1565
+ return val;
1566
+ } else if (val.schema && path.startsWith(cleanPath + '.')) {
1567
+ let remnant = path.slice(cleanPath.length + 1);
1568
+ remnant = remnant.slice(remnant.indexOf('.') + 1);
1569
+ return val.schema.path(remnant);
1570
+ } else if (val.$isSchemaMap && path.startsWith(cleanPath + '.')) {
1571
+ let remnant = path.slice(cleanPath.length + 1);
1572
+ remnant = remnant.slice(remnant.indexOf('.') + 1);
1573
+ const presplitPath = val.$__schemaType._presplitPath;
1574
+ if (remnant.indexOf('.') === -1 && presplitPath[presplitPath.length - 1] === '$*') {
1575
+ // Handle map of map of primitives
1576
+ return val.$__schemaType;
1577
+ } else if (remnant.indexOf('.') !== -1 && val.$__schemaType.schema && presplitPath[presplitPath.length - 1] === '$*') {
1578
+ // map of map of subdocs (recursive)
1579
+ return val.$__schemaType.schema.path(remnant.slice(remnant.indexOf('.') + 1));
1580
+ }
1202
1581
  }
1203
1582
  }
1204
1583
 
@@ -1222,9 +1601,9 @@ Object.defineProperty(Schema.prototype, 'base', {
1222
1601
  /**
1223
1602
  * Converts type arguments into Mongoose Types.
1224
1603
  *
1225
- * @param {String} path
1226
- * @param {Object} obj constructor
1227
- * @param {Object} options
1604
+ * @param {string} path
1605
+ * @param {object} obj constructor
1606
+ * @param {object} options schema options
1228
1607
  * @api private
1229
1608
  */
1230
1609
 
@@ -1240,8 +1619,8 @@ Schema.prototype.interpretAsType = function(path, obj, options) {
1240
1619
 
1241
1620
  // If this schema has an associated Mongoose object, use the Mongoose object's
1242
1621
  // copy of SchemaTypes re: gh-7158 gh-6933
1243
- const MongooseTypes = this.base != null ? this.base.Schema.Types : Schema.Types;
1244
- const Types = this.base != null ? this.base.Types : require('./types');
1622
+ const MongooseTypes = this.base?.Schema.Types ?? Schema.Types;
1623
+ const Types = this.base?.Types ?? require('./types');
1245
1624
 
1246
1625
  if (!utils.isPOJO(obj) && !(obj instanceof SchemaTypeOptions)) {
1247
1626
  const constructorName = utils.getFunctionName(obj.constructor);
@@ -1258,10 +1637,20 @@ Schema.prototype.interpretAsType = function(path, obj, options) {
1258
1637
  let type = obj[options.typeKey] && (obj[options.typeKey] instanceof Function || options.typeKey !== 'type' || !obj.type.type)
1259
1638
  ? obj[options.typeKey]
1260
1639
  : {};
1640
+
1641
+ if (type instanceof SchemaType) {
1642
+ if (type.path === path) {
1643
+ return type;
1644
+ }
1645
+ const clone = type.clone();
1646
+ clone.path = path;
1647
+ return clone;
1648
+ }
1649
+
1261
1650
  let name;
1262
1651
 
1263
1652
  if (utils.isPOJO(type) || type === 'mixed') {
1264
- return new MongooseTypes.Mixed(path, obj);
1653
+ return new MongooseTypes.Mixed(path, obj, null, this);
1265
1654
  }
1266
1655
 
1267
1656
  if (Array.isArray(type) || type === Array || type === 'array' || type === MongooseTypes.Array) {
@@ -1271,33 +1660,45 @@ Schema.prototype.interpretAsType = function(path, obj, options) {
1271
1660
  : type[0];
1272
1661
 
1273
1662
  // new Schema({ path: [new Schema({ ... })] })
1274
- if (cast && cast.instanceOfSchema) {
1663
+ if (cast?.instanceOfSchema) {
1275
1664
  if (!(cast instanceof Schema)) {
1276
- throw new TypeError('Schema for array path `' + path +
1277
- '` is from a different copy of the Mongoose module. ' +
1278
- 'Please make sure you\'re using the same version ' +
1279
- 'of Mongoose everywhere with `npm list mongoose`. If you are still ' +
1280
- 'getting this error, please add `new Schema()` around the path: ' +
1281
- `${path}: new Schema(...)`);
1665
+ if (this.options._isMerging) {
1666
+ cast = new Schema(cast);
1667
+ } else {
1668
+ throw new TypeError('Schema for array path `' + path +
1669
+ '` is from a different copy of the Mongoose module. ' +
1670
+ 'Please make sure you\'re using the same version ' +
1671
+ 'of Mongoose everywhere with `npm list mongoose`. If you are still ' +
1672
+ 'getting this error, please add `new Schema()` around the path: ' +
1673
+ `${path}: new Schema(...)`);
1674
+ }
1282
1675
  }
1283
- return new MongooseTypes.DocumentArray(path, cast, obj);
1676
+ return new MongooseTypes.DocumentArray(path, cast, obj, null, this);
1284
1677
  }
1285
1678
  if (cast &&
1286
1679
  cast[options.typeKey] &&
1287
1680
  cast[options.typeKey].instanceOfSchema) {
1288
1681
  if (!(cast[options.typeKey] instanceof Schema)) {
1289
- throw new TypeError('Schema for array path `' + path +
1290
- '` is from a different copy of the Mongoose module. ' +
1291
- 'Please make sure you\'re using the same version ' +
1292
- 'of Mongoose everywhere with `npm list mongoose`. If you are still ' +
1293
- 'getting this error, please add `new Schema()` around the path: ' +
1294
- `${path}: new Schema(...)`);
1682
+ if (this.options._isMerging) {
1683
+ cast[options.typeKey] = new Schema(cast[options.typeKey]);
1684
+ } else {
1685
+ throw new TypeError('Schema for array path `' + path +
1686
+ '` is from a different copy of the Mongoose module. ' +
1687
+ 'Please make sure you\'re using the same version ' +
1688
+ 'of Mongoose everywhere with `npm list mongoose`. If you are still ' +
1689
+ 'getting this error, please add `new Schema()` around the path: ' +
1690
+ `${path}: new Schema(...)`);
1691
+ }
1295
1692
  }
1296
- return new MongooseTypes.DocumentArray(path, cast[options.typeKey], obj, cast);
1693
+ return new MongooseTypes.DocumentArray(path, cast[options.typeKey], obj, cast, this);
1297
1694
  }
1298
-
1299
- if (Array.isArray(cast)) {
1300
- return new MongooseTypes.Array(path, this.interpretAsType(path, cast, options), obj);
1695
+ if (typeof cast !== 'undefined') {
1696
+ if (Array.isArray(cast) || cast.type === Array || cast.type == 'Array') {
1697
+ if (cast?.type == 'Array') {
1698
+ cast.type = Array;
1699
+ }
1700
+ return new MongooseTypes.Array(path, this.interpretAsType(path, cast, options), obj, null, this);
1701
+ }
1301
1702
  }
1302
1703
 
1303
1704
  // Handle both `new Schema({ arr: [{ subpath: String }] })` and `new Schema({ arr: [{ type: { subpath: string } }] })`
@@ -1307,7 +1708,7 @@ Schema.prototype.interpretAsType = function(path, obj, options) {
1307
1708
  if (typeof cast === 'string') {
1308
1709
  cast = MongooseTypes[cast.charAt(0).toUpperCase() + cast.substring(1)];
1309
1710
  } else if (utils.isPOJO(castFromTypeKey)) {
1310
- if (Object.keys(castFromTypeKey).length) {
1711
+ if (utils.hasOwnKeys(castFromTypeKey)) {
1311
1712
  // The `minimize` and `typeKey` options propagate to child schemas
1312
1713
  // declared inline, like `{ arr: [{ val: { $type: String } }] }`.
1313
1714
  // See gh-3560
@@ -1316,24 +1717,31 @@ Schema.prototype.interpretAsType = function(path, obj, options) {
1316
1717
  childSchemaOptions.typeKey = options.typeKey;
1317
1718
  }
1318
1719
  // propagate 'strict' option to child schema
1319
- if (options.hasOwnProperty('strict')) {
1720
+ if (Object.hasOwn(options, 'strict')) {
1320
1721
  childSchemaOptions.strict = options.strict;
1321
1722
  }
1322
- if (options.hasOwnProperty('strictQuery')) {
1723
+ if (Object.hasOwn(options, 'strictQuery')) {
1323
1724
  childSchemaOptions.strictQuery = options.strictQuery;
1324
1725
  }
1726
+ if (Object.hasOwn(options, 'toObject')) {
1727
+ childSchemaOptions.toObject = utils.omit(options.toObject, ['transform']);
1728
+ }
1729
+ if (Object.hasOwn(options, 'toJSON')) {
1730
+ childSchemaOptions.toJSON = utils.omit(options.toJSON, ['transform']);
1731
+ }
1325
1732
 
1326
- if (this._userProvidedOptions.hasOwnProperty('_id')) {
1733
+ if (Object.hasOwn(this._userProvidedOptions, '_id')) {
1327
1734
  childSchemaOptions._id = this._userProvidedOptions._id;
1328
1735
  } else if (Schema.Types.DocumentArray.defaultOptions._id != null) {
1329
1736
  childSchemaOptions._id = Schema.Types.DocumentArray.defaultOptions._id;
1330
1737
  }
1738
+
1331
1739
  const childSchema = new Schema(castFromTypeKey, childSchemaOptions);
1332
1740
  childSchema.$implicitlyCreated = true;
1333
- return new MongooseTypes.DocumentArray(path, childSchema, obj);
1741
+ return new MongooseTypes.DocumentArray(path, childSchema, obj, null, this);
1334
1742
  } else {
1335
1743
  // Special case: empty object becomes mixed
1336
- return new MongooseTypes.Array(path, MongooseTypes.Mixed, obj);
1744
+ return new MongooseTypes.Array(path, MongooseTypes.Mixed, obj, null, this);
1337
1745
  }
1338
1746
  }
1339
1747
 
@@ -1341,9 +1749,10 @@ Schema.prototype.interpretAsType = function(path, obj, options) {
1341
1749
  type = cast[options.typeKey] && (options.typeKey !== 'type' || !cast.type.type)
1342
1750
  ? cast[options.typeKey]
1343
1751
  : cast;
1344
-
1345
1752
  if (Array.isArray(type)) {
1346
- return new MongooseTypes.Array(path, this.interpretAsType(path, type, options), obj);
1753
+ // Pass `cast` rather than `type` so options on a nested array, like
1754
+ // `[{ type: [Number], castNonArrays: false }]`, aren't dropped.
1755
+ return new MongooseTypes.Array(path, this.interpretAsType(path, cast, options), obj, null, this);
1347
1756
  }
1348
1757
 
1349
1758
  name = typeof type === 'string'
@@ -1360,19 +1769,22 @@ Schema.prototype.interpretAsType = function(path, obj, options) {
1360
1769
  `Could not determine the embedded type for array \`${path}\`. ` +
1361
1770
  'See https://mongoosejs.com/docs/guide.html#definition for more info on supported schema syntaxes.');
1362
1771
  }
1363
- if (!MongooseTypes.hasOwnProperty(name)) {
1772
+ if (!Object.hasOwn(MongooseTypes, name)) {
1364
1773
  throw new TypeError('Invalid schema configuration: ' +
1365
1774
  `\`${name}\` is not a valid type within the array \`${path}\`.` +
1366
1775
  'See https://bit.ly/mongoose-schematypes for a list of valid schema types.');
1367
1776
  }
1777
+
1778
+ if (name === 'Union' && typeof cast === 'object') {
1779
+ cast.parentSchema = this;
1780
+ }
1368
1781
  }
1369
1782
 
1370
- return new MongooseTypes.Array(path, cast || MongooseTypes.Mixed, obj, options);
1783
+ return new MongooseTypes.Array(path, cast || MongooseTypes.Mixed, obj, options, this);
1371
1784
  }
1372
1785
 
1373
- if (type && type.instanceOfSchema) {
1374
-
1375
- return new MongooseTypes.Subdocument(type, path, obj);
1786
+ if (type?.instanceOfSchema) {
1787
+ return new MongooseTypes.Subdocument(type, path, obj, this);
1376
1788
  }
1377
1789
 
1378
1790
  if (Buffer.isBuffer(type)) {
@@ -1411,50 +1823,11 @@ Schema.prototype.interpretAsType = function(path, obj, options) {
1411
1823
  'https://bit.ly/mongoose-schematypes for a list of valid schema types.');
1412
1824
  }
1413
1825
 
1414
- const schemaType = new MongooseTypes[name](path, obj);
1415
-
1416
- if (schemaType.$isSchemaMap) {
1417
- createMapNestedSchemaType(this, schemaType, path, obj, options);
1418
- }
1826
+ const schemaType = new MongooseTypes[name](path, obj, options, this);
1419
1827
 
1420
1828
  return schemaType;
1421
1829
  };
1422
1830
 
1423
- /*!
1424
- * ignore
1425
- */
1426
-
1427
- function createMapNestedSchemaType(schema, schemaType, path, obj, options) {
1428
- const mapPath = path + '.$*';
1429
- let _mapType = { type: {} };
1430
- if (utils.hasUserDefinedProperty(obj, 'of')) {
1431
- const isInlineSchema = utils.isPOJO(obj.of) &&
1432
- Object.keys(obj.of).length > 0 &&
1433
- !utils.hasUserDefinedProperty(obj.of, schema.options.typeKey);
1434
- if (isInlineSchema) {
1435
- _mapType = { [schema.options.typeKey]: new Schema(obj.of) };
1436
- } else if (utils.isPOJO(obj.of)) {
1437
- _mapType = Object.assign({}, obj.of);
1438
- } else {
1439
- _mapType = { [schema.options.typeKey]: obj.of };
1440
- }
1441
-
1442
- if (_mapType[schema.options.typeKey] && _mapType[schema.options.typeKey].instanceOfSchema) {
1443
- const subdocumentSchema = _mapType[schema.options.typeKey];
1444
- subdocumentSchema.eachPath((subpath, type) => {
1445
- if (type.options.select === true || type.options.select === false) {
1446
- throw new MongooseError('Cannot use schema-level projections (`select: true` or `select: false`) within maps at path "' + path + '.' + subpath + '"');
1447
- }
1448
- });
1449
- }
1450
-
1451
- if (utils.hasUserDefinedProperty(obj, 'ref')) {
1452
- _mapType.ref = obj.ref;
1453
- }
1454
- }
1455
- schemaType.$__schemaType = schema.interpretAsType(mapPath, _mapType, options);
1456
- }
1457
-
1458
1831
  /**
1459
1832
  * Iterates the schemas paths similar to Array#forEach.
1460
1833
  *
@@ -1499,7 +1872,7 @@ Schema.prototype.eachPath = function(fn) {
1499
1872
  * s.requiredPaths(); // [ 'age', 'name' ]
1500
1873
  *
1501
1874
  * @api public
1502
- * @param {Boolean} invalidate Refresh the cache
1875
+ * @param {boolean} invalidate Refresh the cache
1503
1876
  * @return {Array}
1504
1877
  */
1505
1878
 
@@ -1522,6 +1895,64 @@ Schema.prototype.requiredPaths = function requiredPaths(invalidate) {
1522
1895
  return this._requiredpaths;
1523
1896
  };
1524
1897
 
1898
+ /**
1899
+ * Returns an Array of path strings that have a `transform` option, either on the
1900
+ * path itself or on the path's `embeddedSchemaType` for arrays.
1901
+ *
1902
+ * #### Example:
1903
+ *
1904
+ * const s = new Schema({
1905
+ * name: { type: String, transform: v => v.toLowerCase() },
1906
+ * tags: [{ type: String, transform: v => v.trim() }],
1907
+ * age: { type: Number, required: true },
1908
+ * notes: String
1909
+ * });
1910
+ * s.pathsWithTransforms(); // [ 'name', 'tags' ]
1911
+ *
1912
+ * @api private
1913
+ * @param {boolean} invalidate Refresh the cache
1914
+ * @return {Array|null}
1915
+ */
1916
+
1917
+ Schema.prototype.pathsWithTransforms = function pathsWithTransforms(invalidate) {
1918
+ if (this._pathsWithTransforms !== undefined && !invalidate) {
1919
+ return this._pathsWithTransforms;
1920
+ }
1921
+
1922
+ const paths = Object.keys(this.paths);
1923
+ const ret = [];
1924
+
1925
+ for (const path of paths) {
1926
+ const schematype = this.paths[path];
1927
+ const topLevelTransformFunction = schematype.options.transform ?? schematype.constructor?.defaultOptions?.transform;
1928
+ const embeddedSchemaTypeTransformFunction = schematype.embeddedSchemaType?.options?.transform
1929
+ ?? schematype.embeddedSchemaType?.constructor?.defaultOptions?.transform;
1930
+ if (topLevelTransformFunction || embeddedSchemaTypeTransformFunction) {
1931
+ ret.push(path);
1932
+ }
1933
+ }
1934
+ this._pathsWithTransforms = ret.length ? ret : null;
1935
+ return this._pathsWithTransforms;
1936
+ };
1937
+
1938
+ /**
1939
+ * Returns a `SchemaDefaultsCache` with the paths in this schema that have a default,
1940
+ * both for the whole schema and grouped by nested path. This lets `applyDefaults()`
1941
+ * and setting nested paths skip iterating over every path in the schema for every
1942
+ * document. Computed when the first document is created, and cleared when
1943
+ * compiling or recompiling a model that uses this schema or if paths are added or removed.
1944
+ *
1945
+ * @api private
1946
+ * @return {SchemaDefaultsCache}
1947
+ */
1948
+
1949
+ Schema.prototype._getDefaultsCache = function _getDefaultsCache() {
1950
+ if (this._defaultsCache == null) {
1951
+ this._defaultsCache = new SchemaDefaultsCache(this);
1952
+ }
1953
+ return this._defaultsCache;
1954
+ };
1955
+
1525
1956
  /**
1526
1957
  * Returns indexes from fields and schema-level indexes (cached).
1527
1958
  *
@@ -1551,30 +1982,30 @@ Schema.prototype.indexedPaths = function indexedPaths() {
1551
1982
  * s.pathType('foo'); // "virtual"
1552
1983
  * s.pathType('fail'); // "adhocOrUndefined"
1553
1984
  *
1554
- * @param {String} path
1555
- * @return {String}
1985
+ * @param {string} path
1986
+ * @return {string}
1556
1987
  * @api public
1557
1988
  */
1558
1989
 
1559
1990
  Schema.prototype.pathType = function(path) {
1560
- if (this.paths.hasOwnProperty(path)) {
1991
+ if (Object.hasOwn(this.paths, path)) {
1561
1992
  return 'real';
1562
1993
  }
1563
- if (this.virtuals.hasOwnProperty(path)) {
1994
+ if (Object.hasOwn(this.virtuals, path)) {
1564
1995
  return 'virtual';
1565
1996
  }
1566
- if (this.nested.hasOwnProperty(path)) {
1997
+ if (Object.hasOwn(this.nested, path)) {
1567
1998
  return 'nested';
1568
1999
  }
1569
2000
 
1570
2001
  // Convert to '.$' to check subpaths re: gh-6405
1571
2002
  const cleanPath = _pathToPositionalSyntax(path);
1572
2003
 
1573
- if (this.subpaths.hasOwnProperty(cleanPath) || this.subpaths.hasOwnProperty(path)) {
2004
+ if (Object.hasOwn(this.subpaths, cleanPath) || Object.hasOwn(this.subpaths, path)) {
1574
2005
  return 'real';
1575
2006
  }
1576
2007
 
1577
- const singleNestedPath = this.singleNestedPaths.hasOwnProperty(cleanPath) || this.singleNestedPaths.hasOwnProperty(path);
2008
+ const singleNestedPath = Object.hasOwn(this.singleNestedPaths, cleanPath) || Object.hasOwn(this.singleNestedPaths, path);
1578
2009
  if (singleNestedPath) {
1579
2010
  return singleNestedPath === 'nested' ? 'nested' : 'real';
1580
2011
  }
@@ -1586,7 +2017,7 @@ Schema.prototype.pathType = function(path) {
1586
2017
  }
1587
2018
 
1588
2019
  if (/\.\d+\.|\.\d+$/.test(path)) {
1589
- return getPositionalPathType(this, path);
2020
+ return getPositionalPathType(this, path, cleanPath);
1590
2021
  }
1591
2022
  return 'adhocOrUndefined';
1592
2023
  };
@@ -1594,8 +2025,8 @@ Schema.prototype.pathType = function(path) {
1594
2025
  /**
1595
2026
  * Returns true iff this path is a child of a mixed schema.
1596
2027
  *
1597
- * @param {String} path
1598
- * @return {Boolean}
2028
+ * @param {string} path
2029
+ * @return {boolean}
1599
2030
  * @api private
1600
2031
  */
1601
2032
 
@@ -1604,7 +2035,7 @@ Schema.prototype.hasMixedParent = function(path) {
1604
2035
  path = '';
1605
2036
  for (let i = 0; i < subpaths.length; ++i) {
1606
2037
  path = i > 0 ? path + '.' + subpaths[i] : subpaths[i];
1607
- if (this.paths.hasOwnProperty(path) &&
2038
+ if (Object.hasOwn(this.paths, path) &&
1608
2039
  this.paths[path] instanceof MongooseTypes.Mixed) {
1609
2040
  return this.paths[path];
1610
2041
  }
@@ -1616,7 +2047,7 @@ Schema.prototype.hasMixedParent = function(path) {
1616
2047
  /**
1617
2048
  * Setup updatedAt and createdAt timestamps to documents if enabled
1618
2049
  *
1619
- * @param {Boolean|Object} timestamps timestamps options
2050
+ * @param {boolean|object} timestamps timestamps options
1620
2051
  * @api private
1621
2052
  */
1622
2053
  Schema.prototype.setupTimestamp = function(timestamps) {
@@ -1625,15 +2056,15 @@ Schema.prototype.setupTimestamp = function(timestamps) {
1625
2056
 
1626
2057
  /**
1627
2058
  * ignore. Deprecated re: #6405
1628
- * @param {Any} self
1629
- * @param {String} path
2059
+ * @param {any} self
2060
+ * @param {string} path
1630
2061
  * @api private
1631
2062
  */
1632
2063
 
1633
- function getPositionalPathType(self, path) {
2064
+ function getPositionalPathType(self, path, cleanPath) {
1634
2065
  const subpaths = path.split(/\.(\d+)\.|\.(\d+)$/).filter(Boolean);
1635
2066
  if (subpaths.length < 2) {
1636
- return self.paths.hasOwnProperty(subpaths[0]) ?
2067
+ return Object.hasOwn(self.paths, subpaths[0]) ?
1637
2068
  self.paths[subpaths[0]] :
1638
2069
  'adhocOrUndefined';
1639
2070
  }
@@ -1652,10 +2083,10 @@ function getPositionalPathType(self, path) {
1652
2083
 
1653
2084
  if (i === last && val && !/\D/.test(subpath)) {
1654
2085
  if (val.$isMongooseDocumentArray) {
1655
- val = val.$embeddedSchemaType;
2086
+ val = val.embeddedSchemaType;
1656
2087
  } else if (val instanceof MongooseTypes.Array) {
1657
2088
  // StringSchema, NumberSchema, etc
1658
- val = val.caster;
2089
+ val = val.embeddedSchemaType;
1659
2090
  } else {
1660
2091
  val = undefined;
1661
2092
  }
@@ -1666,12 +2097,12 @@ function getPositionalPathType(self, path) {
1666
2097
  if (!/\D/.test(subpath)) {
1667
2098
  // Nested array
1668
2099
  if (val instanceof MongooseTypes.Array && i !== last) {
1669
- val = val.caster;
2100
+ val = val.embeddedSchemaType;
1670
2101
  }
1671
2102
  continue;
1672
2103
  }
1673
2104
 
1674
- if (!(val && val.schema)) {
2105
+ if (!val?.schema) {
1675
2106
  val = undefined;
1676
2107
  break;
1677
2108
  }
@@ -1681,7 +2112,7 @@ function getPositionalPathType(self, path) {
1681
2112
  val = val.schema.path(subpath);
1682
2113
  }
1683
2114
 
1684
- self.subpaths[path] = val;
2115
+ self.subpaths[cleanPath] = val;
1685
2116
  if (val) {
1686
2117
  return 'real';
1687
2118
  }
@@ -1696,9 +2127,9 @@ function getPositionalPathType(self, path) {
1696
2127
  * ignore
1697
2128
  */
1698
2129
 
1699
- function getPositionalPath(self, path) {
1700
- getPositionalPathType(self, path);
1701
- return self.subpaths[path];
2130
+ function getPositionalPath(self, path, cleanPath) {
2131
+ getPositionalPathType(self, path, cleanPath);
2132
+ return self.subpaths[cleanPath];
1702
2133
  }
1703
2134
 
1704
2135
  /**
@@ -1712,7 +2143,7 @@ function getPositionalPath(self, path) {
1712
2143
  * const Model = mongoose.model('Test', schema);
1713
2144
  * new Model({ name: 'test' }); // Prints '{"_id": ..., "name": "test" }'
1714
2145
  *
1715
- * @param {String} name name of the document method to call later
2146
+ * @param {string} name name of the document method to call later
1716
2147
  * @param {Array} args arguments to pass to the method
1717
2148
  * @api public
1718
2149
  */
@@ -1729,23 +2160,21 @@ Schema.prototype.queue = function(name, args) {
1729
2160
  *
1730
2161
  * const toySchema = new Schema({ name: String, created: Date });
1731
2162
  *
1732
- * toySchema.pre('save', function(next) {
2163
+ * toySchema.pre('save', function() {
1733
2164
  * if (!this.created) this.created = new Date;
1734
- * next();
1735
2165
  * });
1736
2166
  *
1737
- * toySchema.pre('validate', function(next) {
2167
+ * toySchema.pre('validate', function() {
1738
2168
  * if (this.name !== 'Woody') this.name = 'Woody';
1739
- * next();
1740
2169
  * });
1741
2170
  *
1742
2171
  * // Equivalent to calling `pre()` on `find`, `findOne`, `findOneAndUpdate`.
1743
- * toySchema.pre(/^find/, function(next) {
2172
+ * toySchema.pre(/^find/, function() {
1744
2173
  * console.log(this.getFilter());
1745
2174
  * });
1746
2175
  *
1747
2176
  * // Equivalent to calling `pre()` on `updateOne`, `findOneAndUpdate`.
1748
- * toySchema.pre(['updateOne', 'findOneAndUpdate'], function(next) {
2177
+ * toySchema.pre(['updateOne', 'findOneAndUpdate'], function() {
1749
2178
  * console.log(this.getFilter());
1750
2179
  * });
1751
2180
  *
@@ -1757,10 +2186,10 @@ Schema.prototype.queue = function(name, args) {
1757
2186
  * // Runs when you call `doc.deleteOne()`
1758
2187
  * });
1759
2188
  *
1760
- * @param {String|RegExp|String[]} methodName The method name or regular expression to match method name
1761
- * @param {Object} [options]
1762
- * @param {Boolean} [options.document] If `name` is a hook for both document and query middleware, set to `true` to run on document middleware. For example, set `options.document` to `true` to apply this hook to `Document#deleteOne()` rather than `Query#deleteOne()`.
1763
- * @param {Boolean} [options.query] If `name` is a hook for both document and query middleware, set to `true` to run on query middleware.
2189
+ * @param {string|RegExp|string[]} methodName The method name or regular expression to match method name
2190
+ * @param {object} [options]
2191
+ * @param {boolean} [options.document] If `name` is a hook for both document and query middleware, set to `true` to run on document middleware. For example, set `options.document` to `true` to apply this hook to `Document#deleteOne()` rather than `Query#deleteOne()`.
2192
+ * @param {boolean} [options.query] If `name` is a hook for both document and query middleware, set to `true` to run on query middleware.
1764
2193
  * @param {Function} callback
1765
2194
  * @api public
1766
2195
  */
@@ -1805,18 +2234,16 @@ Schema.prototype.pre = function(name) {
1805
2234
  * const Model = mongoose.model('Model', schema);
1806
2235
  *
1807
2236
  * const m = new Model(..);
1808
- * m.save(function(err) {
1809
- * console.log('this fires after the `post` hook');
1810
- * });
2237
+ * await m.save();
2238
+ * console.log('this fires after the `post` hook');
1811
2239
  *
1812
- * m.find(function(err, docs) {
1813
- * console.log('this fires after the post find hook');
1814
- * });
2240
+ * await m.find();
2241
+ * console.log('this fires after the post find hook');
1815
2242
  *
1816
- * @param {String|RegExp|String[]} methodName The method name or regular expression to match method name
1817
- * @param {Object} [options]
1818
- * @param {Boolean} [options.document] If `name` is a hook for both document and query middleware, set to `true` to run on document middleware.
1819
- * @param {Boolean} [options.query] If `name` is a hook for both document and query middleware, set to `true` to run on query middleware.
2243
+ * @param {string|RegExp|string[]} methodName The method name or regular expression to match method name
2244
+ * @param {object} [options]
2245
+ * @param {boolean} [options.document] If `name` is a hook for both document and query middleware, set to `true` to run on document middleware.
2246
+ * @param {boolean} [options.query] If `name` is a hook for both document and query middleware, set to `true` to run on query middleware.
1820
2247
  * @param {Function} fn callback
1821
2248
  * @see middleware https://mongoosejs.com/docs/middleware.html
1822
2249
  * @see kareem https://npmjs.org/package/kareem
@@ -1860,19 +2287,20 @@ Schema.prototype.post = function(name) {
1860
2287
  * mongoose.model('Test', s); // Prints 'Schema Path Name: name'
1861
2288
  *
1862
2289
  * @param {Function} plugin The Plugin's callback
1863
- * @param {Object} [opts] Options to pass to the plugin
1864
- * @param {Boolean} [opts.deduplicate=false] If true, ignore duplicate plugins (same `fn` argument using `===`)
1865
- * @see plugins /docs/plugins.html
2290
+ * @param {object} [opts] Options to pass to the plugin
2291
+ * @param {boolean} [opts.deduplicate=false] If true, ignore duplicate plugins (same `fn` argument using `===`)
2292
+ * @see plugins https://mongoosejs.com/docs/plugins.html
1866
2293
  * @api public
1867
2294
  */
1868
2295
 
1869
2296
  Schema.prototype.plugin = function(fn, opts) {
1870
2297
  if (typeof fn !== 'function') {
1871
- throw new Error('First param to `schema.plugin()` must be a function, ' +
2298
+ throw new MongooseError('First param to `schema.plugin()` must be a function, ' +
1872
2299
  'got "' + (typeof fn) + '"');
1873
2300
  }
1874
2301
 
1875
- if (opts && opts.deduplicate) {
2302
+
2303
+ if (opts?.deduplicate) {
1876
2304
  for (const plugin of this.plugins) {
1877
2305
  if (plugin.fn === fn) {
1878
2306
  return this;
@@ -1885,6 +2313,37 @@ Schema.prototype.plugin = function(fn, opts) {
1885
2313
  return this;
1886
2314
  };
1887
2315
 
2316
+ /**
2317
+ * Adds a query helper to this schema. Equivalent to `schema.query[name] = fn`.
2318
+ *
2319
+ * #### Example:
2320
+ *
2321
+ * schema.queryHelper('byName', function(name) {
2322
+ * return this.where({ name });
2323
+ * });
2324
+ * const Test = mongoose.model('Test', schema);
2325
+ * await Test.find().byName('John'); // Equivalent to `Test.find({ name: 'John' })`
2326
+ *
2327
+ * @param {string} name The query helper name.
2328
+ * @param {Function} fn The query helper function.
2329
+ * @return {Schema} this
2330
+ * @api public
2331
+ */
2332
+
2333
+ Schema.prototype.queryHelper = function queryHelper(name, fn) {
2334
+ if (typeof name !== 'string') {
2335
+ throw new MongooseError('First param to `schema.queryHelper()` must be a string, ' +
2336
+ 'got "' + (typeof name) + '"');
2337
+ }
2338
+ if (typeof fn !== 'function') {
2339
+ throw new MongooseError('Second param to `schema.queryHelper()` must be a function, ' +
2340
+ 'got "' + (typeof fn) + '"');
2341
+ }
2342
+
2343
+ this.query[name] = fn;
2344
+ return this;
2345
+ };
2346
+
1888
2347
  /**
1889
2348
  * Adds an instance method to documents constructed from Models compiled from this schema.
1890
2349
  *
@@ -1913,22 +2372,34 @@ Schema.prototype.plugin = function(fn, opts) {
1913
2372
  * fizz.purr();
1914
2373
  * fizz.scratch();
1915
2374
  *
1916
- * NOTE: `Schema.method()` adds instance methods to the `Schema.methods` object. You can also add instance methods directly to the `Schema.methods` object as seen in the [guide](/docs/guide.html#methods)
2375
+ * NOTE: `Schema.method()` adds instance methods to the `Schema.methods` object. You can also add instance methods directly to the `Schema.methods` object as seen in the [guide](https://mongoosejs.com/docs/guide.html#methods)
1917
2376
  *
1918
- * @param {String|Object} name The Method Name for a single function, or a Object of "string-function" pairs.
2377
+ * If the method has hooks registered via `schema.pre('meow')` or `schema.post('meow')`, you can allow callers
2378
+ * to skip them for a single call by setting `supportsMiddlewareOption = true` on the function:
2379
+ *
2380
+ * schema.method('meow', function(options = {}) {
2381
+ * console.log('meeeeeoooooooooooow');
2382
+ * });
2383
+ * schema.methods.meow.supportsMiddlewareOption = true;
2384
+ *
2385
+ * // Skips `pre('meow')` and `post('meow')` hooks
2386
+ * await fizz.meow({ middleware: false });
2387
+ *
2388
+ * @param {string|object} name The Method Name for a single function, or an Object of "string-function" pairs.
1919
2389
  * @param {Function} [fn] The Function in a single-function definition.
1920
2390
  * @api public
2391
+ * @see Skip Middleware https://mongoosejs.com/docs/middleware.html#skip-custom-statics-and-methods
1921
2392
  */
1922
2393
 
1923
2394
  Schema.prototype.method = function(name, fn, options) {
1924
2395
  if (typeof name !== 'string') {
1925
2396
  for (const i in name) {
1926
2397
  this.methods[i] = name[i];
1927
- this.methodOptions[i] = utils.clone(options);
2398
+ this.methodOptions[i] = clone(options);
1928
2399
  }
1929
2400
  } else {
1930
2401
  this.methods[name] = fn;
1931
- this.methodOptions[name] = utils.clone(options);
2402
+ this.methodOptions[name] = clone(options);
1932
2403
  }
1933
2404
  return this;
1934
2405
  };
@@ -1960,10 +2431,22 @@ Schema.prototype.method = function(name, fn, options) {
1960
2431
  *
1961
2432
  * If a hash of name/fn pairs is passed as the only argument, each name/fn pair will be added as statics.
1962
2433
  *
1963
- * @param {String|Object} name The Method Name for a single function, or a Object of "string-function" pairs.
2434
+ * If the static has hooks registered via `schema.pre('findByName')` or `schema.post('findByName')`, you can allow
2435
+ * callers to skip them for a single call by setting `supportsMiddlewareOption = true` on the function:
2436
+ *
2437
+ * schema.static('findByName', function(name, options = {}) {
2438
+ * return this.find({ name: name });
2439
+ * });
2440
+ * schema.statics.findByName.supportsMiddlewareOption = true;
2441
+ *
2442
+ * // Skips `pre('findByName')` and `post('findByName')` hooks
2443
+ * await Drink.findByName('LaCroix', { middleware: false });
2444
+ *
2445
+ * @param {string|object} name The Method Name for a single function, or an Object of "string-function" pairs.
1964
2446
  * @param {Function} [fn] The Function in a single-function definition.
1965
2447
  * @api public
1966
- * @see Statics /docs/guide.html#statics
2448
+ * @see Statics https://mongoosejs.com/docs/guide.html#statics
2449
+ * @see Skip Middleware https://mongoosejs.com/docs/middleware.html#skip-custom-statics-and-methods
1967
2450
  */
1968
2451
 
1969
2452
  Schema.prototype.static = function(name, fn) {
@@ -1984,10 +2467,10 @@ Schema.prototype.static = function(name, fn) {
1984
2467
  *
1985
2468
  * schema.index({ first: 1, last: -1 })
1986
2469
  *
1987
- * @param {Object} fields The Fields to index, with the order, available values: `1 | -1 | '2d' | '2dsphere' | 'geoHaystack' | 'hashed' | 'text'`
1988
- * @param {Object} [options] Options to pass to [MongoDB driver's `createIndex()` function](https://mongodb.github.io/node-mongodb-native/4.9/classes/Collection.html#createIndex)
1989
- * @param {String | number} [options.expires=null] Mongoose-specific syntactic sugar, uses [ms](https://www.npmjs.com/package/ms) to convert `expires` option into seconds for the `expireAfterSeconds` in the above link.
1990
- * @param {String} [options.language_override=null] Tells mongodb to use the specified field instead of `language` for parsing text indexes.
2470
+ * @param {object} fields The Fields to index, with the order, available values: `1 | -1 | '2d' | '2dsphere' | 'geoHaystack' | 'hashed' | 'text'`
2471
+ * @param {object} [options] Options to pass to [MongoDB driver's `createIndex()` function](https://mongodb.github.io/node-mongodb-native/7.0/classes/Collection.html#createIndex)
2472
+ * @param {string | number} [options.expires=null] Mongoose-specific syntactic sugar, uses [ms](https://www.npmjs.com/package/ms) to convert `expires` option into seconds for the `expireAfterSeconds` in the above link.
2473
+ * @param {string} [options.language_override=null] Tells mongodb to use the specified field instead of `language` for parsing text indexes.
1991
2474
  * @api public
1992
2475
  */
1993
2476
 
@@ -1998,6 +2481,18 @@ Schema.prototype.index = function(fields, options) {
1998
2481
  if (options.expires) {
1999
2482
  utils.expires(options);
2000
2483
  }
2484
+ for (const key in fields) {
2485
+ if (this.aliases[key]) {
2486
+ fields = utils.renameObjKey(fields, key, this.aliases[key]);
2487
+ }
2488
+ }
2489
+ for (const field of Object.keys(fields)) {
2490
+ if (fields[field] === 'ascending' || fields[field] === 'asc') {
2491
+ fields[field] = 1;
2492
+ } else if (fields[field] === 'descending' || fields[field] === 'desc') {
2493
+ fields[field] = -1;
2494
+ }
2495
+ }
2001
2496
 
2002
2497
  this._indexes.push([fields, options]);
2003
2498
  return this;
@@ -2012,20 +2507,30 @@ Schema.prototype.index = function(fields, options) {
2012
2507
  * schema.set('strict', false); // Sets 'strict' to false
2013
2508
  * schema.set('strict'); // 'false'
2014
2509
  *
2015
- * @param {String} key The name of the option to set the value to
2016
- * @param {Object} [value] The value to set the option to, if not passed, the option will be reset to default
2017
- * @see Schema #schema_Schema
2510
+ * @param {string} key The name of the option to set the value to
2511
+ * @param {object} [value] The value to set the option to, if not passed, the option will be reset to default
2512
+ * @param {string[]} [tags] tags to add to read preference if key === 'read'
2513
+ * @see Schema https://mongoosejs.com/docs/api/schema.html#Schema()
2018
2514
  * @api public
2019
2515
  */
2020
2516
 
2021
- Schema.prototype.set = function(key, value, _tags) {
2517
+ Schema.prototype.set = function(key, value, tags) {
2022
2518
  if (arguments.length === 1) {
2023
2519
  return this.options[key];
2024
2520
  }
2025
2521
 
2026
2522
  switch (key) {
2027
2523
  case 'read':
2028
- this.options[key] = readPref(value, _tags);
2524
+ if (typeof value === 'string') {
2525
+ this.options[key] = { mode: handleReadPreferenceAliases(value), tags };
2526
+ } else if (Array.isArray(value) && typeof value[0] === 'string') {
2527
+ this.options[key] = {
2528
+ mode: handleReadPreferenceAliases(value[0]),
2529
+ tags: value[1]
2530
+ };
2531
+ } else {
2532
+ this.options[key] = value;
2533
+ }
2029
2534
  this._userProvidedOptions[key] = this.options[key];
2030
2535
  break;
2031
2536
  case 'timestamps':
@@ -2049,9 +2554,43 @@ Schema.prototype.set = function(key, value, _tags) {
2049
2554
  break;
2050
2555
  }
2051
2556
 
2557
+ // Propagate `strict` and `strictQuery` changes down to implicitly created schemas
2558
+ if (key === 'strict') {
2559
+ _propagateOptionsToImplicitlyCreatedSchemas(this, { strict: value });
2560
+ }
2561
+ if (key === 'strictQuery') {
2562
+ _propagateOptionsToImplicitlyCreatedSchemas(this, { strictQuery: value });
2563
+ }
2564
+ if (key === 'toObject') {
2565
+ value = { ...value };
2566
+ // Avoid propagating transform to implicitly created schemas re: gh-3279
2567
+ delete value.transform;
2568
+ _propagateOptionsToImplicitlyCreatedSchemas(this, { toObject: value });
2569
+ }
2570
+ if (key === 'toJSON') {
2571
+ value = { ...value };
2572
+ // Avoid propagating transform to implicitly created schemas re: gh-3279
2573
+ delete value.transform;
2574
+ _propagateOptionsToImplicitlyCreatedSchemas(this, { toJSON: value });
2575
+ }
2576
+
2052
2577
  return this;
2053
2578
  };
2054
2579
 
2580
+ /*!
2581
+ * Recursively set options on implicitly created schemas
2582
+ */
2583
+
2584
+ function _propagateOptionsToImplicitlyCreatedSchemas(baseSchema, options) {
2585
+ for (const { schema } of baseSchema.childSchemas) {
2586
+ if (!schema.$implicitlyCreated) {
2587
+ continue;
2588
+ }
2589
+ Object.assign(schema.options, options);
2590
+ _propagateOptionsToImplicitlyCreatedSchemas(schema, options);
2591
+ }
2592
+ }
2593
+
2055
2594
  /**
2056
2595
  * Gets a schema option.
2057
2596
  *
@@ -2061,9 +2600,9 @@ Schema.prototype.set = function(key, value, _tags) {
2061
2600
  * schema.set('strict', false);
2062
2601
  * schema.get('strict'); // false
2063
2602
  *
2064
- * @param {String} key The name of the Option to get the current value for
2603
+ * @param {string} key The name of the Option to get the current value for
2065
2604
  * @api public
2066
- * @return {Any} the option's value
2605
+ * @return {any} the option's value
2067
2606
  */
2068
2607
 
2069
2608
  Schema.prototype.get = function(key) {
@@ -2075,7 +2614,7 @@ const indexTypes = '2d 2dsphere hashed text'.split(' ');
2075
2614
  /**
2076
2615
  * The allowed index types
2077
2616
  *
2078
- * @property {String[]} indexTypes
2617
+ * @property {string[]} indexTypes
2079
2618
  * @memberOf Schema
2080
2619
  * @static
2081
2620
  * @api public
@@ -2086,7 +2625,7 @@ Object.defineProperty(Schema, 'indexTypes', {
2086
2625
  return indexTypes;
2087
2626
  },
2088
2627
  set: function() {
2089
- throw new Error('Cannot overwrite Schema.indexTypes');
2628
+ throw new MongooseError('Cannot overwrite Schema.indexTypes');
2090
2629
  }
2091
2630
  });
2092
2631
 
@@ -2101,11 +2640,11 @@ Object.defineProperty(Schema, 'indexTypes', {
2101
2640
  * registeredAt: { type: Date, index: true }
2102
2641
  * });
2103
2642
  *
2104
- * // [ [ { email: 1 }, { unique: true, background: true } ],
2105
- * // [ { registeredAt: 1 }, { background: true } ] ]
2643
+ * // [ [ { email: 1 }, { unique: true } ],
2644
+ * // [ { registeredAt: 1 }, {} ] ]
2106
2645
  * userSchema.indexes();
2107
2646
  *
2108
- * [Plugins](/docs/plugins.html) can use the return value of this function to modify a schema's indexes.
2647
+ * [Plugins](https://mongoosejs.com/docs/plugins.html) can use the return value of this function to modify a schema's indexes.
2109
2648
  * For example, the below plugin makes every index unique by default.
2110
2649
  *
2111
2650
  * function myPlugin(schema) {
@@ -2127,14 +2666,16 @@ Schema.prototype.indexes = function() {
2127
2666
  /**
2128
2667
  * Creates a virtual type with the given name.
2129
2668
  *
2130
- * @param {String} name The name of the Virtual
2131
- * @param {Object} [options]
2132
- * @param {String|Model} [options.ref] model name or model instance. Marks this as a [populate virtual](/docs/populate.html#populate-virtuals).
2133
- * @param {String|Function} [options.localField] Required for populate virtuals. See [populate virtual docs](/docs/populate.html#populate-virtuals) for more information.
2134
- * @param {String|Function} [options.foreignField] Required for populate virtuals. See [populate virtual docs](/docs/populate.html#populate-virtuals) for more information.
2135
- * @param {Boolean|Function} [options.justOne=false] Only works with populate virtuals. If [truthy](https://masteringjs.io/tutorials/fundamentals/truthy), will be a single doc or `null`. Otherwise, the populate virtual will be an array.
2136
- * @param {Boolean} [options.count=false] Only works with populate virtuals. If [truthy](https://masteringjs.io/tutorials/fundamentals/truthy), this populate virtual will contain the number of documents rather than the documents themselves when you `populate()`.
2137
- * @param {Function|null} [options.get=null] Adds a [getter](/docs/tutorials/getters-setters.html) to this virtual to transform the populated doc.
2669
+ * @param {string} name The name of the Virtual
2670
+ * @param {object} [options]
2671
+ * @param {string|Model} [options.ref] model name or model instance. Marks this as a [populate virtual](https://mongoosejs.com/docs/populate.html#populate-virtuals).
2672
+ * @param {string|Function} [options.localField] Required for populate virtuals. See [populate virtual docs](https://mongoosejs.com/docs/populate.html#populate-virtuals) for more information.
2673
+ * @param {string|Function} [options.foreignField] Required for populate virtuals. See [populate virtual docs](https://mongoosejs.com/docs/populate.html#populate-virtuals) for more information.
2674
+ * @param {boolean|Function} [options.justOne=false] Only works with populate virtuals. If [truthy](https://masteringjs.io/tutorials/fundamentals/truthy), will be a single doc or `null`. Otherwise, the populate virtual will be an array.
2675
+ * @param {boolean} [options.count=false] Only works with populate virtuals. If [truthy](https://masteringjs.io/tutorials/fundamentals/truthy), this populate virtual will contain the number of documents rather than the documents themselves when you `populate()`.
2676
+ * @param {Function|null} [options.get=null] Adds a [getter](https://mongoosejs.com/docs/tutorials/getters-setters.html) to this virtual to transform the populated doc.
2677
+ * @param {object|Function} [options.match=null] Apply a default [`match` option to populate](https://mongoosejs.com/docs/populate.html#match), adding an additional filter to the populate query.
2678
+ * @param {boolean} [options.applyToArray=false] If true and the given `name` is a direct child of an array, apply the virtual to the array rather than the elements.
2138
2679
  * @return {VirtualType}
2139
2680
  */
2140
2681
 
@@ -2152,14 +2693,17 @@ Schema.prototype.virtual = function(name, options) {
2152
2693
 
2153
2694
  if (utils.hasUserDefinedProperty(options, ['ref', 'refPath'])) {
2154
2695
  if (options.localField == null) {
2155
- throw new Error('Reference virtuals require `localField` option');
2696
+ throw new MongooseError('Reference virtuals require `localField` option');
2156
2697
  }
2157
2698
 
2158
2699
  if (options.foreignField == null) {
2159
- throw new Error('Reference virtuals require `foreignField` option');
2700
+ throw new MongooseError('Reference virtuals require `foreignField` option');
2160
2701
  }
2161
2702
 
2162
- this.pre('init', function virtualPreInit(obj) {
2703
+ const virtual = this.virtual(name);
2704
+ virtual.options = options;
2705
+
2706
+ this.pre('init', function virtualPreInit(obj, opts) {
2163
2707
  if (mpath.has(name, obj)) {
2164
2708
  const _v = mpath.get(name, obj);
2165
2709
  if (!this.$$populatedVirtuals) {
@@ -2176,36 +2720,44 @@ Schema.prototype.virtual = function(name, options) {
2176
2720
  _v == null ? [] : [_v];
2177
2721
  }
2178
2722
 
2723
+ if (opts?.hydratedPopulatedDocs && !options.count) {
2724
+ const modelNames = virtual._getModelNamesForPopulate(this);
2725
+ const populatedVal = this.$$populatedVirtuals[name];
2726
+ if (!Array.isArray(populatedVal) && !isMongooseDocument(populatedVal) && modelNames?.length === 1) {
2727
+ const PopulateModel = this.db.model(modelNames[0]);
2728
+ this.$$populatedVirtuals[name] = PopulateModel.hydrate(populatedVal);
2729
+ } else if (Array.isArray(populatedVal) && modelNames?.length === 1) {
2730
+ const PopulateModel = this.db.model(modelNames[0]);
2731
+ for (let i = 0; i < populatedVal.length; ++i) {
2732
+ if (!isMongooseDocument(populatedVal[i])) {
2733
+ populatedVal[i] = PopulateModel.hydrate(populatedVal[i], null, { hydratedPopulatedDocs: true });
2734
+ }
2735
+ }
2736
+ const foreignField = options.foreignField;
2737
+ this.$populated(
2738
+ name,
2739
+ populatedVal.map(doc => doc == null ? doc : doc.get(typeof foreignField === 'function' ? foreignField.call(doc, doc) : foreignField)),
2740
+ { populateModelSymbol: PopulateModel }
2741
+ );
2742
+ }
2743
+ }
2744
+
2179
2745
  mpath.unset(name, obj);
2180
2746
  }
2181
2747
  });
2182
2748
 
2183
- const virtual = this.virtual(name);
2184
- virtual.options = options;
2185
-
2186
2749
  virtual.
2187
- set(function(_v) {
2750
+ set(function(v) {
2188
2751
  if (!this.$$populatedVirtuals) {
2189
2752
  this.$$populatedVirtuals = {};
2190
2753
  }
2191
2754
 
2192
- if (options.justOne || options.count) {
2193
- this.$$populatedVirtuals[name] = Array.isArray(_v) ?
2194
- _v[0] :
2195
- _v;
2196
-
2197
- if (typeof this.$$populatedVirtuals[name] !== 'object') {
2198
- this.$$populatedVirtuals[name] = options.count ? _v : null;
2199
- }
2200
- } else {
2201
- this.$$populatedVirtuals[name] = Array.isArray(_v) ?
2202
- _v :
2203
- _v == null ? [] : [_v];
2204
-
2205
- this.$$populatedVirtuals[name] = this.$$populatedVirtuals[name].filter(function(doc) {
2206
- return doc && typeof doc === 'object';
2207
- });
2208
- }
2755
+ return setPopulatedVirtualValue(
2756
+ this.$$populatedVirtuals,
2757
+ name,
2758
+ v,
2759
+ options
2760
+ );
2209
2761
  });
2210
2762
 
2211
2763
  if (typeof options.get === 'function') {
@@ -2213,14 +2765,22 @@ Schema.prototype.virtual = function(name, options) {
2213
2765
  }
2214
2766
 
2215
2767
  // Workaround for gh-8198: if virtual is under document array, make a fake
2216
- // virtual. See gh-8210
2768
+ // virtual. See gh-8210, gh-13189
2217
2769
  const parts = name.split('.');
2218
2770
  let cur = parts[0];
2219
2771
  for (let i = 0; i < parts.length - 1; ++i) {
2220
- if (this.paths[cur] != null && this.paths[cur].$isMongooseDocumentArray) {
2772
+ if (this.paths[cur] == null) {
2773
+ continue;
2774
+ }
2775
+
2776
+ if (this.paths[cur].$isMongooseDocumentArray || this.paths[cur].$isSingleNested) {
2221
2777
  const remnant = parts.slice(i + 1).join('.');
2222
2778
  this.paths[cur].schema.virtual(remnant, options);
2223
2779
  break;
2780
+ } else if (this.paths[cur].$isSchemaMap) {
2781
+ const remnant = parts.slice(i + 2).join('.');
2782
+ this.paths[cur].$__schemaType.schema.virtual(remnant, options);
2783
+ break;
2224
2784
  }
2225
2785
 
2226
2786
  cur += '.' + parts[i + 1];
@@ -2232,7 +2792,7 @@ Schema.prototype.virtual = function(name, options) {
2232
2792
  const virtuals = this.virtuals;
2233
2793
 
2234
2794
  if (this.pathType(name) === 'real') {
2235
- throw new Error('Virtual path "' + name + '"' +
2795
+ throw new MongooseError('Virtual path "' + name + '"' +
2236
2796
  ' conflicts with a real path in the schema');
2237
2797
  }
2238
2798
 
@@ -2243,18 +2803,27 @@ Schema.prototype.virtual = function(name, options) {
2243
2803
  return mem[part];
2244
2804
  }, this.tree);
2245
2805
 
2806
+ if (options?.applyToArray && parts.length > 1) {
2807
+ const path = this.path(parts.slice(0, -1).join('.'));
2808
+ if (path?.$isMongooseArray) {
2809
+ return path.virtual(parts[parts.length - 1], options);
2810
+ } else {
2811
+ throw new MongooseError(`Path "${path}" is not an array`);
2812
+ }
2813
+ }
2814
+
2246
2815
  return virtuals[name];
2247
2816
  };
2248
2817
 
2249
2818
  /**
2250
2819
  * Returns the virtual type with the given `name`.
2251
2820
  *
2252
- * @param {String} name The name of the Virtual to get
2821
+ * @param {string} name The name of the Virtual to get
2253
2822
  * @return {VirtualType|null}
2254
2823
  */
2255
2824
 
2256
2825
  Schema.prototype.virtualpath = function(name) {
2257
- return this.virtuals.hasOwnProperty(name) ? this.virtuals[name] : null;
2826
+ return Object.hasOwn(this.virtuals, name) ? this.virtuals[name] : null;
2258
2827
  };
2259
2828
 
2260
2829
  /**
@@ -2273,7 +2842,7 @@ Schema.prototype.virtualpath = function(name) {
2273
2842
  * schema.path('name'); // Undefined
2274
2843
  * schema.path('age'); // Undefined
2275
2844
  *
2276
- * @param {String|Array} path The Path(s) to remove
2845
+ * @param {string|Array} path The Path(s) to remove
2277
2846
  * @return {Schema} the Schema instance
2278
2847
  * @api public
2279
2848
  */
@@ -2286,6 +2855,19 @@ Schema.prototype.remove = function(path) {
2286
2855
  if (this.path(name) == null && !this.nested[name]) {
2287
2856
  return;
2288
2857
  }
2858
+ this._defaultsCache = null;
2859
+ this._hasSelectedPaths = undefined;
2860
+ // Drop aliases that point to the removed path, or to a path under it, along
2861
+ // with their virtuals, so they don't keep translating keys to a missing path.
2862
+ for (const [alias, target] of Object.entries(this.aliases)) {
2863
+ if (target === name || target.startsWith(name + '.')) {
2864
+ delete this.aliases[alias];
2865
+ delete this.virtuals[alias];
2866
+ if (get(this.tree, alias) instanceof VirtualType) {
2867
+ _deletePath(this, alias);
2868
+ }
2869
+ }
2870
+ }
2289
2871
  if (this.nested[name]) {
2290
2872
  const allKeys = Object.keys(this.paths).
2291
2873
  concat(Object.keys(this.nested));
@@ -2297,13 +2879,36 @@ Schema.prototype.remove = function(path) {
2297
2879
  }
2298
2880
  }
2299
2881
 
2882
+ this.mapPaths = this.mapPaths.filter(
2883
+ schemaType => !schemaType.path.startsWith(name + '.')
2884
+ );
2885
+ _deleteSubpaths(this, name);
2886
+
2300
2887
  delete this.nested[name];
2301
2888
  _deletePath(this, name);
2302
2889
  return;
2303
2890
  }
2304
2891
 
2305
2892
  delete this.paths[name];
2893
+ // A map registers its values under `<path>.$*`, both in `paths` and in
2894
+ // `mapPaths`. Left behind, they keep answering `pathType()` and casting queries
2895
+ // for a path the schema no longer has.
2896
+ for (const subpath of Object.keys(this.paths)) {
2897
+ if (subpath.startsWith(name + '.')) {
2898
+ delete this.paths[subpath];
2899
+ }
2900
+ }
2901
+ this.mapPaths = this.mapPaths.filter(
2902
+ schemaType => !schemaType.path.startsWith(name + '.')
2903
+ );
2904
+ // A document array registers its element paths under `subpaths` and a
2905
+ // single nested subdocument registers its paths under `singleNestedPaths`.
2906
+ // Left behind, they keep answering `path()` and `pathType()`, and queries
2907
+ // on the removed path keep being cast.
2908
+ _deleteSubpaths(this, name);
2306
2909
  _deletePath(this, name);
2910
+
2911
+ this._removeEncryptedField(name);
2307
2912
  }, this);
2308
2913
  }
2309
2914
  return this;
@@ -2313,6 +2918,20 @@ Schema.prototype.remove = function(path) {
2313
2918
  * ignore
2314
2919
  */
2315
2920
 
2921
+ function _deleteSubpaths(schema, name) {
2922
+ const prefix = name + '.';
2923
+ for (const subpath of Object.keys(schema.subpaths)) {
2924
+ if (subpath === name || subpath.startsWith(prefix)) {
2925
+ delete schema.subpaths[subpath];
2926
+ }
2927
+ }
2928
+ for (const subpath of Object.keys(schema.singleNestedPaths)) {
2929
+ if (subpath === name || subpath.startsWith(prefix)) {
2930
+ delete schema.singleNestedPaths[subpath];
2931
+ }
2932
+ }
2933
+ }
2934
+
2316
2935
  function _deletePath(schema, name) {
2317
2936
  const pieces = name.split('.');
2318
2937
  const last = pieces.pop();
@@ -2321,6 +2940,9 @@ function _deletePath(schema, name) {
2321
2940
 
2322
2941
  for (const piece of pieces) {
2323
2942
  branch = branch[piece];
2943
+ if (branch == null) {
2944
+ return;
2945
+ }
2324
2946
  }
2325
2947
 
2326
2948
  delete branch[last];
@@ -2329,7 +2951,7 @@ function _deletePath(schema, name) {
2329
2951
  /**
2330
2952
  * Removes the given virtual or virtuals from the schema.
2331
2953
  *
2332
- * @param {String|Array} path The virutal path(s) to remove.
2954
+ * @param {string|Array} path The virutal path(s) to remove.
2333
2955
  * @returns {Schema} the Schema instance, or a mongoose error if the virtual does not exist.
2334
2956
  * @api public
2335
2957
  */
@@ -2346,6 +2968,22 @@ Schema.prototype.removeVirtual = function(path) {
2346
2968
  }
2347
2969
 
2348
2970
  for (const virtual of path) {
2971
+ if (Object.hasOwn(this.aliases, virtual)) {
2972
+ // `pick()` rebuilds aliases from the SchemaType's options, and `omit()` and
2973
+ // `add(schema)` rebuild them from the tree, so drop the alias from both or it
2974
+ // comes back on every schema derived from this one.
2975
+ const aliasedPath = this.aliases[virtual];
2976
+ delete this.aliases[virtual];
2977
+ const treeEntry = get(this.tree, aliasedPath);
2978
+ const treeOptions = treeEntry instanceof SchemaType ? treeEntry.options : treeEntry;
2979
+ for (const options of [this.paths[aliasedPath]?.options, treeOptions]) {
2980
+ if (options?.alias === virtual) {
2981
+ delete options.alias;
2982
+ } else if (Array.isArray(options?.alias)) {
2983
+ options.alias = options.alias.filter(a => a !== virtual);
2984
+ }
2985
+ }
2986
+ }
2349
2987
  delete this.paths[virtual];
2350
2988
  delete this.virtuals[virtual];
2351
2989
  if (virtual.indexOf('.') !== -1) {
@@ -2361,9 +2999,9 @@ Schema.prototype.removeVirtual = function(path) {
2361
2999
  /**
2362
3000
  * Loads an ES6 class into a schema. Maps [setters](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/set) + [getters](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/get), [static methods](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes/static),
2363
3001
  * and [instance methods](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes#Class_body_and_method_definitions)
2364
- * to schema [virtuals](/docs/guide.html#virtuals),
2365
- * [statics](/docs/guide.html#statics), and
2366
- * [methods](/docs/guide.html#methods).
3002
+ * to schema [virtuals](https://mongoosejs.com/docs/guide.html#virtuals),
3003
+ * [statics](https://mongoosejs.com/docs/guide.html#statics), and
3004
+ * [methods](https://mongoosejs.com/docs/guide.html#methods).
2367
3005
  *
2368
3006
  * #### Example:
2369
3007
  *
@@ -2394,14 +3032,14 @@ Schema.prototype.removeVirtual = function(path) {
2394
3032
  * ```
2395
3033
  *
2396
3034
  * @param {Function} model The Class to load
2397
- * @param {Boolean} [virtualsOnly] if truthy, only pulls virtuals from the class, not methods or statics
3035
+ * @param {boolean} [virtualsOnly] if truthy, only pulls virtuals from the class, not methods or statics
2398
3036
  */
2399
3037
  Schema.prototype.loadClass = function(model, virtualsOnly) {
2400
3038
  // Stop copying when hit certain base classes
2401
3039
  if (model === Object.prototype ||
2402
3040
  model === Function.prototype ||
2403
- model.prototype.hasOwnProperty('$isMongooseModelPrototype') ||
2404
- model.prototype.hasOwnProperty('$isMongooseDocumentPrototype')) {
3041
+ Object.hasOwn(model.prototype, '$isMongooseModelPrototype') ||
3042
+ Object.hasOwn(model.prototype, '$isMongooseDocumentPrototype')) {
2405
3043
  return this;
2406
3044
  }
2407
3045
 
@@ -2414,7 +3052,7 @@ Schema.prototype.loadClass = function(model, virtualsOnly) {
2414
3052
  return;
2415
3053
  }
2416
3054
  const prop = Object.getOwnPropertyDescriptor(model, name);
2417
- if (prop.hasOwnProperty('value')) {
3055
+ if (Object.hasOwn(prop, 'value')) {
2418
3056
  this.static(name, prop.value);
2419
3057
  }
2420
3058
  }, this);
@@ -2473,11 +3111,11 @@ Schema.prototype._getSchema = function(path) {
2473
3111
  if (foundschema) {
2474
3112
  resultPath.push(trypath);
2475
3113
 
2476
- if (foundschema.caster) {
3114
+ if (foundschema.embeddedSchemaType || foundschema.Constructor) {
2477
3115
  // array of Mixed?
2478
- if (foundschema.caster instanceof MongooseTypes.Mixed) {
2479
- foundschema.caster.$fullPath = resultPath.join('.');
2480
- return foundschema.caster;
3116
+ if (foundschema.embeddedSchemaType instanceof MongooseTypes.Mixed) {
3117
+ foundschema.embeddedSchemaType.$fullPath = resultPath.join('.');
3118
+ return foundschema.embeddedSchemaType;
2481
3119
  }
2482
3120
 
2483
3121
  // Now that we found the array, we need to check if there
@@ -2487,26 +3125,30 @@ Schema.prototype._getSchema = function(path) {
2487
3125
  // If there is no foundschema.schema we are dealing with
2488
3126
  // a path like array.$
2489
3127
  if (p !== parts.length) {
3128
+ if (p + 1 === parts.length && foundschema.embeddedSchemaType && (parts[p] === '$' || isArrayFilter(parts[p]))) {
3129
+ return foundschema.embeddedSchemaType;
3130
+ }
3131
+
2490
3132
  if (foundschema.schema) {
2491
3133
  let ret;
2492
3134
  if (parts[p] === '$' || isArrayFilter(parts[p])) {
2493
3135
  if (p + 1 === parts.length) {
2494
3136
  // comments.$
2495
- return foundschema;
3137
+ return foundschema.embeddedSchemaType;
2496
3138
  }
2497
3139
  // comments.$.comments.$.title
2498
3140
  ret = search(parts.slice(p + 1), foundschema.schema);
2499
3141
  if (ret) {
2500
- ret.$isUnderneathDocArray = ret.$isUnderneathDocArray ||
2501
- !foundschema.schema.$isSingleNested;
3142
+ ret.$parentSchemaDocArray = ret.$parentSchemaDocArray ||
3143
+ (foundschema.schema.$isSingleNested ? null : foundschema);
2502
3144
  }
2503
3145
  return ret;
2504
3146
  }
2505
3147
  // this is the last path of the selector
2506
3148
  ret = search(parts.slice(p), foundschema.schema);
2507
3149
  if (ret) {
2508
- ret.$isUnderneathDocArray = ret.$isUnderneathDocArray ||
2509
- !foundschema.schema.$isSingleNested;
3150
+ ret.$parentSchemaDocArray = ret.$parentSchemaDocArray ||
3151
+ (foundschema.schema.$isSingleNested ? null : foundschema);
2510
3152
  }
2511
3153
  return ret;
2512
3154
  }
@@ -2544,6 +3186,9 @@ Schema.prototype._getSchema = function(path) {
2544
3186
  // Re: gh-5628, because `schema.path()` doesn't take $ into account.
2545
3187
  parts[i] = '0';
2546
3188
  }
3189
+ if (numberRE.test(parts[i])) {
3190
+ parts[i] = '$';
3191
+ }
2547
3192
  }
2548
3193
  return search(parts, _this);
2549
3194
  };
@@ -2569,9 +3214,9 @@ Schema.prototype._getPathType = function(path) {
2569
3214
  trypath = parts.slice(0, p).join('.');
2570
3215
  foundschema = schema.path(trypath);
2571
3216
  if (foundschema) {
2572
- if (foundschema.caster) {
3217
+ if (foundschema.embeddedSchemaType || foundschema.Constructor) {
2573
3218
  // array of Mixed?
2574
- if (foundschema.caster instanceof MongooseTypes.Mixed) {
3219
+ if (foundschema.embeddedSchemaType instanceof MongooseTypes.Mixed) {
2575
3220
  return { schema: foundschema, pathType: 'mixed' };
2576
3221
  }
2577
3222
 
@@ -2598,7 +3243,7 @@ Schema.prototype._getPathType = function(path) {
2598
3243
  };
2599
3244
  }
2600
3245
  return { schema: foundschema, pathType: 'real' };
2601
- } else if (p === parts.length && Object.prototype.hasOwnProperty.call(schema.nested, trypath)) {
3246
+ } else if (p === parts.length && Object.hasOwn(schema.nested, trypath)) {
2602
3247
  return { schema: schema, pathType: 'nested' };
2603
3248
  }
2604
3249
  }
@@ -2609,6 +3254,39 @@ Schema.prototype._getPathType = function(path) {
2609
3254
  return search(path.split('.'), _this);
2610
3255
  };
2611
3256
 
3257
+ /**
3258
+ * Transforms the duplicate key error by checking for duplicate key error messages by path.
3259
+ * If no duplicate key error messages are found, returns the original error.
3260
+ *
3261
+ * @param {Error} error The error to transform
3262
+ * @returns {Error} The transformed error
3263
+ * @api private
3264
+ */
3265
+
3266
+ Schema.prototype._transformDuplicateKeyError = function _transformDuplicateKeyError(error) {
3267
+ if (!this._duplicateKeyErrorMessagesByPath) {
3268
+ return error;
3269
+ }
3270
+ if (error.code !== 11000 && error.code !== 11001) {
3271
+ return error;
3272
+ }
3273
+
3274
+ if (error.keyPattern != null) {
3275
+ const keyPattern = error.keyPattern;
3276
+ const keys = Object.keys(keyPattern);
3277
+ if (keys.length !== 1) {
3278
+ return error;
3279
+ }
3280
+ const firstKey = keys[0];
3281
+ if (!Object.hasOwn(this._duplicateKeyErrorMessagesByPath, firstKey)) {
3282
+ return error;
3283
+ }
3284
+ return new MongooseError(this._duplicateKeyErrorMessagesByPath[firstKey], { cause: error });
3285
+ }
3286
+
3287
+ return error;
3288
+ };
3289
+
2612
3290
  /*!
2613
3291
  * ignore
2614
3292
  */
@@ -2618,8 +3296,10 @@ function isArrayFilter(piece) {
2618
3296
  }
2619
3297
 
2620
3298
  /**
2621
- * Called by `compile()` _right before_ compiling. Good for making any changes to
2622
- * the schema that should respect options set by plugins, like `id`
3299
+ * Called by `Model.compile()` _right before_ compiling and by `Model.recompileSchema()`.
3300
+ * Good for making any changes to the schema that should respect options set by plugins,
3301
+ * like `id`. Not called on nested schemas, because those can still change until the
3302
+ * top-level model is compiled.
2623
3303
  * @method _preCompile
2624
3304
  * @memberOf Schema
2625
3305
  * @instance
@@ -2627,7 +3307,202 @@ function isArrayFilter(piece) {
2627
3307
  */
2628
3308
 
2629
3309
  Schema.prototype._preCompile = function _preCompile() {
2630
- idGetter(this);
3310
+ // Check `defaultSort` again in case it was changed after the schema was created
3311
+ _validateDefaultSort(this.options.defaultSort);
3312
+ this.plugin(idGetter, { deduplicate: true });
3313
+ _precomputeOptimisticConcurrency(this);
3314
+ _clearDerivedPathCaches(this, new Set());
3315
+ this._hasSelectedPaths = _hasSelectedPaths(this, []);
3316
+ };
3317
+
3318
+ /*!
3319
+ * Throws if `defaultSort` is not a valid value for the `defaultSort` schema option. Disallows `$meta` sorts,
3320
+ * like `{ score: { $meta: 'textScore' } }`, because MongoDB throws on `$meta` sorts for queries without `$text`.
3321
+ */
3322
+
3323
+ function _validateDefaultSort(defaultSort) {
3324
+ if (!defaultSort) {
3325
+ return;
3326
+ }
3327
+ // An empty `defaultSort` would silently mean "no sort", which would let `findAndCount()` run unsorted.
3328
+ // Use `defaultSort: null` to disable the default sort instead.
3329
+ const emptyError = '`defaultSort` must not be empty, use `defaultSort: null` to disable the default sort';
3330
+ if (typeof defaultSort === 'string') {
3331
+ if (defaultSort.trim() === '') {
3332
+ throw new MongooseError(emptyError);
3333
+ }
3334
+ return;
3335
+ }
3336
+ if (typeof defaultSort !== 'object') {
3337
+ throw new MongooseError('`defaultSort` must be falsy, string, object, array, or Map, got `' + (typeof defaultSort) + '`');
3338
+ }
3339
+ const entries = defaultSort instanceof Map ?
3340
+ Array.from(defaultSort) :
3341
+ Array.isArray(defaultSort) ? defaultSort : Object.entries(defaultSort);
3342
+ if (entries.length === 0) {
3343
+ throw new MongooseError(emptyError);
3344
+ }
3345
+ for (const entry of entries) {
3346
+ if (!Array.isArray(entry)) {
3347
+ throw new MongooseError('`defaultSort` array must be an array of [key, value] arrays, like `[[\'name\', 1]]`');
3348
+ }
3349
+ if (entry[1] != null && Object.hasOwn(entry[1], '$meta')) {
3350
+ throw new MongooseError('`defaultSort` does not support `$meta` sorts, got `$meta` for `' + entry[0] + '`');
3351
+ }
3352
+ }
3353
+ }
3354
+
3355
+ /*!
3356
+ * Clears caches that are derived from `schema.paths` on `schema` and all of its
3357
+ * nested schemas, because nested schemas can change until the model is compiled.
3358
+ */
3359
+
3360
+ function _clearDerivedPathCaches(schema, seen) {
3361
+ if (seen.has(schema)) {
3362
+ return;
3363
+ }
3364
+ seen.add(schema);
3365
+
3366
+ schema._defaultsCache = null;
3367
+ schema._pathsWithTransforms = undefined;
3368
+ for (const { schema: childSchema } of schema.childSchemas) {
3369
+ _clearDerivedPathCaches(childSchema, seen);
3370
+ }
3371
+ for (const discriminatorSchema of Object.values(schema.discriminators ?? {})) {
3372
+ _clearDerivedPathCaches(discriminatorSchema, seen);
3373
+ }
3374
+ }
3375
+
3376
+ /*!
3377
+ * Returns true if any path in `schema`, including paths in nested schemas,
3378
+ * has a schema-level `select` option. If not, `applyPaths()` can skip walking
3379
+ * the schema on every query. Mirrors the paths that `applyPaths()` checks.
3380
+ */
3381
+
3382
+ function _hasSelectedPaths(schema, stack) {
3383
+ // avoid recursion
3384
+ if (stack.includes(schema)) {
3385
+ return false;
3386
+ }
3387
+ stack.push(schema);
3388
+
3389
+ for (const path of Object.keys(schema.paths)) {
3390
+ const type = schema.paths[path];
3391
+ if (type.$isSchemaMap || path.endsWith('.$*')) {
3392
+ if (type.options?.select === false) {
3393
+ return true;
3394
+ }
3395
+ continue;
3396
+ }
3397
+ if (typeof type.selected === 'boolean') {
3398
+ return true;
3399
+ }
3400
+ if (type.$isMongooseArray && !type.$isMongooseDocumentArray && typeof type.embeddedSchemaType?.selected === 'boolean') {
3401
+ return true;
3402
+ }
3403
+ if (type.schema && _hasSelectedPaths(type.schema, stack)) {
3404
+ return true;
3405
+ }
3406
+ }
3407
+
3408
+ stack.pop();
3409
+ return false;
3410
+ }
3411
+
3412
+ /*!
3413
+ * Build precomputed path tries for optimisticConcurrency include/exclude so
3414
+ * that lookups at save time are a single trie walk that handles nested paths
3415
+ * and map wildcards like `settings.$*`.
3416
+ */
3417
+
3418
+ function _precomputeOptimisticConcurrency(schema) {
3419
+ const opt = schema.options.optimisticConcurrency;
3420
+ if (!opt || opt === true) {
3421
+ return;
3422
+ }
3423
+ if (Array.isArray(opt)) {
3424
+ schema.options._optimisticConcurrencyTrie = new PathTrie(opt);
3425
+ } else if (Array.isArray(opt.exclude)) {
3426
+ schema.options._optimisticConcurrencyExcludeTrie = new PathTrie(opt.exclude);
3427
+ }
3428
+ }
3429
+
3430
+ /**
3431
+ * Returns a JSON schema representation of this Schema.
3432
+ *
3433
+ * By default, returns normal [JSON schema representation](https://json-schema.org/learn/getting-started-step-by-step), which is not typically what you want to use with
3434
+ * [MongoDB's `$jsonSchema` collection option](https://www.mongodb.com/docs/manual/core/schema-validation/specify-json-schema/).
3435
+ * Use the `useBsonType: true` option to return MongoDB `$jsonSchema` syntax instead.
3436
+ *
3437
+ * In addition to types, `jsonSchema()` supports the following Mongoose validators:
3438
+ * - `enum` for strings and numbers
3439
+ *
3440
+ * #### Example:
3441
+ * const schema = new Schema({ name: String });
3442
+ * // { required: ['_id'], properties: { name: { type: ['string', 'null'] }, _id: { type: 'string' } } }
3443
+ * schema.toJSONSchema();
3444
+ *
3445
+ * // { required: ['_id'], properties: { name: { bsonType: ['string', 'null'] }, _id: { bsonType: 'objectId' } } }
3446
+ * schema.toJSONSchema({ useBsonType: true });
3447
+ *
3448
+ * @param {object} [options]
3449
+ * @param {boolean} [options.useBsonType=false] if true, specify each path's type using `bsonType` rather than `type` for MongoDB $jsonSchema support
3450
+ */
3451
+
3452
+ Schema.prototype.toJSONSchema = function toJSONSchema(options) {
3453
+ const useBsonType = options?.useBsonType ?? false;
3454
+ const result = useBsonType ? { required: [], properties: {} } : { type: 'object', required: [], properties: {} };
3455
+ for (const path of Object.keys(this.paths)) {
3456
+ const schemaType = this.paths[path];
3457
+
3458
+ // Skip Map embedded paths, maps will be handled separately.
3459
+ if (schemaType._presplitPath.indexOf('$*') !== -1) {
3460
+ continue;
3461
+ }
3462
+
3463
+ // Nested paths are stored as `nested.path` in the schema type, so create nested paths in the json schema
3464
+ // when necessary.
3465
+ const isNested = schemaType._presplitPath.length > 1;
3466
+ let jsonSchemaForPath = result;
3467
+ if (isNested) {
3468
+ for (let i = 0; i < schemaType._presplitPath.length - 1; ++i) {
3469
+ const subpath = schemaType._presplitPath[i];
3470
+ if (jsonSchemaForPath.properties[subpath] == null) {
3471
+ jsonSchemaForPath.properties[subpath] = useBsonType
3472
+ ? {
3473
+ bsonType: ['object', 'null'],
3474
+ properties: {}
3475
+ }
3476
+ : {
3477
+ type: ['object', 'null'],
3478
+ properties: {}
3479
+ };
3480
+ }
3481
+ jsonSchemaForPath = jsonSchemaForPath.properties[subpath];
3482
+ }
3483
+ }
3484
+
3485
+ const lastSubpath = schemaType._presplitPath[schemaType._presplitPath.length - 1];
3486
+ if (path === '_id') {
3487
+ if (!jsonSchemaForPath.required) {
3488
+ jsonSchemaForPath.required = [];
3489
+ }
3490
+ jsonSchemaForPath.required.push('_id');
3491
+ } else if (schemaType.options.required && typeof schemaType.options.required !== 'function') {
3492
+ if (!jsonSchemaForPath.required) {
3493
+ jsonSchemaForPath.required = [];
3494
+ }
3495
+ // Only `required: true` paths are required, conditional required is not required
3496
+ jsonSchemaForPath.required.push(lastSubpath);
3497
+ }
3498
+ jsonSchemaForPath.properties[lastSubpath] = schemaType.toJSONSchema(options);
3499
+ }
3500
+
3501
+ // Otherwise MongoDB errors with "$jsonSchema keyword 'required' cannot be an empty array"
3502
+ if (result.required.length === 0) {
3503
+ delete result.required;
3504
+ }
3505
+ return result;
2631
3506
  };
2632
3507
 
2633
3508
  /*!
@@ -2648,14 +3523,18 @@ module.exports = exports = Schema;
2648
3523
  *
2649
3524
  * #### Types:
2650
3525
  *
2651
- * - [String](/docs/schematypes.html#strings)
2652
- * - [Number](/docs/schematypes.html#numbers)
2653
- * - [Boolean](/docs/schematypes.html#booleans) | Bool
2654
- * - [Array](/docs/schematypes.html#arrays)
2655
- * - [Buffer](/docs/schematypes.html#buffers)
2656
- * - [Date](/docs/schematypes.html#dates)
2657
- * - [ObjectId](/docs/schematypes.html#objectids) | Oid
2658
- * - [Mixed](/docs/schematypes.html#mixed)
3526
+ * - [String](https://mongoosejs.com/docs/schematypes.html#strings)
3527
+ * - [Number](https://mongoosejs.com/docs/schematypes.html#numbers)
3528
+ * - [Boolean](https://mongoosejs.com/docs/schematypes.html#booleans) | Bool
3529
+ * - [Array](https://mongoosejs.com/docs/schematypes.html#arrays)
3530
+ * - [Buffer](https://mongoosejs.com/docs/schematypes.html#buffers)
3531
+ * - [Date](https://mongoosejs.com/docs/schematypes.html#dates)
3532
+ * - [ObjectId](https://mongoosejs.com/docs/schematypes.html#objectids) | Oid
3533
+ * - [Mixed](https://mongoosejs.com/docs/schematypes.html#mixed)
3534
+ * - [UUID](https://mongoosejs.com/docs/schematypes.html#uuid)
3535
+ * - [BigInt](https://mongoosejs.com/docs/schematypes.html#bigint)
3536
+ * - [Double] (https://mongoosejs.com/docs/schematypes.html#double)
3537
+ * - [Int32](https://mongoosejs.com/docs/schematypes.html#int32)
2659
3538
  *
2660
3539
  * Using this exposed access to the `Mixed` SchemaType, we can use them in our schema.
2661
3540
  *