@datanimbus/mongoose 6.13.13 → 9.13.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (302) hide show
  1. package/README.md +80 -70
  2. package/eslint.config.mjs +202 -0
  3. package/index.js +2 -1
  4. package/lib/aggregate.js +276 -174
  5. package/lib/cast/bigint.js +46 -0
  6. package/lib/cast/boolean.js +3 -3
  7. package/lib/cast/decimal128.js +4 -1
  8. package/lib/cast/double.js +56 -0
  9. package/lib/cast/int32.js +42 -0
  10. package/lib/cast/number.js +6 -6
  11. package/lib/cast/objectid.js +3 -3
  12. package/lib/cast/string.js +3 -3
  13. package/lib/cast/uuid.js +35 -0
  14. package/lib/cast.js +100 -92
  15. package/lib/collection.js +31 -22
  16. package/lib/connection.js +792 -507
  17. package/lib/constants.js +73 -0
  18. package/lib/cursor/{AggregationCursor.js → aggregationCursor.js} +205 -52
  19. package/lib/cursor/changeStream.js +218 -0
  20. package/lib/cursor/queryCursor.js +676 -0
  21. package/lib/defaults/schemaDefaultsCache.js +62 -0
  22. package/lib/document.js +2419 -1306
  23. package/lib/drivers/node-mongodb-native/bulkWriteResult.js +5 -0
  24. package/lib/drivers/node-mongodb-native/collection.js +101 -135
  25. package/lib/drivers/node-mongodb-native/connection.js +386 -28
  26. package/lib/drivers/node-mongodb-native/index.js +3 -5
  27. package/lib/error/browserMissingSchema.js +5 -4
  28. package/lib/error/bulkSaveIncompleteError.js +44 -0
  29. package/lib/error/cast.js +30 -21
  30. package/lib/error/createCollectionsError.js +26 -0
  31. package/lib/error/divergentArray.js +11 -9
  32. package/lib/error/eachAsyncMultiError.js +2 -2
  33. package/lib/error/index.js +38 -29
  34. package/lib/error/invalidSchemaOption.js +32 -0
  35. package/lib/error/messages.js +4 -3
  36. package/lib/error/missingSchema.js +8 -6
  37. package/lib/error/notFound.js +7 -5
  38. package/lib/error/objectExpected.js +9 -8
  39. package/lib/error/objectParameter.js +12 -11
  40. package/lib/error/overwriteModel.js +7 -6
  41. package/lib/error/parallelSave.js +11 -8
  42. package/lib/error/parallelValidate.js +9 -7
  43. package/lib/error/serverSelection.js +1 -0
  44. package/lib/error/setOptionError.js +11 -9
  45. package/lib/error/strict.js +12 -10
  46. package/lib/error/strictPopulate.js +11 -9
  47. package/lib/error/syncIndexes.js +2 -2
  48. package/lib/error/validation.js +11 -17
  49. package/lib/error/validator.js +9 -8
  50. package/lib/error/version.js +12 -10
  51. package/lib/filters/operators.js +8 -0
  52. package/lib/helpers/aggregate/prepareDiscriminatorPipeline.js +4 -4
  53. package/lib/helpers/buildMiddlewareFilter.js +42 -0
  54. package/lib/helpers/clone.js +121 -35
  55. package/lib/helpers/common.js +7 -7
  56. package/lib/helpers/cursor/eachAsync.js +14 -11
  57. package/lib/helpers/cursor/waitForInitialization.js +17 -0
  58. package/lib/helpers/discriminator/applyEmbeddedDiscriminators.js +36 -0
  59. package/lib/helpers/discriminator/areDiscriminatorValuesEqual.js +1 -1
  60. package/lib/helpers/discriminator/getConstructor.js +9 -6
  61. package/lib/helpers/discriminator/getDiscriminatorByKey.js +1 -1
  62. package/lib/helpers/discriminator/getDiscriminatorByValue.js +1 -1
  63. package/lib/helpers/discriminator/getDiscriminatorValueFromFilter.js +30 -0
  64. package/lib/helpers/discriminator/getSchemaDiscriminatorByValue.js +1 -1
  65. package/lib/helpers/discriminator/mergeDiscriminatorSchema.js +41 -9
  66. package/lib/helpers/document/applyDefaults.js +82 -14
  67. package/lib/helpers/document/applyTimestamps.js +106 -0
  68. package/lib/helpers/document/applyVirtuals.js +147 -0
  69. package/lib/helpers/document/cleanModifiedSubpaths.js +14 -4
  70. package/lib/helpers/document/compile.js +20 -15
  71. package/lib/helpers/document/getDeepestSubdocumentForPath.js +38 -0
  72. package/lib/helpers/document/getEmbeddedDiscriminatorPath.js +6 -3
  73. package/lib/helpers/document/handleSpreadDoc.js +2 -1
  74. package/lib/helpers/document/isInPathsToSave.js +24 -0
  75. package/lib/helpers/document/toObjectRecursive.js +49 -0
  76. package/lib/helpers/get.js +1 -1
  77. package/lib/helpers/getDefaultBulkwriteResult.js +11 -20
  78. package/lib/helpers/getInheritedProperty.js +28 -0
  79. package/lib/helpers/getOwnProperty.js +19 -0
  80. package/lib/helpers/indexes/applySchemaCollation.js +1 -1
  81. package/lib/helpers/indexes/decorateDiscriminatorIndexOptions.js +1 -1
  82. package/lib/helpers/indexes/getRelatedIndexes.js +8 -4
  83. package/lib/helpers/indexes/isDefaultIdIndex.js +1 -1
  84. package/lib/helpers/indexes/isIndexEqual.js +13 -12
  85. package/lib/helpers/indexes/isIndexSpecEqual.js +32 -0
  86. package/lib/helpers/indexes/isTimeseriesIndex.js +16 -0
  87. package/lib/helpers/isBsonType.js +3 -6
  88. package/lib/helpers/isMongooseDocument.js +24 -0
  89. package/lib/helpers/isMongooseObject.js +6 -4
  90. package/lib/helpers/isObject.js +2 -2
  91. package/lib/helpers/isPOJO.js +12 -0
  92. package/lib/helpers/isSimpleValidator.js +2 -2
  93. package/lib/helpers/minimize.js +41 -0
  94. package/lib/helpers/model/applyDefaultsToPOJO.js +2 -2
  95. package/lib/helpers/model/applyHooks.js +72 -54
  96. package/lib/helpers/model/applyMethods.js +3 -3
  97. package/lib/helpers/model/applyStaticHooks.js +20 -50
  98. package/lib/helpers/model/castBulkWrite.js +278 -172
  99. package/lib/helpers/model/decorateBulkWriteResult.js +8 -0
  100. package/lib/helpers/model/discriminator.js +77 -21
  101. package/lib/helpers/omitUndefined.js +20 -0
  102. package/lib/helpers/parallelLimit.js +61 -34
  103. package/lib/helpers/path/setDottedPath.js +1 -1
  104. package/lib/helpers/pathTrie.js +167 -0
  105. package/lib/helpers/pluralize.js +5 -4
  106. package/lib/helpers/populate/assignRawDocsToIdStructure.js +12 -7
  107. package/lib/helpers/populate/assignVals.js +46 -21
  108. package/lib/helpers/populate/createPopulateQueryFilter.js +13 -5
  109. package/lib/helpers/populate/getModelsMapForPopulate.js +250 -108
  110. package/lib/helpers/populate/getSchemaTypes.js +27 -30
  111. package/lib/helpers/populate/getVirtual.js +31 -0
  112. package/lib/helpers/populate/markArraySubdocsPopulated.js +6 -4
  113. package/lib/helpers/populate/modelNamesFromRefPath.js +11 -5
  114. package/lib/helpers/populate/removeDeselectedForeignField.js +3 -2
  115. package/lib/helpers/populate/setInheritedReadOptions.js +21 -0
  116. package/lib/helpers/populate/setPopulatedVirtualValue.js +33 -0
  117. package/lib/helpers/populate/splitPopulateQuery.js +81 -0
  118. package/lib/helpers/printJestWarning.js +1 -1
  119. package/lib/helpers/processConnectionOptions.js +7 -2
  120. package/lib/helpers/projection/applyProjection.js +8 -2
  121. package/lib/helpers/projection/hasIncludedChildren.js +1 -1
  122. package/lib/helpers/projection/isExclusive.js +8 -6
  123. package/lib/helpers/projection/isInclusive.js +2 -1
  124. package/lib/helpers/projection/isPathExcluded.js +3 -3
  125. package/lib/helpers/projection/isPathSelectedInclusive.js +1 -11
  126. package/lib/helpers/projection/isSubpath.js +1 -1
  127. package/lib/helpers/projection/parseProjection.js +9 -4
  128. package/lib/helpers/query/applyGlobalOption.js +9 -9
  129. package/lib/helpers/query/cast$expr.js +52 -23
  130. package/lib/helpers/query/castFilterPath.js +22 -22
  131. package/lib/helpers/query/castUpdate.js +207 -79
  132. package/lib/helpers/query/cloneMongooseOptions.js +44 -0
  133. package/lib/helpers/query/getEmbeddedDiscriminatorPath.js +27 -13
  134. package/lib/helpers/query/handleImmutable.js +18 -2
  135. package/lib/helpers/query/handleReadPreferenceAliases.js +23 -0
  136. package/lib/helpers/query/sanitizeFilter.js +3 -2
  137. package/lib/helpers/query/selectPopulatedFields.js +13 -0
  138. package/lib/helpers/query/validOps.js +1 -22
  139. package/lib/helpers/schema/applyPlugins.js +2 -2
  140. package/lib/helpers/schema/applyReadConcern.js +20 -0
  141. package/lib/helpers/schema/applyWriteConcern.js +12 -3
  142. package/lib/helpers/schema/cleanPositionalOperators.js +5 -3
  143. package/lib/helpers/schema/getIndexes.js +20 -13
  144. package/lib/helpers/schema/getKeysInSchemaOrder.js +13 -16
  145. package/lib/helpers/schema/getPath.js +11 -3
  146. package/lib/helpers/schema/getSubdocumentStrictValue.js +32 -0
  147. package/lib/helpers/schema/handleIdOption.js +1 -1
  148. package/lib/helpers/schema/idGetter.js +7 -2
  149. package/lib/helpers/schema/merge.js +9 -1
  150. package/lib/helpers/schematype/getConditionalHandler.js +23 -0
  151. package/lib/helpers/schematype/handleImmutable.js +1 -1
  152. package/lib/helpers/setDefaultsOnInsert.js +85 -43
  153. package/lib/helpers/symbols.js +4 -4
  154. package/lib/helpers/timestamps/setDocumentTimestamps.js +2 -2
  155. package/lib/helpers/timestamps/setupTimestamps.js +69 -37
  156. package/lib/helpers/update/applyTimestampsToChildren.js +1 -1
  157. package/lib/helpers/update/applyTimestampsToUpdate.js +53 -37
  158. package/lib/helpers/update/castArrayFilters.js +68 -29
  159. package/lib/helpers/update/decorateUpdateWithVersionKey.js +35 -0
  160. package/lib/helpers/update/modifiedPaths.js +2 -2
  161. package/lib/helpers/update/removeUnusedArrayFilters.js +11 -2
  162. package/lib/helpers/updateValidators.js +87 -128
  163. package/lib/index.js +6 -1320
  164. package/lib/internal.js +7 -1
  165. package/lib/model.js +2587 -2618
  166. package/lib/modifiedPathsSnapshot.js +9 -0
  167. package/lib/mongoose.js +1456 -0
  168. package/lib/options/saveOptions.js +2 -0
  169. package/lib/options/{SchemaArrayOptions.js → schemaArrayOptions.js} +16 -5
  170. package/lib/options/{SchemaBufferOptions.js → schemaBufferOptions.js} +2 -2
  171. package/lib/options/{SchemaDateOptions.js → schemaDateOptions.js} +1 -1
  172. package/lib/options/{SchemaDocumentArrayOptions.js → schemaDocumentArrayOptions.js} +24 -1
  173. package/lib/options/{SchemaMapOptions.js → schemaMapOptions.js} +1 -1
  174. package/lib/options/{SchemaNumberOptions.js → schemaNumberOptions.js} +5 -5
  175. package/lib/options/{SchemaObjectIdOptions.js → schemaObjectIdOptions.js} +4 -4
  176. package/lib/options/{SchemaStringOptions.js → schemaStringOptions.js} +10 -10
  177. package/lib/options/schemaSubdocumentOptions.js +89 -0
  178. package/lib/options/{SchemaTypeOptions.js → schemaTypeOptions.js} +28 -14
  179. package/lib/options/schemaUnionOptions.js +32 -0
  180. package/lib/options/{VirtualOptions.js → virtualOptions.js} +13 -13
  181. package/lib/options.js +4 -1
  182. package/lib/plugins/index.js +0 -2
  183. package/lib/plugins/saveSubdocs.js +85 -50
  184. package/lib/plugins/sharding.js +43 -15
  185. package/lib/plugins/trackTransaction.js +46 -34
  186. package/lib/query.js +1844 -1909
  187. package/lib/{queryhelpers.js → queryHelpers.js} +184 -81
  188. package/lib/schema/array.js +229 -169
  189. package/lib/schema/bigint.js +281 -0
  190. package/lib/schema/boolean.js +90 -26
  191. package/lib/schema/buffer.js +119 -50
  192. package/lib/schema/date.js +102 -38
  193. package/lib/schema/decimal128.js +88 -37
  194. package/lib/schema/{documentarray.js → documentArray.js} +259 -151
  195. package/lib/schema/documentArrayElement.js +180 -0
  196. package/lib/schema/double.js +244 -0
  197. package/lib/schema/index.js +12 -19
  198. package/lib/schema/int32.js +288 -0
  199. package/lib/schema/map.js +129 -20
  200. package/lib/schema/mixed.js +40 -26
  201. package/lib/schema/number.js +128 -51
  202. package/lib/schema/{objectid.js → objectId.js} +89 -47
  203. package/lib/schema/operators/exists.js +1 -1
  204. package/lib/schema/operators/geospatial.js +2 -2
  205. package/lib/schema/operators/text.js +4 -4
  206. package/lib/schema/string.js +125 -66
  207. package/lib/schema/subdocument.js +443 -0
  208. package/lib/schema/symbols.js +2 -0
  209. package/lib/schema/union.js +167 -0
  210. package/lib/schema/uuid.js +90 -120
  211. package/lib/schema.js +1267 -388
  212. package/lib/{schematype.js → schemaType.js} +481 -246
  213. package/lib/standardSchema/convertErrorToIssues.js +20 -0
  214. package/lib/{statemachine.js → stateMachine.js} +66 -17
  215. package/lib/tracing.js +38 -0
  216. package/lib/types/array/index.js +13 -10
  217. package/lib/types/array/methods/index.js +243 -63
  218. package/lib/types/{ArraySubdocument.js → arraySubdocument.js} +35 -14
  219. package/lib/types/buffer.js +31 -14
  220. package/lib/types/decimal128.js +1 -1
  221. package/lib/types/{DocumentArray → documentArray}/index.js +13 -13
  222. package/lib/types/{DocumentArray → documentArray}/methods/index.js +197 -31
  223. package/lib/types/double.js +13 -0
  224. package/lib/types/index.js +5 -2
  225. package/lib/types/map.js +62 -25
  226. package/lib/types/objectid.js +2 -2
  227. package/lib/types/subdocument.js +79 -58
  228. package/lib/types/uuid.js +13 -0
  229. package/lib/utils.js +201 -155
  230. package/lib/{validoptions.js → validOptions.js} +10 -2
  231. package/lib/{virtualtype.js → virtualType.js} +47 -18
  232. package/package.json +75 -92
  233. package/types/aggregate.d.ts +31 -7
  234. package/types/augmentations.d.ts +2 -2
  235. package/types/collection.d.ts +21 -16
  236. package/types/connection.d.ts +82 -27
  237. package/types/cursor.d.ts +15 -10
  238. package/types/document.d.ts +137 -56
  239. package/types/error.d.ts +11 -6
  240. package/types/expressions.d.ts +33 -2
  241. package/types/index.d.ts +805 -190
  242. package/types/indexes.d.ts +85 -13
  243. package/types/inferhydrateddoctype.d.ts +151 -0
  244. package/types/inferrawdoctype.d.ts +201 -0
  245. package/types/inferschematype.d.ts +287 -128
  246. package/types/middlewares.d.ts +50 -7
  247. package/types/models.d.ts +1555 -268
  248. package/types/mongooseoptions.d.ts +56 -7
  249. package/types/pipelinestage.d.ts +42 -3
  250. package/types/populate.d.ts +63 -1
  251. package/types/query.d.ts +592 -255
  252. package/types/schemaoptions.d.ts +78 -12
  253. package/types/schematypes.d.ts +254 -65
  254. package/types/session.d.ts +0 -4
  255. package/types/tracing.d.ts +10 -0
  256. package/types/types.d.ts +25 -8
  257. package/types/utility.d.ts +329 -30
  258. package/types/validation.d.ts +19 -14
  259. package/types/virtuals.d.ts +10 -10
  260. package/.eslintrc.js +0 -232
  261. package/.mocharc.yml +0 -4
  262. package/browser.js +0 -8
  263. package/lgtm.yml +0 -12
  264. package/lib/browser.js +0 -158
  265. package/lib/browserDocument.js +0 -101
  266. package/lib/cursor/ChangeStream.js +0 -154
  267. package/lib/cursor/QueryCursor.js +0 -545
  268. package/lib/document_provider.js +0 -30
  269. package/lib/drivers/browser/ReadPreference.js +0 -7
  270. package/lib/drivers/browser/binary.js +0 -14
  271. package/lib/drivers/browser/decimal128.js +0 -7
  272. package/lib/drivers/browser/index.js +0 -16
  273. package/lib/drivers/browser/objectid.js +0 -29
  274. package/lib/drivers/node-mongodb-native/ReadPreference.js +0 -47
  275. package/lib/drivers/node-mongodb-native/binary.js +0 -10
  276. package/lib/drivers/node-mongodb-native/decimal128.js +0 -7
  277. package/lib/drivers/node-mongodb-native/objectid.js +0 -16
  278. package/lib/error/disconnected.js +0 -33
  279. package/lib/helpers/printStrictQueryWarning.js +0 -11
  280. package/lib/helpers/promiseOrCallback.js +0 -55
  281. package/lib/helpers/query/applyQueryMiddleware.js +0 -79
  282. package/lib/helpers/query/completeMany.js +0 -52
  283. package/lib/helpers/query/wrapThunk.js +0 -36
  284. package/lib/options/SchemaSubdocumentOptions.js +0 -42
  285. package/lib/options/removeOptions.js +0 -14
  286. package/lib/plugins/removeSubdocs.js +0 -31
  287. package/lib/plugins/validateBeforeSave.js +0 -45
  288. package/lib/promise_provider.js +0 -49
  289. package/lib/schema/DocumentArrayElement.js +0 -100
  290. package/lib/schema/SubdocumentPath.js +0 -369
  291. package/scripts/build-browser.js +0 -18
  292. package/scripts/create-tarball.js +0 -7
  293. package/scripts/generateSearch.js +0 -154
  294. package/scripts/tsc-diagnostics-check.js +0 -15
  295. package/tools/auth.js +0 -31
  296. package/tools/repl.js +0 -35
  297. package/tools/sharded.js +0 -46
  298. package/tsconfig.json +0 -9
  299. /package/lib/{connectionstate.js → connectionState.js} +0 -0
  300. /package/lib/helpers/populate/{SkipPopulateValue.js → skipPopulateValue.js} +0 -0
  301. /package/lib/options/{PopulateOptions.js → populateOptions.js} +0 -0
  302. /package/lib/types/{DocumentArray → documentArray}/isMongooseDocumentArray.js +0 -0
package/types/index.d.ts CHANGED
@@ -20,13 +20,17 @@
20
20
  /// <reference path="./types.d.ts" />
21
21
  /// <reference path="./utility.d.ts" />
22
22
  /// <reference path="./validation.d.ts" />
23
+ /// <reference path="./inferhydrateddoctype.d.ts" />
24
+ /// <reference path="./inferrawdoctype.d.ts" />
23
25
  /// <reference path="./inferschematype.d.ts" />
24
26
  /// <reference path="./virtuals.d.ts" />
27
+ /// <reference path="./tracing.d.ts" />
25
28
  /// <reference path="./augmentations.d.ts" />
26
29
 
27
- declare class NativeDate extends global.Date { }
30
+ declare class NativeDate extends globalThis.Date { }
28
31
 
29
32
  declare module 'mongoose' {
33
+ import Kareem = require('kareem');
30
34
  import events = require('events');
31
35
  import mongodb = require('mongodb');
32
36
  import mongoose = require('mongoose');
@@ -40,7 +44,6 @@ declare module 'mongoose' {
40
44
  export const Mongoose: new (options?: MongooseOptions | null) => Mongoose;
41
45
 
42
46
  export let Promise: any;
43
- export const PromiseProvider: any;
44
47
 
45
48
  /**
46
49
  * Can be extended to explicitly type specific models.
@@ -63,11 +66,15 @@ declare module 'mongoose' {
63
66
  * Sanitizes query filters against query selector injection attacks by wrapping
64
67
  * any nested objects that have a property whose name starts with `$` in a `$eq`.
65
68
  */
66
- export function sanitizeFilter<T>(filter: FilterQuery<T>): FilterQuery<T>;
69
+ export function sanitizeFilter<T>(filter: QueryFilter<T>): QueryFilter<T>;
67
70
 
68
71
  /** Gets mongoose options */
69
72
  export function get<K extends keyof MongooseOptions>(key: K): MongooseOptions[K];
70
73
 
74
+ export function omitUndefined<T extends Record<string, any>>(val: T): T;
75
+
76
+ export type HydratedDocFromModel<M extends Model<any>> = ReturnType<M['hydrate']>;
77
+
71
78
  /* ! ignore */
72
79
  export type CompileModelOptions = {
73
80
  overwriteModels?: boolean,
@@ -80,18 +87,31 @@ declare module 'mongoose' {
80
87
  collection?: string,
81
88
  options?: CompileModelOptions
82
89
  ): Model<
83
- InferSchemaType<TSchema>,
84
- ObtainSchemaGeneric<TSchema, 'TQueryHelpers'>,
85
- ObtainSchemaGeneric<TSchema, 'TInstanceMethods'>,
86
- ObtainSchemaGeneric<TSchema, 'TVirtuals'>,
87
- TSchema
90
+ InferSchemaType<TSchema>,
91
+ ObtainSchemaGeneric<TSchema, 'TQueryHelpers'>,
92
+ ObtainSchemaGeneric<TSchema, 'TInstanceMethods'>,
93
+ ObtainSchemaGeneric<TSchema, 'TVirtuals'>,
94
+ // If first schema generic param is set, that means we have an explicit raw doc type,
95
+ // so user should also specify a hydrated doc type if the auto inferred one isn't correct.
96
+ IsItRecordAndNotAny<ObtainSchemaGeneric<TSchema, 'EnforcedDocType'>> extends true
97
+ ? ObtainSchemaGeneric<TSchema, 'THydratedDocumentType'>
98
+ : HydratedDocument<
99
+ InferSchemaType<TSchema>,
100
+ ObtainSchemaGeneric<TSchema, 'TVirtuals'> & ObtainSchemaGeneric<TSchema, 'TInstanceMethods'>,
101
+ ObtainSchemaGeneric<TSchema, 'TQueryHelpers'>,
102
+ ObtainSchemaGeneric<TSchema, 'TVirtuals'>,
103
+ InferSchemaType<TSchema>,
104
+ ObtainSchemaGeneric<TSchema, 'TSchemaOptions'>
105
+ >,
106
+ TSchema,
107
+ Default__v<Require_id<ObtainSchemaGeneric<TSchema, 'TLeanResultType'>>>
88
108
  > & ObtainSchemaGeneric<TSchema, 'TStaticMethods'>;
89
109
 
90
110
  export function model<T>(name: string, schema?: Schema<T, any, any> | Schema<T & Document, any, any>, collection?: string, options?: CompileModelOptions): Model<T>;
91
111
 
92
112
  export function model<T, U, TQueryHelpers = {}>(
93
113
  name: string,
94
- schema?: Schema<T, any, any, TQueryHelpers, any, any>,
114
+ schema?: Schema<T, any, any, TQueryHelpers, any, any, any>,
95
115
  collection?: string,
96
116
  options?: CompileModelOptions
97
117
  ): U;
@@ -106,7 +126,7 @@ declare module 'mongoose' {
106
126
  export function setDriver(driver: any): Mongoose;
107
127
 
108
128
  /** The node-mongodb-native driver Mongoose uses. */
109
- export const mongo: typeof mongodb;
129
+ export { mongodb as mongo };
110
130
 
111
131
  /** Declares a global plugin executed on all Schemas. */
112
132
  export function plugin(fn: (schema: Schema, opts?: any) => void, opts?: any): Mongoose;
@@ -130,51 +150,147 @@ declare module 'mongoose' {
130
150
  ? IfAny<U, T & { _id: Types.ObjectId }, T & Required<{ _id: U }>>
131
151
  : T & { _id: Types.ObjectId };
132
152
 
133
- export type HydratedDocument<DocType, TMethodsAndOverrides = {}, TVirtuals = {}> = DocType extends Document ?
134
- Require_id<DocType> :
135
- Document<unknown, any, DocType> & MergeType<Require_id<DocType>, TVirtuals & TMethodsAndOverrides>;
153
+ export type Default_id<T, TSchemaOptions = {}> = TSchemaOptions extends { _id: false } ? T : Require_id<T>;
154
+
155
+ export type Default__v<T, TSchemaOptions = {}> = TSchemaOptions extends { versionKey: false }
156
+ ? T
157
+ : TSchemaOptions extends { versionKey: infer VK }
158
+ ? (
159
+ // If VK is a *literal* string, add that property
160
+ T & {
161
+ [K in VK as K extends string
162
+ ? (string extends K ? never : K) // drop if wide string
163
+ : never
164
+ ]: number
165
+ }
166
+ )
167
+ : T extends { __v?: infer U }
168
+ ? T
169
+ : T & { __v: number };
170
+
171
+ /** Helper type for getting the hydrated document type from the raw document type. The hydrated document type is what `new MyModel()` returns. */
172
+ export type HydratedDocument<
173
+ HydratedDocPathsType,
174
+ TOverrides = {},
175
+ TQueryHelpers = {},
176
+ TVirtuals = {},
177
+ RawDocType = HydratedDocPathsType,
178
+ TSchemaOptions = DefaultSchemaOptions
179
+ > = IfAny<
180
+ HydratedDocPathsType,
181
+ any,
182
+ TOverrides extends Record<string, never> ?
183
+ Document<unknown, TQueryHelpers, RawDocType, TVirtuals, TSchemaOptions> &
184
+ Default__v<Require_id<HydratedDocPathsType>, TSchemaOptions> &
185
+ IfEquals<
186
+ TVirtuals,
187
+ {},
188
+ AddDefaultId<HydratedDocPathsType, {}, TSchemaOptions>,
189
+ TVirtuals
190
+ > :
191
+ IfAny<
192
+ TOverrides,
193
+ Document<unknown, TQueryHelpers, RawDocType, TVirtuals, TSchemaOptions> & Default__v<Require_id<HydratedDocPathsType>, TSchemaOptions>,
194
+ Document<unknown, TQueryHelpers, RawDocType, TVirtuals, TSchemaOptions> & MergeType<
195
+ Default__v<Require_id<HydratedDocPathsType>, TSchemaOptions>,
196
+ HydratedDocumentOverrides<
197
+ IfEquals<
198
+ TOverrides,
199
+ {},
200
+ TOverrides,
201
+ TOverrides & AddDefaultId<HydratedDocPathsType, TVirtuals, TSchemaOptions>
202
+ >
203
+ >
204
+ >
205
+ >
206
+ >;
207
+
208
+ export type HydratedSingleSubdocument<
209
+ DocType,
210
+ TOverrides = {}
211
+ > = IfAny<
212
+ DocType,
213
+ any,
214
+ TOverrides extends Record<string, never> ?
215
+ Types.Subdocument<unknown, Record<string, never>, DocType> & Require_id<DocType> :
216
+ IfAny<
217
+ TOverrides,
218
+ Types.Subdocument<unknown, Record<string, never>, DocType> & Require_id<DocType>,
219
+ Types.Subdocument<unknown, Record<string, never>, DocType> & MergeType<
220
+ Require_id<DocType>,
221
+ TOverrides
222
+ >
223
+ >
224
+ >;
225
+ export type HydratedArraySubdocument<DocType, TOverrides = {}> = IfAny<
226
+ DocType,
227
+ any,
228
+ TOverrides extends Record<string, never> ?
229
+ Types.ArraySubdocument<unknown, Record<string, never>, DocType> & Require_id<DocType> :
230
+ IfAny<
231
+ TOverrides,
232
+ Types.ArraySubdocument<unknown, Record<string, never>, DocType> & Require_id<DocType>,
233
+ Types.ArraySubdocument<unknown, Record<string, never>, DocType> & MergeType<
234
+ Require_id<DocType>,
235
+ TOverrides
236
+ >
237
+ >
238
+ >;
136
239
 
137
240
  export type HydratedDocumentFromSchema<TSchema extends Schema> = HydratedDocument<
138
- InferSchemaType<TSchema>,
139
- ObtainSchemaGeneric<TSchema, 'TInstanceMethods'>,
140
- ObtainSchemaGeneric<TSchema, 'TVirtuals'>
241
+ InferSchemaType<TSchema>,
242
+ ObtainSchemaGeneric<TSchema, 'TInstanceMethods'> & ObtainSchemaGeneric<TSchema, 'TVirtuals'>,
243
+ ObtainSchemaGeneric<TSchema, 'TQueryHelpers'>,
244
+ ObtainSchemaGeneric<TSchema, 'TVirtuals'>,
245
+ InferSchemaType<TSchema>,
246
+ ObtainSchemaGeneric<TSchema, 'TSchemaOptions'>
141
247
  >;
142
248
 
143
249
  export interface TagSet {
144
250
  [k: string]: string;
145
251
  }
146
252
 
147
- export interface ToObjectOptions {
148
- /** apply all getters (path and virtual getters) */
149
- getters?: boolean;
150
- /** apply virtual getters (can override getters option) */
151
- virtuals?: boolean | string[];
253
+ export interface ToObjectOptions<RawDocType = unknown, THydratedDocumentType = HydratedDocument<RawDocType>> {
152
254
  /** if `options.virtuals = true`, you can set `options.aliases = false` to skip applying aliases. This option is a no-op if `options.virtuals = false`. */
153
255
  aliases?: boolean;
154
- /** remove empty objects (defaults to true) */
155
- minimize?: boolean;
156
- /** if set, mongoose will call this function to allow you to transform the returned object */
157
- transform?: boolean | ((doc: any, ret: any, options: any) => any);
158
256
  /** if true, replace any conventionally populated paths with the original id in the output. Has no affect on virtual populated paths. */
159
257
  depopulate?: boolean;
160
- /** if false, exclude the version key (`__v` by default) from the output */
161
- versionKey?: boolean;
162
258
  /** if true, convert Maps to POJOs. Useful if you want to `JSON.stringify()` the result of `toObject()`. */
163
259
  flattenMaps?: boolean;
260
+ /** if true, convert any ObjectIds in the result to 24 character hex strings. */
261
+ flattenObjectIds?: boolean;
262
+ /** if true, convert any UUIDs in the result to 36 character hex strings. */
263
+ flattenUUIDs?: boolean;
264
+ /** apply all getters (path and virtual getters) */
265
+ getters?: boolean;
266
+ /** remove empty objects (defaults to true) */
267
+ minimize?: boolean;
268
+ /** If true, the resulting object will only have fields that are defined in the document's schema. By default, `toJSON()` & `toObject()` returns all fields in the underlying document from MongoDB, including ones that are not listed in the schema. */
269
+ schemaFieldsOnly?: boolean;
270
+ /** if set, mongoose will call this function to allow you to transform the returned object */
271
+ transform?: boolean | ((
272
+ doc: THydratedDocumentType,
273
+ ret: Default__v<Require_id<RawDocType>>,
274
+ options: ToObjectOptions<THydratedDocumentType>
275
+ ) => any);
164
276
  /** If true, omits fields that are excluded in this document's projection. Unless you specified a projection, this will omit any field that has `select: false` in the schema. */
165
277
  useProjection?: boolean;
278
+ /** if false, exclude the version key (`__v` by default) from the output */
279
+ versionKey?: boolean;
280
+ /** apply virtual getters (can override getters option) */
281
+ virtuals?: boolean | string[];
166
282
  }
167
283
 
168
- export type DiscriminatorModel<M, T> = T extends Model<infer T1, infer T2, infer T3, infer T4>
284
+ export type DiscriminatorModel<M, T> = T extends Model<infer T, infer TQueryHelpers, infer TInstanceMethods, infer TVirtuals>
169
285
  ?
170
- M extends Model<infer M1, infer M2, infer M3, infer M4>
171
- ? Model<Omit<M1, keyof T1> & T1, M2 | T2, M3 | T3, M4 | T4>
286
+ M extends Model<infer M, infer MQueryHelpers, infer MInstanceMethods, infer MVirtuals>
287
+ ? Model<Omit<M, keyof T> & T, MQueryHelpers | TQueryHelpers, MInstanceMethods | TInstanceMethods, MVirtuals | TVirtuals>
172
288
  : M
173
289
  : M;
174
290
 
175
291
  export type DiscriminatorSchema<DocType, M, TInstanceMethods, TQueryHelpers, TVirtuals, TStaticMethods, DisSchema> =
176
292
  DisSchema extends Schema<infer DisSchemaEDocType, infer DisSchemaM, infer DisSchemaInstanceMethods, infer DisSchemaQueryhelpers, infer DisSchemaVirtuals, infer DisSchemaStatics>
177
- ? Schema<Omit<DocType, keyof DisSchemaEDocType> & DisSchemaEDocType, DiscriminatorModel<DisSchemaM, M>, DisSchemaInstanceMethods | TInstanceMethods, DisSchemaQueryhelpers | TQueryHelpers, DisSchemaVirtuals | TVirtuals, DisSchemaStatics & TStaticMethods>
293
+ ? Schema<MergeType<DocType, DisSchemaEDocType>, DiscriminatorModel<DisSchemaM, M>, DisSchemaInstanceMethods | TInstanceMethods, DisSchemaQueryhelpers | TQueryHelpers, DisSchemaVirtuals | TVirtuals, DisSchemaStatics & TStaticMethods>
178
294
  : Schema<DocType, M, TInstanceMethods, TQueryHelpers, TVirtuals, TStaticMethods>;
179
295
 
180
296
  type QueryResultType<T> = T extends Query<infer ResultType, any> ? ResultType : never;
@@ -188,23 +304,132 @@ declare module 'mongoose' {
188
304
  TStaticMethods> = (schema: Schema<DocType, M, TInstanceMethods, TQueryHelpers, TVirtuals, TStaticMethods>, opts?: any) => void;
189
305
 
190
306
  export class Schema<
191
- EnforcedDocType = any,
192
- M = Model<EnforcedDocType, any, any, any>,
307
+ RawDocType = any,
308
+ TModelType = Model<RawDocType, any, any, any>,
193
309
  TInstanceMethods = {},
194
310
  TQueryHelpers = {},
195
311
  TVirtuals = {},
196
312
  TStaticMethods = {},
197
- TSchemaOptions extends ResolveSchemaOptions<TSchemaOptions> = DefaultSchemaOptions,
198
- DocType extends ApplySchemaOptions<ObtainDocumentType<DocType, EnforcedDocType, TSchemaOptions>, TSchemaOptions> = ApplySchemaOptions<ObtainDocumentType<any, EnforcedDocType, TSchemaOptions>, TSchemaOptions>,
313
+ TSchemaOptions = DefaultSchemaOptions,
314
+ DocType extends ApplySchemaOptions<
315
+ ObtainDocumentType<DocType, RawDocType, ResolveSchemaOptions<TSchemaOptions>>,
316
+ ResolveSchemaOptions<TSchemaOptions>
317
+ > = ApplySchemaOptions<
318
+ ObtainDocumentType<any, RawDocType, ResolveSchemaOptions<TSchemaOptions>>,
319
+ ResolveSchemaOptions<TSchemaOptions>
320
+ >,
321
+ THydratedDocumentType = HydratedDocument<
322
+ DocType,
323
+ AddDefaultId<DocType, TVirtuals, TSchemaOptions> & TInstanceMethods,
324
+ TQueryHelpers,
325
+ AddDefaultId<DocType, TVirtuals, TSchemaOptions>,
326
+ IsItRecordAndNotAny<RawDocType> extends true ? RawDocType : DocType,
327
+ ResolveSchemaOptions<TSchemaOptions>
328
+ >,
329
+ TSchemaDefinition = IfAny<RawDocType, unknown, SchemaDefinition<SchemaDefinitionType<RawDocType>, RawDocType, THydratedDocumentType>>,
330
+ LeanResultType = IsItRecordAndNotAny<RawDocType> extends true ? RawDocType : Default__v<Require_id<BufferToBinary<FlattenMaps<DocType>>>>
199
331
  >
200
332
  extends events.EventEmitter {
201
333
  /**
202
334
  * Create a new schema
203
335
  */
204
- constructor(definition?: SchemaDefinition<SchemaDefinitionType<EnforcedDocType>> | DocType, options?: SchemaOptions<FlatRecord<DocType>, TInstanceMethods, TQueryHelpers, TStaticMethods, TVirtuals> | TSchemaOptions);
336
+ constructor(
337
+ definition?: SchemaDefinition<SchemaDefinitionType<RawDocType>, RawDocType, THydratedDocumentType> | DocType,
338
+ options?: SchemaOptions<
339
+ FlatRecord<DocType>,
340
+ TInstanceMethods,
341
+ TQueryHelpers,
342
+ TStaticMethods,
343
+ TVirtuals,
344
+ THydratedDocumentType,
345
+ IfEquals<
346
+ TModelType,
347
+ Model<any, any, any, any>,
348
+ Model<DocType, TQueryHelpers, TInstanceMethods, TVirtuals, THydratedDocumentType>,
349
+ TModelType
350
+ >
351
+ > | ResolveSchemaOptions<TSchemaOptions>
352
+ );
353
+
354
+ /* Creates a new schema with the given definition and options. Equivalent to `new Schema(definition, options)`, but with better automatic type inference. */
355
+ static create<
356
+ TSchemaDefinition extends SchemaDefinition<undefined, RawDocType, THydratedDocumentType>,
357
+ TSchemaOptions extends DefaultSchemaOptions,
358
+ RawDocType extends ApplySchemaOptions<
359
+ InferRawDocType<TSchemaDefinition, ResolveSchemaOptions<TSchemaOptions>>,
360
+ ResolveSchemaOptions<TSchemaOptions>
361
+ >,
362
+ THydratedDocumentType extends AnyObject = HydratedDocument<
363
+ InferHydratedDocType<TSchemaDefinition, ResolveSchemaOptions<TSchemaOptions>>,
364
+ TSchemaOptions extends { methods: infer M } ? M : {},
365
+ TSchemaOptions extends { query: any } ? TSchemaOptions['query'] : {},
366
+ ResolveVirtuals<TSchemaOptions, RawDocType>,
367
+ RawDocType,
368
+ ResolveSchemaOptions<TSchemaOptions>
369
+ >
370
+ >(def: TSchemaDefinition): Schema<
371
+ RawDocType,
372
+ Model<RawDocType, any, any, any>,
373
+ TSchemaOptions extends { methods: infer M } ? M : {},
374
+ TSchemaOptions extends { query: any } ? TSchemaOptions['query'] : {},
375
+ ResolveVirtuals<TSchemaOptions, RawDocType>,
376
+ TSchemaOptions extends { statics: any } ? TSchemaOptions['statics'] : {},
377
+ TSchemaOptions,
378
+ ApplySchemaOptions<
379
+ ObtainDocumentType<any, RawDocType, ResolveSchemaOptions<TSchemaOptions>>,
380
+ ResolveSchemaOptions<TSchemaOptions>
381
+ >,
382
+ THydratedDocumentType,
383
+ TSchemaDefinition,
384
+ ApplySchemaOptions<
385
+ InferRawDocType<TSchemaDefinition, ResolveSchemaOptions<TSchemaOptions>, { bufferToBinary: true }>,
386
+ ResolveSchemaOptions<TSchemaOptions>
387
+ >
388
+ >;
389
+
390
+ static create<
391
+ TSchemaDefinition extends SchemaDefinition<undefined, RawDocType, any>,
392
+ TSchemaOptions extends SchemaOptions<InferRawDocType<TSchemaDefinition>>,
393
+ RawDocType extends ApplySchemaOptions<
394
+ InferRawDocType<TSchemaDefinition, ResolveSchemaOptions<TSchemaOptions>>,
395
+ ResolveSchemaOptions<TSchemaOptions>
396
+ >,
397
+ TMethods = TSchemaOptions extends { methods: infer M } ? { [K in keyof M]: OmitThisParameter<M[K]> } : {},
398
+ TStatics = TSchemaOptions extends { statics: infer S } ? { [K in keyof S]: OmitThisParameter<S[K]> } : {}
399
+ >(def: TSchemaDefinition, options: TSchemaOptions & {
400
+ statics?: SchemaOptionsStaticsPropertyType<
401
+ TStatics,
402
+ Model<RawDocType>
403
+ >
404
+ }): Schema<
405
+ RawDocType,
406
+ Model<RawDocType, any, any, any>,
407
+ TMethods,
408
+ TSchemaOptions extends { query: any } ? TSchemaOptions['query'] : {},
409
+ ResolveVirtuals<TSchemaOptions, RawDocType>,
410
+ TStatics,
411
+ TSchemaOptions,
412
+ ApplySchemaOptions<
413
+ ObtainDocumentType<any, RawDocType, ResolveSchemaOptions<TSchemaOptions>>,
414
+ ResolveSchemaOptions<TSchemaOptions>
415
+ >,
416
+ HydratedDocument<
417
+ InferHydratedDocType<TSchemaDefinition, ResolveSchemaOptions<TSchemaOptions>>,
418
+ TMethods,
419
+ TSchemaOptions extends { query: any } ? TSchemaOptions['query'] : {},
420
+ ResolveVirtuals<TSchemaOptions, RawDocType>,
421
+ RawDocType,
422
+ ResolveSchemaOptions<TSchemaOptions>
423
+ >,
424
+ TSchemaDefinition,
425
+ ApplySchemaOptions<
426
+ InferRawDocType<TSchemaDefinition, ResolveSchemaOptions<TSchemaOptions>, { bufferToBinary: true }>,
427
+ ResolveSchemaOptions<TSchemaOptions>
428
+ >
429
+ >;
205
430
 
206
431
  /** Adds key path / schema type pairs to this schema. */
207
- add(obj: SchemaDefinition<SchemaDefinitionType<EnforcedDocType>> | Schema, prefix?: string): this;
432
+ add(obj: SchemaDefinition<SchemaDefinitionType<RawDocType>, RawDocType> | Schema, prefix?: string): this;
208
433
 
209
434
  /**
210
435
  * Add an alias for `path`. This means getting or setting the `alias`
@@ -223,9 +448,9 @@ declare module 'mongoose' {
223
448
  clearIndexes(): this;
224
449
 
225
450
  /** Returns a copy of this schema */
226
- clone<T = this>(): T;
451
+ clone(): this;
227
452
 
228
- discriminator<DisSchema = Schema>(name: string, schema: DisSchema): this;
453
+ discriminator<DisSchema = Schema>(name: string | number, schema: DisSchema, options?: DiscriminatorOptions): this;
229
454
 
230
455
  /** Returns a new schema that has the picked `paths` from this schema. */
231
456
  pick<T = this>(paths: string[], options?: SchemaOptions): T;
@@ -237,13 +462,20 @@ declare module 'mongoose' {
237
462
  eachPath(fn: (path: string, type: SchemaType) => void): this;
238
463
 
239
464
  /** Defines an index (most likely compound) for this schema. */
240
- index(fields: IndexDefinition, options?: IndexOptions): this;
465
+ index(fields: IndexDefinition, options?: Omit<IndexOptions, 'unique'> & { unique?: boolean | [true, string] }): this;
466
+
467
+ /**
468
+ * Define a search index for this schema.
469
+ *
470
+ * @remarks Search indexes are only supported when used against a 7.0+ Mongo Atlas cluster.
471
+ */
472
+ searchIndex(description: SearchIndexDescription): this;
241
473
 
242
474
  /**
243
475
  * Returns a list of indexes that this schema declares, via `schema.index()`
244
476
  * or by `index: true` in a path's options.
245
477
  */
246
- indexes(): Array<IndexDefinition>;
478
+ indexes(): Array<[IndexDefinition, IndexOptions]>;
247
479
 
248
480
  /** Gets a schema option. */
249
481
  get<K extends keyof SchemaOptions>(key: K): SchemaOptions[K];
@@ -258,18 +490,41 @@ declare module 'mongoose' {
258
490
  loadClass(model: Function, onlyVirtuals?: boolean): this;
259
491
 
260
492
  /** Adds an instance method to documents constructed from Models compiled from this schema. */
261
- method<Context = any>(name: string, fn: (this: Context, ...args: any[]) => any, opts?: any): this;
493
+ method<Context = THydratedDocumentType>(name: string, fn: (this: Context, ...args: any[]) => any, opts?: any): this;
262
494
  method(obj: Partial<TInstanceMethods>): this;
263
495
 
496
+ /** Adds a query helper to this schema. */
497
+ queryHelper<Name extends string, Fn extends (this: QueryWithHelpers<any, DocType, TQueryHelpers, RawDocType>, ...args: any[]) => any>(
498
+ name: Name,
499
+ fn: Fn
500
+ ): Schema<
501
+ RawDocType,
502
+ TModelType,
503
+ TInstanceMethods,
504
+ TQueryHelpers & { [K in Name]: Fn },
505
+ TVirtuals,
506
+ TStaticMethods,
507
+ TSchemaOptions,
508
+ DocType,
509
+ THydratedDocumentType,
510
+ TSchemaDefinition,
511
+ LeanResultType
512
+ >;
513
+
264
514
  /** Object of currently defined methods on this schema. */
265
- methods: { [F in keyof TInstanceMethods]: TInstanceMethods[F] } & AnyObject;
515
+ methods: AddThisParameter<TInstanceMethods, THydratedDocumentType> & AnyObject;
266
516
 
267
517
  /** The original object passed to the schema constructor */
268
- obj: SchemaDefinition<SchemaDefinitionType<EnforcedDocType>>;
518
+ obj: SchemaDefinition<SchemaDefinitionType<RawDocType>, RawDocType>;
519
+
520
+ /** Returns a new schema that has the `paths` from the original schema, minus the omitted ones. */
521
+ omit<T = this>(paths: string[], options?: SchemaOptions): T;
522
+
523
+ options: SchemaOptions;
269
524
 
270
525
  /** Gets/sets schema paths. */
271
- path<ResultType extends SchemaType = SchemaType<any, HydratedDocument<DocType, TInstanceMethods>>>(path: string): ResultType;
272
- path<pathGeneric extends keyof EnforcedDocType>(path: pathGeneric): SchemaType<EnforcedDocType[pathGeneric]>;
526
+ path<ResultType extends SchemaType = SchemaType<any, THydratedDocumentType>>(path: string): ResultType;
527
+ path<pathGeneric extends keyof RawDocType>(path: pathGeneric): SchemaType<RawDocType[pathGeneric]>;
273
528
  path(path: string, constructor: any): this;
274
529
 
275
530
  /** Lists all paths and their type in the schema. */
@@ -281,53 +536,134 @@ declare module 'mongoose' {
281
536
  pathType(path: string): string;
282
537
 
283
538
  /** Registers a plugin for this schema. */
284
- plugin<PFunc extends PluginFunction<DocType, M, any, any, any, any>, POptions extends Parameters<PFunc>[1] = Parameters<PFunc>[1]>(fn: PFunc, opts?: POptions): this;
539
+ plugin<PFunc extends PluginFunction<DocType, TModelType, any, any, any, any>, POptions extends Parameters<PFunc>[1] = Parameters<PFunc>[1]>(fn: PFunc, opts?: POptions): this;
540
+ plugin<PFunc extends PluginFunction<DocType, Model<DocType, any, any, any, any, any>, any, any, any, any>, POptions extends Parameters<PFunc>[1] = Parameters<PFunc>[1]>(fn: PFunc, opts?: POptions): this;
285
541
 
286
542
  /** Defines a post hook for the model. */
543
+
544
+ // PostMiddlewareFunction
545
+ // with errorHandler set to true
287
546
  post<T = Query<any, any>>(method: MongooseQueryMiddleware | MongooseQueryMiddleware[] | RegExp, options: SchemaPostOptions & { errorHandler: true }, fn: ErrorHandlingMiddlewareWithOption<T>): this;
288
- post<T = HydratedDocument<DocType, TInstanceMethods>>(method: MongooseDocumentMiddleware | MongooseDocumentMiddleware[] | RegExp, options: SchemaPostOptions & { errorHandler: true }, fn: ErrorHandlingMiddlewareWithOption<T>): this;
547
+ post<T = THydratedDocumentType>(method: MongooseDocumentMiddleware | MongooseDocumentMiddleware[] | RegExp, options: SchemaPostOptions & { errorHandler: true }, fn: ErrorHandlingMiddlewareWithOption<T>): this;
289
548
  post<T extends Aggregate<any>>(method: 'aggregate' | RegExp, options: SchemaPostOptions & { errorHandler: true }, fn: ErrorHandlingMiddlewareWithOption<T, Array<any>>): this;
290
- post<T = M>(method: 'insertMany' | RegExp, options: SchemaPostOptions & { errorHandler: true }, fn: ErrorHandlingMiddlewareWithOption<T>): this;
291
-
292
- post<T = Query<any, any>>(method: MongooseQueryMiddleware | MongooseQueryMiddleware[] | RegExp, fn: PostMiddlewareFunction<T, QueryResultType<T>>): this;
293
- post<T = Query<any, any>>(method: MongooseQueryMiddleware | MongooseQueryMiddleware[] | RegExp, options: SchemaPostOptions, fn: PostMiddlewareFunction<T, QueryResultType<T>>): this;
294
- post<T = HydratedDocument<DocType, TInstanceMethods>>(method: MongooseDocumentMiddleware | MongooseDocumentMiddleware[] | RegExp, fn: PostMiddlewareFunction<T, T>): this;
295
- post<T = HydratedDocument<DocType, TInstanceMethods>>(method: MongooseDocumentMiddleware | MongooseDocumentMiddleware[] | RegExp, options: SchemaPostOptions, fn: PostMiddlewareFunction<T, T>): this;
549
+ post(method: 'insertMany' | RegExp, options: SchemaPostOptions & { errorHandler: true }, fn: ErrorHandlingMiddlewareWithOption<TModelType>): this;
550
+
551
+ // this = never since it never happens
552
+ post<T = never>(method: MongooseQueryOrDocumentMiddleware | MongooseQueryOrDocumentMiddleware[] | RegExp, options: SchemaPostOptions & { document: false, query: false }, fn: PostMiddlewareFunction<never, never>): this;
553
+ post<T = never>(method: MongooseDistinctQueryMiddleware|MongooseDistinctQueryMiddleware[], options: SchemaPostOptions & { document: boolean, query: false }, fn: PostMiddlewareFunction<T, QueryResultType<T>>): this;
554
+ post<T = never>(method: MongooseDistinctDocumentMiddleware | MongooseDistinctDocumentMiddleware[] | RegExp, options: SchemaPostOptions & { document: false, query: true }, fn: PostMiddlewareFunction<T, T>): this;
555
+ // this = Document
556
+ post<T = THydratedDocumentType>(method: MongooseDistinctDocumentMiddleware|MongooseDistinctDocumentMiddleware[], fn: PostMiddlewareFunction<T, T>): this;
557
+ post<T = THydratedDocumentType>(method: MongooseDistinctDocumentMiddleware|MongooseDistinctDocumentMiddleware[], options: SchemaPostOptions & SchemaPostOptions, fn: PostMiddlewareFunction<T, T>): this;
558
+ post<T = THydratedDocumentType>(method: MongooseQueryOrDocumentMiddleware | MongooseQueryOrDocumentMiddleware[] | RegExp, options: SchemaPostOptions & { document: true, query: false }, fn: PostMiddlewareFunction<T, T>): this;
559
+ post<T = THydratedDocumentType>(method: 'init', fn: PostMiddlewareFunction<T, T>): this;
560
+
561
+ // this = Query
562
+ post<T = Query<any, any>>(method: MongooseRawResultQueryMiddleware|MongooseRawResultQueryMiddleware[], fn: PostMiddlewareFunction<T, null | QueryResultType<T> | ModifyResult<QueryResultType<T>>>): this;
563
+ post<T = Query<any, any>>(method: MongooseDefaultQueryMiddleware|MongooseDefaultQueryMiddleware[], fn: PostMiddlewareFunction<T, QueryResultType<T>>): this;
564
+ post<T = Query<any, any>>(method: MongooseDistinctQueryMiddleware|MongooseDistinctQueryMiddleware[], options: SchemaPostOptions, fn: PostMiddlewareFunction<T, QueryResultType<T>>): this;
565
+ post<T = Query<any, any>>(method: MongooseQueryOrDocumentMiddleware | MongooseQueryOrDocumentMiddleware[] | RegExp, options: SchemaPostOptions & { document: false, query: true }, fn: PostMiddlewareFunction<T, QueryResultType<T>>): this;
566
+ // this = Union of Document and Query, could be called with any of them
567
+ post<T = THydratedDocumentType|Query<any, any>>(method: MongooseQueryOrDocumentMiddleware | MongooseQueryOrDocumentMiddleware[] | RegExp, options: SchemaPostOptions & { document: true, query: true }, fn: PostMiddlewareFunction<T, T|QueryResultType<T>>): this;
568
+ post<T = THydratedDocumentType|Query<any, any>>(method: MongooseQueryOrDocumentMiddleware | MongooseQueryOrDocumentMiddleware[] | RegExp, fn: PostMiddlewareFunction<T, T|QueryResultType<T>>): this;
569
+
570
+ // ErrorHandlingMiddlewareFunction
571
+ // this = never since it never happens
572
+ post<T = never>(method: MongooseDistinctQueryMiddleware|MongooseDistinctQueryMiddleware[], options: SchemaPostOptions & { document: boolean, query: false }, fn: ErrorHandlingMiddlewareFunction<T>): this;
573
+ post<T = never>(method: MongooseDistinctDocumentMiddleware|MongooseDistinctDocumentMiddleware[], options: SchemaPostOptions & { document: false, query: boolean }, fn: ErrorHandlingMiddlewareFunction<T>): this;
574
+ post<T = never>(method: MongooseQueryOrDocumentMiddleware | MongooseQueryOrDocumentMiddleware[] | RegExp, options: SchemaPostOptions & { document: false, query: false }, fn: ErrorHandlingMiddlewareFunction<T>): this;
575
+ // this = Document
576
+ post<T = THydratedDocumentType>(method: MongooseDistinctDocumentMiddleware|MongooseDistinctDocumentMiddleware[], fn: ErrorHandlingMiddlewareFunction<T>): this;
577
+ post<T = THydratedDocumentType>(method: MongooseDistinctDocumentMiddleware|MongooseDistinctDocumentMiddleware[], options: SchemaPostOptions, fn: ErrorHandlingMiddlewareFunction<T>): this;
578
+ post<T = THydratedDocumentType>(method: MongooseQueryOrDocumentMiddleware | MongooseQueryOrDocumentMiddleware[] | RegExp, options: SchemaPostOptions & { document: true, query: false }, fn: ErrorHandlingMiddlewareFunction<T>): this;
579
+ // this = Query
580
+ post<T = Query<any, any>>(method: MongooseDefaultQueryMiddleware|MongooseDefaultQueryMiddleware[], fn: ErrorHandlingMiddlewareFunction<T>): this;
581
+ post<T = Query<any, any>>(method: MongooseDistinctQueryMiddleware|MongooseDistinctQueryMiddleware[], options: SchemaPostOptions, fn: ErrorHandlingMiddlewareFunction<T>): this;
582
+ post<T = Query<any, any>>(method: MongooseQueryOrDocumentMiddleware | MongooseQueryOrDocumentMiddleware[] | RegExp, options: SchemaPostOptions & { document: false, query: true }, fn: ErrorHandlingMiddlewareFunction<T>): this;
583
+ // this = Union of Document and Query, could be called with any of them
584
+ post<T = THydratedDocumentType|Query<any, any>>(method: MongooseQueryOrDocumentMiddleware | MongooseQueryOrDocumentMiddleware[] | RegExp, options: SchemaPostOptions & { document: true, query: true }, fn: ErrorHandlingMiddlewareFunction<T>): this;
585
+ post<T = THydratedDocumentType|Query<any, any>>(method: MongooseQueryOrDocumentMiddleware | MongooseQueryOrDocumentMiddleware[] | RegExp, fn: ErrorHandlingMiddlewareFunction<T>): this;
586
+
587
+ // method aggregate and insertMany with PostMiddlewareFunction
296
588
  post<T extends Aggregate<any>>(method: 'aggregate' | RegExp, fn: PostMiddlewareFunction<T, Array<AggregateExtract<T>>>): this;
297
589
  post<T extends Aggregate<any>>(method: 'aggregate' | RegExp, options: SchemaPostOptions, fn: PostMiddlewareFunction<T, Array<AggregateExtract<T>>>): this;
298
- post<T = M>(method: 'insertMany' | RegExp, fn: PostMiddlewareFunction<T, T>): this;
299
- post<T = M>(method: 'insertMany' | RegExp, options: SchemaPostOptions, fn: PostMiddlewareFunction<T, T>): this;
590
+ post(method: 'insertMany' | RegExp, fn: PostMiddlewareFunction<TModelType, TModelType>): this;
591
+ post(method: 'insertMany' | RegExp, options: SchemaPostOptions, fn: PostMiddlewareFunction<TModelType, TModelType>): this;
300
592
 
301
- post<T = Query<any, any>>(method: MongooseQueryMiddleware | MongooseQueryMiddleware[] | RegExp, fn: ErrorHandlingMiddlewareFunction<T>): this;
302
- post<T = Query<any, any>>(method: MongooseQueryMiddleware | MongooseQueryMiddleware[] | RegExp, options: SchemaPostOptions, fn: ErrorHandlingMiddlewareFunction<T>): this;
303
- post<T = HydratedDocument<DocType, TInstanceMethods>>(method: MongooseDocumentMiddleware | MongooseDocumentMiddleware[] | RegExp, fn: ErrorHandlingMiddlewareFunction<T>): this;
304
- post<T = HydratedDocument<DocType, TInstanceMethods>>(method: MongooseDocumentMiddleware | MongooseDocumentMiddleware[] | RegExp, options: SchemaPostOptions, fn: ErrorHandlingMiddlewareFunction<T>): this;
593
+ // method aggregate and insertMany with ErrorHandlingMiddlewareFunction
305
594
  post<T extends Aggregate<any>>(method: 'aggregate' | RegExp, fn: ErrorHandlingMiddlewareFunction<T, Array<any>>): this;
306
595
  post<T extends Aggregate<any>>(method: 'aggregate' | RegExp, options: SchemaPostOptions, fn: ErrorHandlingMiddlewareFunction<T, Array<any>>): this;
307
- post<T = M>(method: 'insertMany' | RegExp, fn: ErrorHandlingMiddlewareFunction<T>): this;
308
- post<T = M>(method: 'insertMany' | RegExp, options: SchemaPostOptions, fn: ErrorHandlingMiddlewareFunction<T>): this;
596
+ post(method: 'bulkWrite' | 'createCollection' | 'insertMany' | RegExp, fn: ErrorHandlingMiddlewareFunction<TModelType>): this;
597
+ post(method: 'bulkWrite' | 'createCollection' | 'insertMany' | RegExp, options: SchemaPostOptions, fn: ErrorHandlingMiddlewareFunction<TModelType>): this;
309
598
 
310
599
  /** Defines a pre hook for the model. */
311
- pre<T = HydratedDocument<DocType, TInstanceMethods>>(
312
- method: DocumentOrQueryMiddleware | DocumentOrQueryMiddleware[],
313
- options: SchemaPreOptions & { document: true; query: false; },
314
- fn: PreMiddlewareFunction<T>
600
+ // this = never since it never happens
601
+ pre<T = never>(method: 'save', options: SchemaPreOptions & { document: false, query: boolean }, fn: PreSaveMiddlewareFunction<T>): this;
602
+ pre<T = never>(method: MongooseQueryOrDocumentMiddleware | MongooseQueryOrDocumentMiddleware[] | RegExp, options: SchemaPreOptions & { document: false, query: false }, fn: PreMiddlewareFunction<T>): this;
603
+ pre<T = never>(method: MongooseDistinctQueryMiddleware|MongooseDistinctQueryMiddleware[], options: SchemaPreOptions & { document: boolean, query: false }, fn: PreMiddlewareFunction<T>): this;
604
+ pre<T = never>(method: MongooseDistinctDocumentMiddleware | MongooseDistinctDocumentMiddleware[] | RegExp, options: SchemaPreOptions & { document: false, query: boolean }, fn: PreMiddlewareFunction<T>): this;
605
+ // this = Union of Document and Query, could be called with any of them
606
+ pre<T = THydratedDocumentType | Query<any, any>>(
607
+ method: 'updateOne' | RegExp,
608
+ options: SchemaPreOptions & { document: true, query: true },
609
+ fn: PreUpdateOneMiddlewareFunction<T>
610
+ ): this;
611
+ pre<T = THydratedDocumentType | Query<any, any>>(
612
+ method: 'deleteOne' | RegExp,
613
+ options: SchemaPreOptions & { document: true, query: true },
614
+ fn: PreDeleteOneMiddlewareFunction<T>
315
615
  ): this;
316
- pre<T = Query<any, any>>(
317
- method: DocumentOrQueryMiddleware | DocumentOrQueryMiddleware[],
318
- options: SchemaPreOptions & { document: false; query: true; },
319
- fn: PreMiddlewareFunction<T>
616
+ // this = Document
617
+ pre<T = THydratedDocumentType>(method: 'save', fn: PreSaveMiddlewareFunction<T>): this;
618
+ pre<T = THydratedDocumentType, U = RawDocType>(method: 'init', fn: (this: T, doc: U) => void): this;
619
+ pre<T = THydratedDocumentType>(method: MongooseDistinctDocumentMiddleware|MongooseDistinctDocumentMiddleware[], fn: PreMiddlewareFunction<T>): this;
620
+ pre<T = THydratedDocumentType>(method: MongooseDistinctDocumentMiddleware|MongooseDistinctDocumentMiddleware[], options: SchemaPreOptions, fn: PreMiddlewareFunction<T>): this;
621
+ pre<T = THydratedDocumentType>(
622
+ method: 'updateOne' | RegExp,
623
+ options: SchemaPreOptions & { document: true },
624
+ fn: PreUpdateOneMiddlewareFunction<T>
320
625
  ): this;
321
- pre<T = HydratedDocument<DocType, TInstanceMethods>>(method: 'save', fn: PreSaveMiddlewareFunction<T>): this;
322
- pre<T = HydratedDocument<DocType, TInstanceMethods>>(method: 'save', options: SchemaPreOptions, fn: PreSaveMiddlewareFunction<T>): this;
323
- pre<T = Query<any, any>>(method: MongooseQueryMiddleware | MongooseQueryMiddleware[] | RegExp, fn: PreMiddlewareFunction<T>): this;
324
- pre<T = Query<any, any>>(method: MongooseQueryMiddleware | MongooseQueryMiddleware[] | RegExp, options: SchemaPreOptions, fn: PreMiddlewareFunction<T>): this;
325
- pre<T = HydratedDocument<DocType, TInstanceMethods>>(method: MongooseDocumentMiddleware | MongooseDocumentMiddleware[] | RegExp, fn: PreMiddlewareFunction<T>): this;
326
- pre<T = HydratedDocument<DocType, TInstanceMethods>>(method: MongooseDocumentMiddleware | MongooseDocumentMiddleware[] | RegExp, options: SchemaPreOptions, fn: PreMiddlewareFunction<T>): this;
626
+ pre<T = THydratedDocumentType>(
627
+ method: 'deleteOne' | RegExp,
628
+ options: SchemaPreOptions & { document: true },
629
+ fn: PreDeleteOneMiddlewareFunction<T>
630
+ ): this;
631
+ pre<T = THydratedDocumentType>(method: MongooseQueryOrDocumentMiddleware | MongooseQueryOrDocumentMiddleware[] | RegExp, options: SchemaPreOptions & { document: true, query: false }, fn: PreMiddlewareFunction<T>): this;
632
+ // this = Query
633
+ pre<T = Query<any, any>>(method: MongooseDefaultQueryMiddleware|MongooseDefaultQueryMiddleware[], fn: PreMiddlewareFunction<T>): this;
634
+ pre<T = Query<any, any>>(method: MongooseDistinctQueryMiddleware|MongooseDistinctQueryMiddleware[], options: SchemaPreOptions, fn: PreMiddlewareFunction<T>): this;
635
+ pre<T = Query<any, any>>(method: MongooseQueryOrDocumentMiddleware | MongooseQueryOrDocumentMiddleware[] | RegExp, options: SchemaPreOptions & { document: false, query: true }, fn: PreMiddlewareFunction<T>): this;
636
+ // this = Union of Document and Query, could be called with any of them
637
+ pre<T = THydratedDocumentType|Query<any, any>>(method: MongooseQueryOrDocumentMiddleware | MongooseQueryOrDocumentMiddleware[] | RegExp, options: SchemaPreOptions & { document: true, query: true }, fn: PreMiddlewareFunction<T>): this;
638
+ pre<T = THydratedDocumentType|Query<any, any>>(method: MongooseQueryOrDocumentMiddleware | MongooseQueryOrDocumentMiddleware[] | RegExp, fn: PreMiddlewareFunction<T>): this;
639
+ // method aggregate
327
640
  pre<T extends Aggregate<any>>(method: 'aggregate' | RegExp, fn: PreMiddlewareFunction<T>): this;
328
- pre<T extends Aggregate<any>>(method: 'aggregate' | RegExp, options: SchemaPreOptions, fn: PreMiddlewareFunction<T>): this;
329
- pre<T = M>(method: 'insertMany' | RegExp, fn: (this: T, next: (err?: CallbackError) => void, docs: any | Array<any>) => void | Promise<void>): this;
330
- pre<T = M>(method: 'insertMany' | RegExp, options: SchemaPreOptions, fn: (this: T, next: (err?: CallbackError) => void, docs: any | Array<any>) => void | Promise<void>): this;
641
+ /* method insertMany */
642
+ pre(
643
+ method: 'insertMany' | RegExp,
644
+ fn: (
645
+ this: TModelType,
646
+ docs: any | Array<any>,
647
+ options?: InsertManyOptions & { lean?: boolean }
648
+ ) => void | Promise<void>
649
+ ): this;
650
+ /* method bulkWrite */
651
+ pre(
652
+ method: 'bulkWrite' | RegExp,
653
+ fn: (
654
+ this: TModelType,
655
+ ops: Array<AnyBulkWriteOperation<any>>,
656
+ options?: mongodb.BulkWriteOptions & MongooseBulkWriteOptions
657
+ ) => void | Promise<void>
658
+ ): this;
659
+ /* method createCollection */
660
+ pre(
661
+ method: 'createCollection' | RegExp,
662
+ fn: (
663
+ this: TModelType,
664
+ options?: mongodb.CreateCollectionOptions & Pick<SchemaOptions, 'expires'>
665
+ ) => void | Promise<void>
666
+ ): this;
331
667
 
332
668
  /** Object of currently defined query helpers on this schema. */
333
669
  query: TQueryHelpers;
@@ -339,24 +675,59 @@ declare module 'mongoose' {
339
675
  remove(paths: string | Array<string>): this;
340
676
 
341
677
  /** Removes index by name or index spec */
342
- remove(index: string | AnyObject): this;
678
+ removeIndex(index: string | AnyObject): this;
679
+
680
+ /** Removes the given virtual or virtuals from this schema. Throws if a virtual does not exist. */
681
+ removeVirtual(path: string | string[]): this;
343
682
 
344
683
  /** Returns an Array of path strings that are required by this schema. */
345
684
  requiredPaths(invalidate?: boolean): string[];
346
685
 
347
686
  /** Sets a schema option. */
348
- set<K extends keyof SchemaOptions>(key: K, value: SchemaOptions[K], _tags?: any): this;
687
+ set<K extends keyof SchemaOptions>(key: K, value: SchemaOptions<DocType>[K], _tags?: any): this;
349
688
 
350
689
  /** Adds static "class" methods to Models compiled from this schema. */
351
690
  static<K extends keyof TStaticMethods>(name: K, fn: TStaticMethods[K]): this;
352
- static(obj: { [F in keyof TStaticMethods]: TStaticMethods[F] } & { [name: string]: (this: M, ...args: any[]) => any }): this;
353
- static(name: string, fn: (this: M, ...args: any[]) => any): this;
691
+ static<Fns extends Partial<TStaticMethods> & { [name: string]: (this: TModelType, ...args: any[]) => any }>(
692
+ obj: Fns
693
+ ): Schema<
694
+ RawDocType,
695
+ TModelType,
696
+ TInstanceMethods,
697
+ TQueryHelpers,
698
+ TVirtuals,
699
+ TStaticMethods & Fns,
700
+ TSchemaOptions,
701
+ DocType,
702
+ THydratedDocumentType,
703
+ TSchemaDefinition,
704
+ LeanResultType
705
+ >;
706
+ static<Name extends string, Fn extends (this: TModelType, ...args: any[]) => any>(
707
+ name: Name,
708
+ fn: Fn
709
+ ): Schema<
710
+ RawDocType,
711
+ TModelType,
712
+ TInstanceMethods,
713
+ TQueryHelpers,
714
+ TVirtuals,
715
+ TStaticMethods & { [K in Name]: Fn },
716
+ TSchemaOptions,
717
+ DocType,
718
+ THydratedDocumentType,
719
+ TSchemaDefinition,
720
+ LeanResultType
721
+ >;
354
722
 
355
723
  /** Object of currently defined statics on this schema. */
356
- statics: { [F in keyof TStaticMethods]: TStaticMethods[F] } & { [name: string]: (this: M, ...args: any[]) => any };
724
+ statics: { [F in keyof TStaticMethods]: TStaticMethods[F] } &
725
+ { [name: string]: ((this: TModelType, ...args: any[]) => unknown) & SupportsMiddlewareOption };
726
+
727
+ toJSONSchema(options?: { useBsonType?: boolean }): Record<string, any>;
357
728
 
358
729
  /** Creates a virtual type with the given name. */
359
- virtual<T = HydratedDocument<DocType, TInstanceMethods, TVirtuals>>(
730
+ virtual<T = THydratedDocumentType>(
360
731
  name: keyof TVirtuals | string,
361
732
  options?: VirtualTypeOptions<T, DocType>
362
733
  ): VirtualType<T>;
@@ -365,14 +736,23 @@ declare module 'mongoose' {
365
736
  virtuals: TVirtuals;
366
737
 
367
738
  /** Returns the virtual type with the given `name`. */
368
- virtualpath<T = HydratedDocument<DocType, TInstanceMethods>>(name: string): VirtualType<T> | null;
739
+ virtualpath(name: string): VirtualType<THydratedDocumentType> | null;
740
+
741
+ static ObjectId: typeof Schema.Types.ObjectId;
369
742
  }
370
743
 
371
- export type NumberSchemaDefinition = typeof Number | 'number' | 'Number' | typeof Schema.Types.Number;
372
- export type StringSchemaDefinition = typeof String | 'string' | 'String' | typeof Schema.Types.String;
373
- export type BooleanSchemaDefinition = typeof Boolean | 'boolean' | 'Boolean' | typeof Schema.Types.Boolean;
374
- export type DateSchemaDefinition = typeof NativeDate | 'date' | 'Date' | typeof Schema.Types.Date;
375
- export type ObjectIdSchemaDefinition = 'ObjectId' | 'ObjectID' | typeof Schema.Types.ObjectId;
744
+ export type NumberSchemaDefinition = typeof Number | 'number' | 'Number' | typeof Schema.Types.Number | Schema.Types.Number | 'int32' | 'Int32' | typeof Schema.Types.Int32 | Schema.Types.Int32;
745
+ export type StringSchemaDefinition = typeof String | 'string' | 'String' | typeof Schema.Types.String | Schema.Types.String;
746
+ export type BooleanSchemaDefinition = typeof Boolean | 'boolean' | 'Boolean' | typeof Schema.Types.Boolean | Schema.Types.Boolean;
747
+ export type DateSchemaDefinition = DateConstructor | 'date' | 'Date' | typeof Schema.Types.Date | Schema.Types.Date;
748
+ export type ObjectIdSchemaDefinition = 'ObjectId' | 'ObjectID' | typeof Schema.Types.ObjectId | Schema.Types.ObjectId | Types.ObjectId | typeof Types.ObjectId;
749
+ export type BufferSchemaDefinition = typeof Buffer | 'buffer' | 'Buffer' | typeof Schema.Types.Buffer;
750
+ export type Decimal128SchemaDefinition = 'decimal128' | 'Decimal128' | typeof Schema.Types.Decimal128 | Schema.Types.Decimal128 | Types.Decimal128;
751
+ export type BigintSchemaDefinition = 'bigint' | 'BigInt' | typeof Schema.Types.BigInt | Schema.Types.BigInt | typeof BigInt | BigInt;
752
+ export type UuidSchemaDefinition = 'uuid' | 'UUID' | typeof Schema.Types.UUID | Schema.Types.UUID;
753
+ export type MapSchemaDefinition = MapConstructor | 'Map' | typeof Schema.Types.Map;
754
+ export type UnionSchemaDefinition = 'Union' | 'union' | typeof Schema.Types.Union | Schema.Types.Union;
755
+ export type DoubleSchemaDefinition = 'double' | 'Double' | typeof Schema.Types.Double | Schema.Types.Double;
376
756
 
377
757
  export type SchemaDefinitionWithBuiltInClass<T> = T extends number
378
758
  ? NumberSchemaDefinition
@@ -384,26 +764,28 @@ declare module 'mongoose' {
384
764
  ? DateSchemaDefinition
385
765
  : (Function | string);
386
766
 
387
- export type SchemaDefinitionProperty<T = undefined> = SchemaDefinitionWithBuiltInClass<T> |
388
- SchemaTypeOptions<T extends undefined ? any : T> |
389
- typeof SchemaType |
390
- Schema<any, any, any> |
391
- Schema<any, any, any>[] |
392
- SchemaTypeOptions<T extends undefined ? any : Unpacked<T>>[] |
393
- Function[] |
394
- SchemaDefinition<T> |
395
- SchemaDefinition<Unpacked<T>>[] |
396
- typeof Schema.Types.Mixed |
397
- MixedSchemaTypeOptions;
398
-
399
- export type SchemaDefinition<T = undefined> = T extends undefined
767
+ export type SchemaDefinitionProperty<T = undefined, EnforcedDocType = any, THydratedDocumentType = HydratedDocument<EnforcedDocType>> =
768
+ // ThisType intersection here avoids corrupting ThisType for SchemaTypeOptions (see test gh11828)
769
+ | SchemaDefinitionWithBuiltInClass<T> & ThisType<THydratedDocumentType>
770
+ | SchemaTypeOptions<T extends undefined ? any : T, EnforcedDocType, THydratedDocumentType>
771
+ | typeof SchemaType
772
+ | Schema<any, any, any>
773
+ | Schema<any, any, any>[]
774
+ | SchemaTypeOptions<T extends undefined ? any : Unpacked<T>, EnforcedDocType, THydratedDocumentType>[]
775
+ | Function[]
776
+ | SchemaDefinition<T, EnforcedDocType, THydratedDocumentType>
777
+ | SchemaDefinition<Unpacked<T>, EnforcedDocType, THydratedDocumentType>[]
778
+ | typeof Schema.Types.Mixed
779
+ | MixedSchemaTypeOptions<EnforcedDocType, THydratedDocumentType>;
780
+
781
+ export type SchemaDefinition<T = undefined, EnforcedDocType = any, THydratedDocumentType = HydratedDocument<EnforcedDocType>> = T extends undefined
400
782
  ? { [path: string]: SchemaDefinitionProperty; }
401
- : { [path in keyof T]?: SchemaDefinitionProperty<T[path]>; };
783
+ : { [path in keyof T]?: SchemaDefinitionProperty<T[path], EnforcedDocType, THydratedDocumentType>; };
402
784
 
403
785
  export type AnyArray<T> = T[] | ReadonlyArray<T>;
404
786
  export type ExtractMongooseArray<T> = T extends Types.Array<any> ? AnyArray<Unpacked<T>> : T;
405
787
 
406
- export interface MixedSchemaTypeOptions extends SchemaTypeOptions<Schema.Types.Mixed> {
788
+ export interface MixedSchemaTypeOptions<EnforcedDocType, THydratedDocumentType> extends SchemaTypeOptions<Schema.Types.Mixed, EnforcedDocType, THydratedDocumentType> {
407
789
  type: typeof Schema.Types.Mixed;
408
790
  }
409
791
 
@@ -417,10 +799,11 @@ declare module 'mongoose' {
417
799
  | typeof Schema.Types.Number
418
800
  | typeof Schema.Types.String
419
801
  | typeof Schema.Types.Buffer
420
- | typeof Schema.Types.ObjectId;
802
+ | typeof Schema.Types.ObjectId
803
+ | typeof Schema.Types.UUID;
421
804
 
422
805
 
423
- export type InferId<T> = T extends { _id?: any } ? T['_id'] : Types.ObjectId;
806
+ export type InferId<T> = mongodb.InferIdType<T>;
424
807
 
425
808
  export interface VirtualTypeOptions<HydratedDocType = Document, DocType = unknown> {
426
809
  /** If `ref` is not nullish, this becomes a populated virtual. */
@@ -448,7 +831,7 @@ declare module 'mongoose' {
448
831
  count?: boolean;
449
832
 
450
833
  /** Add an extra match condition to `populate()`. */
451
- match?: FilterQuery<any> | Function;
834
+ match?: QueryFilter<any> | ((doc: Record<string, any>, virtual?: this) => Record<string, any> | null);
452
835
 
453
836
  /** Add a default `limit` to the `populate()` query. */
454
837
  limit?: number;
@@ -468,6 +851,9 @@ declare module 'mongoose' {
468
851
  /** Additional options like `limit` and `lean`. */
469
852
  options?: QueryOptions<DocType> & { match?: AnyObject };
470
853
 
854
+ /** If true and the given `name` is a direct child of an array, apply the virtual to the array rather than the elements. */
855
+ applyToArray?: boolean;
856
+
471
857
  /** Additional options for plugins */
472
858
  [extra: string]: any;
473
859
  }
@@ -488,38 +874,68 @@ declare module 'mongoose' {
488
874
 
489
875
  export type ReturnsNewDoc = { new: true } | { returnOriginal: false } | { returnDocument: 'after' };
490
876
 
491
- export type ProjectionElementType = number | string;
492
- export type ProjectionType<T> = { [P in keyof T]?: ProjectionElementType } | AnyObject | string;
493
-
877
+ export type ArrayProjectionOperators = { $slice: number | [number, number]; $elemMatch?: never } | { $elemMatch: Record<string, any>; $slice?: never };
878
+ export type ProjectionOperators = { $meta: string };
879
+ /**
880
+ * This Type Assigns `Element | undefined` recursively to the `T` type.
881
+ * if it is an array it will do this to the element of the array, if it is an object it will do this for the properties of the object.
882
+ * `Element` is the truthy or falsy values that are going to be used as the value of the projection.(1 | true or 0 | false)
883
+ * For the elements of the array we will use: `Element | `undefined` | `ArrayProjectionOperators`
884
+ * @example
885
+ * type CalculatedType = Projector<{ a: string, b: number, c: { d: string }, d: string[] }, true>
886
+ * type CalculatedType = {
887
+ a?: true | undefined;
888
+ b?: true | undefined;
889
+ c?: true | {
890
+ d?: true | undefined;
891
+ } | undefined;
892
+ d?: true | ArrayProjectionOperators | undefined;
893
+ }
894
+ */
895
+ export type Projector<T, Element> = T extends Array<infer U>
896
+ ? Projector<U, Element> | ArrayProjectionOperators | ProjectionOperators
897
+ : T extends TreatAsPrimitives
898
+ ? Element | ProjectionOperators
899
+ : T extends Record<string, any>
900
+ ? {
901
+ [K in keyof T]?: T[K] extends Record<string, any> ? Projector<T[K], Element> | Element | ProjectionOperators : Element | ProjectionOperators;
902
+ }
903
+ : Element | ProjectionOperators;
904
+ type _IDType = { _id?: boolean | number };
905
+ export type InclusionProjection<T> = IsItRecordAndNotAny<T> extends true
906
+ ? Omit<Projector<WithLevel1NestedPaths<T>, boolean | number>, '_id'> & _IDType
907
+ : AnyObject;
908
+ export type ExclusionProjection<T> = IsItRecordAndNotAny<T> extends true
909
+ ? Omit<Projector<WithLevel1NestedPaths<T>, false | 0>, '_id'> & _IDType
910
+ : AnyObject;
911
+
912
+ export type ProjectionType<T> = (InclusionProjection<T> & AnyObject)
913
+ | (ExclusionProjection<T> & AnyObject)
914
+ | string;
494
915
  export type SortValues = SortOrder;
495
916
 
496
917
  export type SortOrder = -1 | 1 | 'asc' | 'ascending' | 'desc' | 'descending';
497
918
 
498
- type _UpdateQuery<TSchema> = {
919
+ type _UpdateQuery<TSchema, AdditionalProperties = AnyObject> = {
499
920
  /** @see https://www.mongodb.com/docs/manual/reference/operator/update-field/ */
500
- $currentDate?: AnyKeys<TSchema> & AnyObject;
501
- $inc?: AnyKeys<TSchema> & AnyObject;
502
- $min?: AnyKeys<TSchema> & AnyObject;
503
- $max?: AnyKeys<TSchema> & AnyObject;
504
- $mul?: AnyKeys<TSchema> & AnyObject;
921
+ $currentDate?: AnyKeys<TSchema> & AdditionalProperties;
922
+ $inc?: AnyKeys<TSchema> & AdditionalProperties;
923
+ $min?: AnyKeys<TSchema> & AdditionalProperties;
924
+ $max?: AnyKeys<TSchema> & AdditionalProperties;
925
+ $mul?: AnyKeys<TSchema> & AdditionalProperties;
505
926
  $rename?: Record<string, string>;
506
- $set?: AnyKeys<TSchema> & AnyObject;
507
- $setOnInsert?: AnyKeys<TSchema> & AnyObject;
508
- $unset?: AnyKeys<TSchema> & AnyObject;
927
+ $set?: AnyKeys<TSchema> & AdditionalProperties;
928
+ $setOnInsert?: AnyKeys<TSchema> & AdditionalProperties;
929
+ $unset?: AnyKeys<TSchema> & AdditionalProperties;
509
930
 
510
931
  /** @see https://www.mongodb.com/docs/manual/reference/operator/update-array/ */
511
- $addToSet?: AnyKeys<TSchema> & AnyObject;
512
- $pop?: AnyKeys<TSchema> & AnyObject;
513
- $pull?: AnyKeys<TSchema> & AnyObject;
514
- $push?: AnyKeys<TSchema> & AnyObject;
515
- $pullAll?: AnyKeys<TSchema> & AnyObject;
932
+ $addToSet?: AnyKeys<TSchema> & AdditionalProperties;
933
+ $pop?: AnyKeys<TSchema> & AdditionalProperties;
934
+ $pull?: AnyKeys<TSchema> & AdditionalProperties;
935
+ $push?: AnyKeys<TSchema> & AdditionalProperties;
936
+ $pullAll?: AnyKeys<TSchema> & AdditionalProperties;
516
937
 
517
938
  /** @see https://www.mongodb.com/docs/manual/reference/operator/update-bitwise/ */
518
- // Needs to be `AnyKeys` for now, because anything stricter makes us incompatible
519
- // with the MongoDB Node driver's `UpdateFilter` interface (see gh-12595, gh-11911)
520
- // and using the Node driver's `$bit` definition breaks because their `OnlyFieldsOfType`
521
- // interface breaks on Mongoose Document class due to circular references.
522
- // Re-evaluate this when we drop `extends Document` support in document interfaces.
523
939
  $bit?: AnyKeys<TSchema>;
524
940
  };
525
941
 
@@ -538,90 +954,289 @@ declare module 'mongoose' {
538
954
  * { age: 30 }
539
955
  * ```
540
956
  */
541
- export type UpdateQuery<T> = _UpdateQuery<T> & AnyObject;
542
-
543
- export type DocumentDefinition<T> = {
544
- [K in keyof Omit<T, Exclude<keyof Document, '_id' | 'id' | '__v'>>]:
545
- [Extract<T[K], mongodb.ObjectId>] extends [never]
546
- ? T[K] extends TreatAsPrimitives
547
- ? T[K]
548
- : LeanDocumentElement<T[K]>
549
- : T[K] | string;
550
- };
957
+ export type UpdateQuery<T> = AnyKeys<T> & _UpdateQuery<T> & AnyObject;
958
+
959
+ /**
960
+ * A more strict form of UpdateQuery that enforces updating only
961
+ * known top-level properties.
962
+ * @example
963
+ * ```ts
964
+ * function updateUser(_id: mongoose.Types.ObjectId, update: UpdateQueryKnownOnly<IUser>) {
965
+ * return User.updateOne({ _id }, update);
966
+ * }
967
+ * ```
968
+ */
969
+ export type UpdateQueryKnownOnly<T> = _UpdateQuery<T, {}>;
551
970
 
552
971
  export type FlattenMaps<T> = {
553
- [K in keyof T]: T[K] extends Map<any, any>
554
- ? AnyObject : T[K] extends TreatAsPrimitives
555
- ? T[K] : FlattenMaps<T[K]>;
972
+ [K in keyof T]: FlattenProperty<T[K]>;
556
973
  };
557
974
 
558
- export type actualPrimitives = string | boolean | number | bigint | symbol | null | undefined;
559
- export type TreatAsPrimitives = actualPrimitives | NativeDate | RegExp | symbol | Error | BigInt | Types.ObjectId;
975
+ export type BufferToBinaryProperty<T> = unknown extends Buffer
976
+ ? T
977
+ : T extends Buffer
978
+ ? mongodb.Binary
979
+ : T extends Types.DocumentArray<infer ItemType>
980
+ ? Types.DocumentArray<BufferToBinary<ItemType>>
981
+ : T extends Types.Subdocument<unknown, unknown, infer SubdocType>
982
+ ? HydratedSingleSubdocument<BufferToBinary<SubdocType>>
983
+ : BufferToBinary<T>;
560
984
 
561
- export type LeanType<T> =
562
- 0 extends (1 & T) ? T : // any
563
- T extends TreatAsPrimitives ? T : // primitives
564
- T extends Types.ArraySubdocument ? Omit<LeanDocument<T>, 'parentArray' | 'ownerDocument' | 'parent'> :
565
- T extends Types.Subdocument ? Omit<LeanDocument<T>, '$isSingleNested' | 'ownerDocument' | 'parent'> :
566
- LeanDocument<T>; // Documents and everything else
985
+ /**
986
+ * Converts any Buffer properties into mongodb.Binary instances, which is what `lean()` returns
987
+ */
988
+ export type BufferToBinary<T> = unknown extends Buffer
989
+ ? T
990
+ : T extends Buffer
991
+ ? mongodb.Binary
992
+ : T extends Document
993
+ ? T
994
+ : T extends TreatAsPrimitives
995
+ ? T
996
+ : T extends Record<string, any>
997
+ ? {
998
+ [K in keyof T]: BufferToBinaryProperty<T[K]>
999
+ }
1000
+ : T;
567
1001
 
568
- export type LeanArray<T extends unknown[]> = T extends unknown[][] ? LeanArray<T[number]>[] : LeanType<T[number]>[];
1002
+ /**
1003
+ * Converts any Buffer properties into { type: 'buffer', data: [1, 2, 3] } format for JSON serialization
1004
+ */
1005
+ export type BufferToJSON<T> = unknown extends Buffer
1006
+ ? T
1007
+ : T extends Buffer
1008
+ ? { type: 'buffer', data: number[] }
1009
+ : T extends Document
1010
+ ? T
1011
+ : T extends TreatAsPrimitives
1012
+ ? T
1013
+ : T extends Record<string, any> ? {
1014
+ [K in keyof T]: T[K] extends Buffer
1015
+ ? { type: 'buffer', data: number[] }
1016
+ : T[K] extends Types.DocumentArray<infer ItemType>
1017
+ ? Types.DocumentArray<BufferToBinary<ItemType>>
1018
+ : T[K] extends Types.Subdocument<unknown, unknown, infer SubdocType>
1019
+ ? HydratedSingleSubdocument<SubdocType>
1020
+ : BufferToBinary<T[K]>;
1021
+ } : T;
569
1022
 
570
- export type _LeanDocument<T> = {
571
- [K in keyof T]: LeanDocumentElement<T[K]>;
572
- };
1023
+ /**
1024
+ * Converts any UUID properties into strings for JSON serialization
1025
+ */
1026
+ export type UUIDToString<T> = T extends Types.UUID
1027
+ ? string
1028
+ : T extends mongodb.UUID
1029
+ ? string
1030
+ : T extends Document
1031
+ ? T
1032
+ : T extends TreatAsPrimitives
1033
+ ? T
1034
+ : T extends Record<string, any> ? {
1035
+ [K in keyof T]: T[K] extends Types.UUID
1036
+ ? string
1037
+ : T[K] extends mongodb.UUID
1038
+ ? string
1039
+ : T[K] extends Types.DocumentArray<infer ItemType>
1040
+ ? Types.DocumentArray<UUIDToString<ItemType>>
1041
+ : T[K] extends Types.Subdocument<unknown, unknown, infer SubdocType>
1042
+ ? HydratedSingleSubdocument<UUIDToString<SubdocType>>
1043
+ : UUIDToString<T[K]>;
1044
+ } : T;
573
1045
 
574
- // Keep this a separate type, to ensure that T is a naked type.
575
- // This way, the conditional type is distributive over union types.
576
- // This is required for PopulatedDoc.
577
- export type LeanDocumentElement<T> =
578
- T extends unknown[] ? LeanArray<T> : // Array
579
- T extends Document ? LeanDocument<T> : // Subdocument
580
- T;
1046
+ /**
1047
+ * Alias for UUIDToString for backwards compatibility.
1048
+ * @deprecated Use UUIDToString instead.
1049
+ */
1050
+ export type UUIDToJSON<T> = UUIDToString<T>;
581
1051
 
582
- export type SchemaDefinitionType<T> = T extends Document ? Omit<T, Exclude<keyof Document, '_id' | 'id' | '__v'>> : T;
1052
+ /**
1053
+ * Converts any ObjectId properties into strings for JSON serialization
1054
+ */
1055
+ export type ObjectIdToString<T> = T extends mongodb.ObjectId
1056
+ ? string
1057
+ : T extends Document
1058
+ ? T
1059
+ : T extends TreatAsPrimitives
1060
+ ? T
1061
+ : T extends Record<string, any> ? {
1062
+ [K in keyof T]: T[K] extends mongodb.ObjectId
1063
+ ? string
1064
+ : T[K] extends Types.DocumentArray<infer ItemType>
1065
+ ? Types.DocumentArray<ObjectIdToString<ItemType>>
1066
+ : T[K] extends Types.Subdocument<unknown, unknown, infer SubdocType>
1067
+ ? HydratedSingleSubdocument<ObjectIdToString<SubdocType>>
1068
+ : ObjectIdToString<T[K]>;
1069
+ } : T;
583
1070
 
584
- // tests for these two types are located in test/types/lean.test.ts
585
- export type DocTypeFromUnion<T> = T extends (Document<infer T1, infer T2, infer T3> & infer U) ?
586
- [U] extends [Document<T1, T2, T3> & infer U] ? IfUnknown<IfAny<U, false>, false> : false : false;
1071
+ /**
1072
+ * Converts any Date properties into strings for JSON serialization
1073
+ */
1074
+ export type DateToString<T> = T extends NativeDate
1075
+ ? string
1076
+ : T extends Document
1077
+ ? T
1078
+ : T extends TreatAsPrimitives
1079
+ ? T
1080
+ : T extends Record<string, any> ? {
1081
+ [K in keyof T]: T[K] extends NativeDate
1082
+ ? string
1083
+ : T[K] extends (NativeDate | null | undefined)
1084
+ ? string | null | undefined
1085
+ : T[K] extends Types.DocumentArray<infer ItemType>
1086
+ ? Types.DocumentArray<DateToString<ItemType>>
1087
+ : T[K] extends Types.Subdocument<unknown, unknown, infer SubdocType>
1088
+ ? HydratedSingleSubdocument<DateToString<SubdocType>>
1089
+ : DateToString<T[K]>;
1090
+ } : T;
587
1091
 
588
- export type DocTypeFromGeneric<T> = T extends Document<infer IdType, infer TQueryHelpers, infer DocType> ?
589
- IfUnknown<IfAny<DocType, false>, false> : false;
1092
+ /**
1093
+ * Converts any Mongoose subdocuments (single nested or doc arrays) into POJO equivalents
1094
+ */
1095
+ export type SubdocsToPOJOs<T> = T extends Document
1096
+ ? T
1097
+ : T extends TreatAsPrimitives
1098
+ ? T
1099
+ : T extends Record<string, any> ? {
1100
+ [K in keyof T]: T[K] extends Types.DocumentArray<infer ItemType>
1101
+ ? ItemType[]
1102
+ : T[K] extends Types.Subdocument<unknown, unknown, infer SubdocType>
1103
+ ? SubdocType
1104
+ : SubdocsToPOJOs<T[K]>;
1105
+ } : T;
1106
+
1107
+ export type JSONSerialized<T> = SubdocsToPOJOs<
1108
+ FlattenMaps<
1109
+ BufferToJSON<
1110
+ ObjectIdToString<
1111
+ UUIDToJSON<
1112
+ DateToString<T>
1113
+ >
1114
+ >
1115
+ >
1116
+ >
1117
+ >;
590
1118
 
591
1119
  /**
592
- * Helper to choose the best option between two type helpers
1120
+ * Helper types for computing toObject/toJSON return types based on options.
1121
+ * These compose transforms conditionally to avoid combinatorial explosion of overloads.
593
1122
  */
594
- export type _pickObject<T1, T2, Fallback> = T1 extends false ? T2 extends false ? Fallback : T2 : T1;
1123
+ type ApplyVirtuals<T, TVirtuals, O> =
1124
+ O extends { virtuals: true } ? T & TVirtuals : T;
1125
+
1126
+ type GetVersionKeyName<TSchemaOptions> =
1127
+ TSchemaOptions extends { versionKey: infer VK }
1128
+ ? VK extends string ? VK : '__v'
1129
+ : '__v';
1130
+
1131
+ type ApplyVersionKey<T, O, TSchemaOptions = {}> =
1132
+ O extends { versionKey: false } ? Omit<T, GetVersionKeyName<TSchemaOptions>> : T;
595
1133
 
596
1134
  /**
597
- * There may be a better way to do this, but the goal is to return the DocType if it can be infered
598
- * and if not to return a type which is easily identified as "not valid" so we fall back to
599
- * "strip out known things added by extending Document"
600
- * There are three basic ways to mix in Document -- "Document & T", "Document<ObjId, mixins, T>",
601
- * and "T extends Document". In the last case there is no type without Document mixins, so we can only
602
- * strip things out. In the other two cases we can infer the type, so we should
1135
+ * Single-pass type that applies all flatten transforms (flattenMaps, flattenObjectIds, flattenUUIDs)
1136
+ * in one recursive traversal. This avoids TypeScript's "union type too complex" error that occurs
1137
+ * when nesting separate recursive transform types.
1138
+ *
1139
+ * By handling all transforms in one pass, we correctly handle ObjectIds/UUIDs nested inside Maps
1140
+ * since we recurse into Map values during the same traversal that converts ObjectIds/UUIDs.
603
1141
  */
604
- export type BaseDocumentType<T> = _pickObject<DocTypeFromUnion<T>, DocTypeFromGeneric<T>, false>;
1142
+ type ApplyFlattenTransforms<T, O> =
1143
+ // Handle ObjectId first (before TreatAsPrimitives since ObjectId is in TreatAsPrimitives)
1144
+ T extends mongodb.ObjectId
1145
+ ? O extends { flattenObjectIds: true } ? string : T
1146
+ // Handle UUID (both Types.UUID and mongodb.UUID)
1147
+ : T extends Types.UUID
1148
+ ? O extends { flattenUUIDs: true } ? string : T
1149
+ : T extends mongodb.UUID
1150
+ ? O extends { flattenUUIDs: true } ? string : T
1151
+ // Handle Map - flatten to Record and recurse into values
1152
+ : T extends Map<any, infer V>
1153
+ ? O extends { flattenMaps: true }
1154
+ ? Record<string, ApplyFlattenTransforms<V, O>>
1155
+ : T
1156
+ // Don't recurse into Documents
1157
+ : T extends Document
1158
+ ? T
1159
+ // Don't modify primitives
1160
+ : T extends TreatAsPrimitives
1161
+ ? T
1162
+ // Handle DocumentArray - recurse into items
1163
+ : T extends Types.DocumentArray<infer ItemType>
1164
+ ? Types.DocumentArray<ApplyFlattenTransforms<ItemType, O>>
1165
+ // Handle plain arrays - recurse into items
1166
+ : T extends Array<infer ItemType>
1167
+ ? ApplyFlattenTransforms<ItemType, O>[]
1168
+ // Handle Subdocument - recurse into subdoc type
1169
+ : T extends Types.Subdocument<unknown, unknown, infer SubdocType>
1170
+ ? HydratedSingleSubdocument<ApplyFlattenTransforms<SubdocType, O>>
1171
+ // Handle regular objects - recurse into properties
1172
+ : T extends Record<string, any>
1173
+ ? { [K in keyof T]: ApplyFlattenTransforms<T[K], O> }
1174
+ : T;
605
1175
 
606
1176
  /**
607
- * Documents returned from queries with the lean option enabled.
608
- * Plain old JavaScript object documents (POJO).
609
- * @see https://mongoosejs.com/docs/tutorials/lean.html
1177
+ * Extracts the `toObject` or `toJSON` options declared in the schema options.
1178
+ * The runtime applies these as defaults when the corresponding method is
1179
+ * called without arguments.
610
1180
  */
611
- export type LeanDocument<T> = Omit<_LeanDocument<T>, Exclude<keyof Document, '_id' | 'id' | '__v'> | '$isSingleNested'>;
1181
+ export type SchemaDeclaredToObjectOptions<TSchemaOptions, Key extends 'toObject' | 'toJSON'> =
1182
+ Key extends keyof TSchemaOptions
1183
+ ? NonNullable<TSchemaOptions[Key]> extends infer O extends ToObjectOptions
1184
+ ? O
1185
+ : {}
1186
+ : {};
612
1187
 
613
- export type LeanDocumentOrArray<T> = 0 extends (1 & T) ? T :
614
- T extends unknown[] ? LeanDocument<T[number]>[] :
615
- T extends Document ? LeanDocument<T> :
616
- T;
1188
+ /**
1189
+ * Computes the return type of toObject/toJSON when called without arguments,
1190
+ * applying the options declared in the schema like the runtime does. When the
1191
+ * schema declares no options for the method, the plain document shape is
1192
+ * returned without running it through the option transforms.
1193
+ */
1194
+ export type DefaultToObjectReturnType<DocType, TVirtuals, TSchemaOptions, Key extends 'toObject' | 'toJSON'> =
1195
+ SchemaDeclaredToObjectOptions<TSchemaOptions, Key> extends infer O extends ToObjectOptions
1196
+ ? keyof O extends never
1197
+ ? Default__v<Require_id<DocType>, TSchemaOptions>
1198
+ : ToObjectReturnType<DocType, TVirtuals, O, TSchemaOptions>
1199
+ : Default__v<Require_id<DocType>, TSchemaOptions>;
617
1200
 
618
- export type LeanDocumentOrArrayWithRawType<T, RawDocType> = 0 extends (1 & T) ? T :
619
- T extends unknown[] ? LeanDocument<RawDocType>[] :
620
- T extends Document ? LeanDocument<RawDocType> :
621
- T;
1201
+ /**
1202
+ * Computes the return type of toObject/toJSON based on the provided options.
1203
+ * Uses a single-pass transform for flatten operations to correctly handle all combinations.
1204
+ */
1205
+ export type ToObjectReturnType<DocType, TVirtuals, O extends ToObjectOptions, TSchemaOptions = {}> =
1206
+ ApplyVersionKey<
1207
+ Default__v<
1208
+ ApplyFlattenTransforms<
1209
+ ApplyVirtuals<Require_id<DocType>, TVirtuals, O>,
1210
+ O
1211
+ >,
1212
+ TSchemaOptions
1213
+ >,
1214
+ O,
1215
+ TSchemaOptions
1216
+ >;
1217
+
1218
+ /**
1219
+ * Separate type is needed for properties of union type (for example, Types.DocumentArray | undefined) to apply conditional check to each member of it
1220
+ * https://www.typescriptlang.org/docs/handbook/2/conditional-types.html#distributive-conditional-types
1221
+ */
1222
+ type FlattenProperty<T> = T extends Map<any, infer V>
1223
+ ? Record<string, V> : T extends TreatAsPrimitives
1224
+ ? T : T extends Document ? T : T extends Types.DocumentArray<infer ItemType>
1225
+ ? Types.DocumentArray<FlattenMaps<ItemType>> : FlattenMaps<T>;
1226
+
1227
+ export type actualPrimitives = string | boolean | number | bigint | symbol | null | undefined;
1228
+ export type TreatAsPrimitives = actualPrimitives | NativeDate | RegExp | symbol | Error | BigInt | Types.ObjectId | Buffer | Function | mongodb.Binary | mongodb.ClientSession;
1229
+
1230
+ export type SchemaDefinitionType<T> = T extends Document ? Omit<T, Exclude<keyof Document, '_id' | 'id' | '__v'>> : T;
622
1231
 
623
1232
  /* for ts-mongoose */
624
1233
  export class mquery { }
625
1234
 
1235
+ export function overwriteMiddlewareResult(val: any): Kareem.OverwriteResult;
1236
+
1237
+ export function skipMiddlewareFunction(val: any): Kareem.SkipWrappedFunction;
1238
+
1239
+ export function overwriteMiddlewareArguments(val: any): Kareem.OverwriteArguments;
1240
+
626
1241
  export default mongoose;
627
1242
  }