@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/query.d.ts CHANGED
@@ -1,161 +1,188 @@
1
1
  declare module 'mongoose' {
2
2
  import mongodb = require('mongodb');
3
3
 
4
- export type ApplyBasicQueryCasting<T> = T | T[] | (T extends (infer U)[] ? U : any) | any;
5
- type Condition<T> = ApplyBasicQueryCasting<T> | QuerySelector<ApplyBasicQueryCasting<T>>;
6
-
7
- type _FilterQuery<T> = {
8
- [P in keyof T]?: Condition<T[P]>;
9
- } & RootQuerySelector<T>;
10
-
11
- /**
12
- * Filter query to select the documents that match the query
13
- * @example
14
- * ```js
15
- * { age: { $gte: 30 } }
16
- * ```
17
- */
18
- type FilterQuery<T> = _FilterQuery<T>;
19
-
20
- type MongooseQueryOptions<DocType = unknown> = Pick<QueryOptions<DocType>, 'populate' | 'lean' | 'strict' | 'sanitizeProjection' | 'sanitizeFilter'>;
21
-
22
- type ProjectionFields<DocType> = { [Key in keyof Omit<LeanDocument<DocType>, '__v'>]?: any } & Record<string, any>;
23
-
24
- type QueryWithHelpers<ResultType, DocType, THelpers = {}, RawDocType = DocType> = Query<ResultType, DocType, THelpers, RawDocType> & THelpers;
25
-
26
- type QuerySelector<T> = {
27
- // Comparison
28
- $eq?: T;
29
- $gt?: T;
30
- $gte?: T;
31
- $in?: [T] extends AnyArray<any> ? Unpacked<T>[] : T[];
32
- $lt?: T;
33
- $lte?: T;
34
- $ne?: T;
35
- $nin?: [T] extends AnyArray<any> ? Unpacked<T>[] : T[];
36
- // Logical
37
- $not?: T extends string ? QuerySelector<T> | RegExp : QuerySelector<T>;
38
- // Element
39
- /**
40
- * When `true`, `$exists` matches the documents that contain the field,
41
- * including documents where the field value is null.
42
- */
43
- $exists?: boolean;
44
- $type?: string | number;
45
- // Evaluation
46
- $expr?: any;
47
- $jsonSchema?: any;
48
- $mod?: T extends number ? [number, number] : never;
49
- $regex?: T extends string ? RegExp | string : never;
50
- $options?: T extends string ? string : never;
51
- // Geospatial
52
- // TODO: define better types for geo queries
53
- $geoIntersects?: { $geometry: object };
54
- $geoWithin?: object;
55
- $near?: object;
56
- $nearSphere?: object;
57
- $maxDistance?: number;
58
- // Array
59
- // TODO: define better types for $all and $elemMatch
60
- $all?: T extends AnyArray<any> ? any[] : never;
61
- $elemMatch?: T extends AnyArray<any> ? object : never;
62
- $size?: T extends AnyArray<any> ? number : never;
63
- // Bitwise
64
- $bitsAllClear?: number | mongodb.Binary | number[];
65
- $bitsAllSet?: number | mongodb.Binary | number[];
66
- $bitsAnyClear?: number | mongodb.Binary | number[];
67
- $bitsAnySet?: number | mongodb.Binary | number[];
4
+ type StringQueryTypeCasting<T> = string extends T ? string | RegExp : T | RegExp;
5
+ type ObjectIdQueryTypeCasting = Types.ObjectId | string;
6
+ type DateQueryTypeCasting = string | number | NativeDate;
7
+ type UUIDQueryTypeCasting = Types.UUID | string;
8
+ type BufferQueryCasting = Buffer | mongodb.Binary | number[] | string | { $binary: string | mongodb.Binary };
9
+ type QueryTypeCasting<T> = T extends string
10
+ ? StringQueryTypeCasting<T>
11
+ : T extends Types.ObjectId
12
+ ? ObjectIdQueryTypeCasting
13
+ : T extends Types.UUID
14
+ ? UUIDQueryTypeCasting
15
+ : T extends Buffer
16
+ ? BufferQueryCasting
17
+ : T extends NativeDate
18
+ ? DateQueryTypeCasting
19
+ : T;
20
+
21
+ export type ApplyBasicQueryCasting<T> = QueryTypeCasting<T> | QueryTypeCasting<T>[] | (T extends (infer U)[] ? QueryTypeCasting<U> : T) | null;
22
+
23
+ type RemoveIndexSignature<T> = {
24
+ [K in keyof T as string extends K ? never : number extends K ? never : symbol extends K ? never : K]: T[K];
68
25
  };
69
26
 
70
- type RootQuerySelector<T> = {
71
- /** @see https://www.mongodb.com/docs/manual/reference/operator/query/and/#op._S_and */
72
- $and?: Array<FilterQuery<T>>;
73
- /** @see https://www.mongodb.com/docs/manual/reference/operator/query/nor/#op._S_nor */
74
- $nor?: Array<FilterQuery<T>>;
75
- /** @see https://www.mongodb.com/docs/manual/reference/operator/query/or/#op._S_or */
76
- $or?: Array<FilterQuery<T>>;
77
- /** @see https://www.mongodb.com/docs/manual/reference/operator/query/text */
78
- $text?: {
79
- $search: string;
80
- $language?: string;
81
- $caseSensitive?: boolean;
82
- $diacriticSensitive?: boolean;
83
- };
84
- /** @see https://www.mongodb.com/docs/manual/reference/operator/query/where/#op._S_where */
85
- $where?: string | Function;
86
- /** @see https://www.mongodb.com/docs/manual/reference/operator/query/comment/#op._S_comment */
87
- $comment?: string;
88
- // we could not find a proper TypeScript generic to support nested queries e.g. 'user.friends.name'
89
- // this will mark all unrecognized properties as any (including nested queries)
90
- [key: string]: any;
27
+ type StrictFilterOperators<TValue> = RemoveIndexSignature<mongodb.FilterOperators<TValue>>;
28
+
29
+ type StrictCondition<T> = mongodb.AlternativeType<T> | StrictFilterOperators<mongodb.AlternativeType<T>>;
30
+
31
+ type _StrictFilter<TSchema> = {
32
+ [P in keyof TSchema]?: StrictCondition<ApplyBasicQueryCasting<TSchema[P]>>;
33
+ } & StrictRootFilterOperators<TSchema>;
34
+
35
+ type StrictRootFilterOperators<TSchema> = Omit<mongodb.RootFilterOperators<TSchema>, '$and' | '$or' | '$nor'> & {
36
+ $and?: _StrictFilter<TSchema>[];
37
+ $or?: _StrictFilter<TSchema>[];
38
+ $nor?: _StrictFilter<TSchema>[];
91
39
  };
92
40
 
41
+ type _QueryFilter<T> = (
42
+ { [P in keyof T]?: StrictCondition<ApplyBasicQueryCasting<T[P]>>; } &
43
+ StrictRootFilterOperators<{ [P in keyof mongodb.WithId<T>]?: ApplyBasicQueryCasting<mongodb.WithId<T>[P]>; }>
44
+ );
45
+ type _QueryFilterLooseId<T> = (
46
+ { [P in keyof T]?: StrictCondition<ApplyBasicQueryCasting<T[P]>>; } &
47
+ StrictRootFilterOperators<
48
+ { [P in keyof T]?: ApplyBasicQueryCasting<T[P]>; }
49
+ >
50
+ );
51
+ type QueryFilter<T> = IsItRecordAndNotAny<T> extends true ? _QueryFilter<WithLevel1NestedPaths<T>> : _QueryFilterLooseId<Record<string, any>>;
52
+
53
+ type MongooseBaseQueryOptionKeys =
54
+ | 'cloneUpdate'
55
+ | 'context'
56
+ | 'middleware'
57
+ | 'multipleCastError'
58
+ | 'overwriteDiscriminatorKey'
59
+ | 'overwriteImmutable'
60
+ | 'populate'
61
+ | 'runValidators'
62
+ | 'sanitizeProjection'
63
+ | 'sanitizeFilter'
64
+ | 'schemaLevelProjections'
65
+ | 'setDefaultsOnInsert'
66
+ | 'strict'
67
+ | 'strictQuery'
68
+ | 'translateAliases'
69
+ | 'updatePipeline';
70
+
71
+ type MongooseBaseQueryOptions<DocType = unknown> = Pick<QueryOptions<DocType>, MongooseBaseQueryOptionKeys | 'timestamps' | 'lean'> & {
72
+ [other: string]: any;
73
+ };
74
+
75
+ type MongooseUpdateQueryOptions<DocType = unknown> = Pick<QueryOptions<DocType>, MongooseBaseQueryOptionKeys | 'timestamps'>;
76
+
77
+ type ProjectionFields<DocType> = { [Key in keyof DocType]?: any } & Record<string, any>;
78
+
79
+ type QueryWithHelpers<
80
+ ResultType,
81
+ DocType,
82
+ THelpers = {},
83
+ RawDocType = DocType,
84
+ QueryOp = 'find',
85
+ TDocOverrides = Record<string, never>,
86
+ TLeanResultType = RawDocType
87
+ > = Query<ResultType, DocType, THelpers, RawDocType, QueryOp, TDocOverrides, TLeanResultType> & THelpers;
88
+
93
89
  interface QueryTimestampsConfig {
94
90
  createdAt?: boolean;
95
91
  updatedAt?: boolean;
96
92
  }
97
93
 
94
+ // Options that can be passed to Query.prototype.lean()
95
+ interface LeanOptions {
96
+ // Set to false to strip out the version key
97
+ versionKey?: boolean;
98
+ // Transform the result document in place. `doc` is the raw document being transformed.
99
+ // Typed as `Record<string, unknown>` because TypeScript gets confused when handling Document.prototype.deleteOne()
100
+ // and other document methods that try to infer the raw doc type from the Document class.
101
+ transform?: (doc: Record<string, unknown>) => void;
102
+ [key: string]: any;
103
+ }
104
+
98
105
  interface QueryOptions<DocType = unknown> extends
99
106
  PopulateOption,
100
107
  SessionOption {
101
- arrayFilters?: { [key: string]: any }[];
108
+ arrayFilters?: AnyObject[];
102
109
  batchSize?: number;
103
110
  collation?: mongodb.CollationOptions;
104
111
  comment?: any;
105
112
  context?: string;
113
+ /**
114
+ * If `false`, Mongoose will not clone the update before executing the query.
115
+ */
116
+ cloneUpdate?: boolean;
106
117
  explain?: mongodb.ExplainVerbosityLike;
107
118
  fields?: any | string;
108
119
  hint?: mongodb.Hint;
109
120
  /**
110
121
  * If truthy, mongoose will return the document as a plain JavaScript object rather than a mongoose document.
111
122
  */
112
- lean?: boolean | any;
123
+ lean?: boolean | LeanOptions;
113
124
  limit?: number;
114
125
  maxTimeMS?: number;
115
- maxscan?: number;
116
126
  multi?: boolean;
117
127
  multipleCastError?: boolean;
118
128
  /**
119
129
  * By default, `findOneAndUpdate()` returns the document as it was **before**
120
130
  * `update` was applied. If you set `new: true`, `findOneAndUpdate()` will
121
131
  * instead give you the object after `update` was applied.
132
+ * Use `returnDocument: 'after'` instead of `new: true`, or `returnDocument: 'before'` instead of `new: false`.
133
+ *
134
+ * @deprecated
122
135
  */
123
136
  new?: boolean;
124
- overwrite?: boolean;
137
+
138
+ /**
139
+ * If `false`, skip applying default schema values to the returned document(s).
140
+ * @default true
141
+ */
142
+ defaults?: boolean;
125
143
  overwriteDiscriminatorKey?: boolean;
126
- projection?: ProjectionType<DocType>;
127
144
  /**
128
- * if true, returns the raw result from the MongoDB driver
145
+ * Mongoose removes updated immutable properties from `update` by default (excluding $setOnInsert).
146
+ * Set `overwriteImmutable` to `true` to allow updating immutable properties using other update operators.
129
147
  */
130
- rawResult?: boolean;
148
+ overwriteImmutable?: boolean;
149
+ projection?: AnyObject | string;
150
+ /**
151
+ * if true, returns the full ModifyResult rather than just the document
152
+ */
153
+ includeResultMetadata?: boolean;
131
154
  readPreference?: string | mongodb.ReadPreferenceMode;
132
155
  /**
133
156
  * An alias for the `new` option. `returnOriginal: false` is equivalent to `new: true`.
157
+ * Use `returnDocument: 'after'` instead of `returnOriginal: false`, or `returnDocument: 'before'` instead of `returnOriginal: true`.
158
+ *
159
+ * @deprecated
134
160
  */
135
161
  returnOriginal?: boolean;
136
162
  /**
137
- * Another alias for the `new` option. `returnOriginal` is deprecated so this should be used.
163
+ * Has two possible values, `'before'` and `'after'`. By default, it will return the document before the update was applied.
164
+ * @default 'before'
138
165
  */
139
166
  returnDocument?: 'before' | 'after';
140
- runValidators?: boolean;
141
167
  /**
142
- * Set to `true` to automatically sanitize potentially unsafe user-generated query projections.
143
- * Converts projection values that aren't numbers or booleans to `1`, including strings like `'$password'`
144
- * and expressions like `{ $concat: ['$password'] }`, so projections can't copy one field's value into another.
145
- * The only projection operators that are allowed are `$elemMatch`, `$slice` with numbers, and `$meta: 'textScore'`.
146
- *
147
- * In Mongoose 6, `sanitizeProjection` does **not** prevent projecting in fields that the schema deselects
148
- * with `select: false`: `select('+password')` and `select({ password: 1 })` still include `password`.
168
+ * Set to true to enable `update validators`
169
+ * (https://mongoosejs.com/docs/validation.html#update-validators). Defaults to false.
149
170
  */
171
+ runValidators?: boolean;
172
+ /* Set to `true` to automatically sanitize potentially unsafe user-generated query projections */
150
173
  sanitizeProjection?: boolean;
151
174
  /**
152
175
  * Set to `true` to automatically sanitize potentially unsafe query filters by stripping out query selectors that
153
176
  * aren't explicitly allowed using `mongoose.trusted()`.
154
177
  */
155
178
  sanitizeFilter?: boolean;
179
+ /**
180
+ * Enable or disable schema level projections for this query. Enabled by default.
181
+ * Set to `false` to include fields with `select: false` in the query result by default.
182
+ */
183
+ schemaLevelProjections?: boolean;
156
184
  setDefaultsOnInsert?: boolean;
157
185
  skip?: number;
158
- snapshot?: any;
159
186
  sort?: any;
160
187
  /** overwrites the schema's strict mode option */
161
188
  strict?: boolean | string;
@@ -171,27 +198,66 @@ declare module 'mongoose' {
171
198
  * timestamps. Does nothing if schema-level timestamps are not set.
172
199
  */
173
200
  timestamps?: boolean | QueryTimestampsConfig;
201
+ /**
202
+ * If `true`, convert any aliases in filter, projection, update, and distinct
203
+ * to their database property names. Defaults to false.
204
+ */
205
+ translateAliases?: boolean;
174
206
  upsert?: boolean;
207
+ useBigInt64?: boolean;
208
+ /**
209
+ * Set to true to allow passing in an update pipeline instead of an update document.
210
+ * Mongoose disallows update pipelines by default because Mongoose does not cast update pipelines.
211
+ */
212
+ updatePipeline?: boolean;
175
213
  writeConcern?: mongodb.WriteConcern;
176
214
 
215
+ /** set to `false` to skip all user-defined middleware, or `{ pre: false }` / `{ post: false }` to skip only pre or post hooks */
216
+ middleware?: boolean | SkipMiddlewareOptions;
217
+
177
218
  [other: string]: any;
178
219
  }
179
220
 
180
- class Query<ResultType, DocType, THelpers = {}, RawDocType = DocType> implements SessionOperation {
181
- _mongooseOptions: MongooseQueryOptions<DocType>;
221
+ type QueryOpThatReturnsDocument = 'find' | 'findOne' | 'findOneAndUpdate' | 'findOneAndReplace' | 'findOneAndDelete';
222
+
223
+ type GetLeanResultType<RawDocType, ResultType, QueryOp> = QueryOp extends QueryOpThatReturnsDocument
224
+ ? (ResultType extends any[] ? RawDocType[] : RawDocType)
225
+ : ResultType;
226
+
227
+ type MergePopulatePaths<RawDocType, ResultType, QueryOp, Paths, TQueryHelpers, TDocOverrides = Record<string, never>> = QueryOp extends QueryOpThatReturnsDocument
228
+ ? ResultType extends null
229
+ ? ResultType
230
+ : ResultType extends (infer U)[]
231
+ ? U extends Document
232
+ ? PopulateDocumentResult<U, Paths, MergeType<RawDocType, Paths>, RawDocType>[]
233
+ : (MergeType<U, Paths>)[]
234
+ : ResultType extends Document
235
+ ? PopulateDocumentResult<ResultType, Paths, MergeType<RawDocType, Paths>, RawDocType>
236
+ : MergeType<ResultType, Paths>
237
+ : MergeType<ResultType, Paths>;
238
+
239
+ class Query<ResultType, DocType, THelpers = {}, RawDocType = unknown, QueryOp = 'find', TDocOverrides = Record<string, never>, TLeanResultType = RawDocType> implements SessionOperation {
240
+ _mongooseOptions: QueryOptions<RawDocType>;
182
241
 
183
242
  /**
184
- * Returns a wrapper around a [mongodb driver cursor](https://mongodb.github.io/node-mongodb-native/4.9/classes/FindCursor.html).
243
+ * Returns a wrapper around a [mongodb driver cursor](https://mongodb.github.io/node-mongodb-native/7.0/classes/FindCursor.html).
185
244
  * A QueryCursor exposes a Streams3 interface, as well as a `.next()` function.
186
245
  * This is equivalent to calling `.cursor()` with no arguments.
187
246
  */
188
- [Symbol.asyncIterator](): AsyncIterableIterator<DocType>;
247
+ [Symbol.asyncIterator](): AsyncIterableIterator<Unpacked<ResultType>>;
189
248
 
190
249
  /** Executes the query */
191
- exec(callback: Callback<ResultType>): void;
192
250
  exec(): Promise<ResultType>;
193
251
 
194
- $where(argument: string | Function): QueryWithHelpers<DocType[], DocType, THelpers, RawDocType>;
252
+ $where(argument: string | Function): QueryWithHelpers<
253
+ DocType[],
254
+ DocType,
255
+ THelpers,
256
+ RawDocType,
257
+ QueryOp,
258
+ TDocOverrides,
259
+ TLeanResultType
260
+ >;
195
261
 
196
262
  /** Specifies an `$all` query condition. When called with one argument, the most recent path passed to `where()` is used. */
197
263
  all(path: string, val: Array<any>): this;
@@ -201,7 +267,7 @@ declare module 'mongoose' {
201
267
  allowDiskUse(value: boolean): this;
202
268
 
203
269
  /** Specifies arguments for an `$and` condition. */
204
- and(array: FilterQuery<DocType>[]): this;
270
+ and(array: QueryFilter<RawDocType>[]): this;
205
271
 
206
272
  /** Specifies the batchSize option. */
207
273
  batchSize(val: number): this;
@@ -226,6 +292,15 @@ declare module 'mongoose' {
226
292
  */
227
293
  catch: Promise<ResultType>['catch'];
228
294
 
295
+ /**
296
+ * Executes the query returning a `Promise` which will be
297
+ * resolved with `.finally()` chained.
298
+ */
299
+ finally: Promise<ResultType>['finally'];
300
+
301
+ // Returns a string representation of this query.
302
+ [Symbol.toStringTag]: string;
303
+
229
304
  /** Specifies a `$center` or `$centerSphere` condition. */
230
305
  circle(path: string, area: any): this;
231
306
  circle(area: any): this;
@@ -239,47 +314,126 @@ declare module 'mongoose' {
239
314
  /** Specifies the `comment` option. */
240
315
  comment(val: string): this;
241
316
 
242
- /** Specifies this query as a `count` query. */
243
- count(criteria: FilterQuery<DocType>, callback?: Callback<number>): QueryWithHelpers<number, DocType, THelpers, RawDocType>;
244
- count(callback?: Callback<number>): QueryWithHelpers<number, DocType, THelpers, RawDocType>;
245
-
246
317
  /** Specifies this query as a `countDocuments` query. */
247
318
  countDocuments(
248
- criteria: FilterQuery<DocType>,
249
- options?: QueryOptions<DocType>,
250
- callback?: Callback<number>
251
- ): QueryWithHelpers<number, DocType, THelpers, RawDocType>;
252
- countDocuments(callback?: Callback<number>): QueryWithHelpers<number, DocType, THelpers, RawDocType>;
319
+ criteria?: QueryFilter<RawDocType>,
320
+ options?: QueryOptions<RawDocType>
321
+ ): QueryWithHelpers<number, DocType, THelpers, RawDocType, 'countDocuments', TDocOverrides, TLeanResultType>;
322
+ countDocuments(
323
+ criteria?: Query<any, any>,
324
+ options?: QueryOptions<RawDocType>
325
+ ): QueryWithHelpers<number, DocType, THelpers, RawDocType, 'countDocuments', TDocOverrides, TLeanResultType>;
253
326
 
254
327
  /**
255
- * Returns a wrapper around a [mongodb driver cursor](https://mongodb.github.io/node-mongodb-native/4.9/classes/FindCursor.html).
328
+ * Returns a wrapper around a [mongodb driver cursor](https://mongodb.github.io/node-mongodb-native/7.0/classes/FindCursor.html).
256
329
  * A QueryCursor exposes a Streams3 interface, as well as a `.next()` function.
257
330
  */
258
- cursor(options?: QueryOptions<DocType>): Cursor<DocType, QueryOptions<DocType>>;
331
+ cursor(options?: QueryOptions<RawDocType>): Cursor<Unpacked<ResultType>, QueryOptions<RawDocType>>;
259
332
 
260
333
  /**
261
334
  * Declare and/or execute this query as a `deleteMany()` operation. Works like
262
335
  * remove, except it deletes _every_ document that matches `filter` in the
263
336
  * collection, regardless of the value of `single`.
264
337
  */
265
- deleteMany(filter?: FilterQuery<DocType>, options?: QueryOptions<DocType>, callback?: Callback): QueryWithHelpers<any, DocType, THelpers, RawDocType>;
266
- deleteMany(filter: FilterQuery<DocType>, callback: Callback): QueryWithHelpers<any, DocType, THelpers, RawDocType>;
267
- deleteMany(callback: Callback): QueryWithHelpers<any, DocType, THelpers, RawDocType>;
338
+ deleteMany(
339
+ filter?: QueryFilter<RawDocType>,
340
+ options?: QueryOptions<RawDocType>
341
+ ): QueryWithHelpers<any, DocType, THelpers, RawDocType, 'deleteMany', TDocOverrides, TLeanResultType>;
342
+ deleteMany(
343
+ filter?: Query<any, any>,
344
+ options?: QueryOptions<RawDocType>
345
+ ): QueryWithHelpers<any, DocType, THelpers, RawDocType, 'deleteMany', TDocOverrides, TLeanResultType>;
346
+ deleteMany(filter: QueryFilter<RawDocType>): QueryWithHelpers<
347
+ any,
348
+ DocType,
349
+ THelpers,
350
+ RawDocType,
351
+ 'deleteMany',
352
+ TDocOverrides,
353
+ TLeanResultType
354
+ >;
355
+ deleteMany(filter: Query<any, any>): QueryWithHelpers<
356
+ any,
357
+ DocType,
358
+ THelpers,
359
+ RawDocType,
360
+ 'deleteMany',
361
+ TDocOverrides,
362
+ TLeanResultType
363
+ >;
364
+ deleteMany(): QueryWithHelpers<any, DocType, THelpers, RawDocType, 'deleteMany', TDocOverrides, TLeanResultType>;
268
365
 
269
366
  /**
270
367
  * Declare and/or execute this query as a `deleteOne()` operation. Works like
271
368
  * remove, except it deletes at most one document regardless of the `single`
272
369
  * option.
273
370
  */
274
- deleteOne(filter?: FilterQuery<DocType>, options?: QueryOptions<DocType>, callback?: Callback): QueryWithHelpers<any, DocType, THelpers, RawDocType>;
275
- deleteOne(filter: FilterQuery<DocType>, callback: Callback): QueryWithHelpers<any, DocType, THelpers, RawDocType>;
276
- deleteOne(callback: Callback): QueryWithHelpers<any, DocType, THelpers, RawDocType>;
371
+ deleteOne(
372
+ filter?: QueryFilter<RawDocType>,
373
+ options?: QueryOptions<RawDocType>
374
+ ): QueryWithHelpers<any, DocType, THelpers, RawDocType, 'deleteOne', TDocOverrides, TLeanResultType>;
375
+ deleteOne(
376
+ filter?: Query<any, any>,
377
+ options?: QueryOptions<RawDocType>
378
+ ): QueryWithHelpers<any, DocType, THelpers, RawDocType, 'deleteOne', TDocOverrides, TLeanResultType>;
379
+ deleteOne(filter: QueryFilter<RawDocType>): QueryWithHelpers<
380
+ any,
381
+ DocType,
382
+ THelpers,
383
+ RawDocType,
384
+ 'deleteOne',
385
+ TDocOverrides,
386
+ TLeanResultType
387
+ >;
388
+ deleteOne(filter: Query<any, any>): QueryWithHelpers<
389
+ any,
390
+ DocType,
391
+ THelpers,
392
+ RawDocType,
393
+ 'deleteOne',
394
+ TDocOverrides,
395
+ TLeanResultType
396
+ >;
397
+ deleteOne(): QueryWithHelpers<any, DocType, THelpers, RawDocType, 'deleteOne', TDocOverrides, TLeanResultType>;
277
398
 
278
399
  /** Creates a `distinct` query: returns the distinct values of the given `field` that match `filter`. */
279
- distinct<ReturnType = any>(field: string, filter?: FilterQuery<DocType>, callback?: Callback<number>): QueryWithHelpers<Array<ReturnType>, DocType, THelpers, RawDocType>;
400
+ distinct<DocKey extends string, ResultType = unknown>(
401
+ field: DocKey,
402
+ filter?: QueryFilter<RawDocType>,
403
+ options?: QueryOptions<RawDocType>
404
+ ): QueryWithHelpers<
405
+ Array<
406
+ DocKey extends keyof WithLevel1NestedPaths<DocType>
407
+ ? WithoutUndefined<Unpacked<WithLevel1NestedPaths<DocType>[DocKey]>>
408
+ : ResultType
409
+ >,
410
+ DocType,
411
+ THelpers,
412
+ RawDocType,
413
+ 'distinct',
414
+ TDocOverrides,
415
+ TLeanResultType
416
+ >;
417
+ distinct<DocKey extends string, ResultType = unknown>(
418
+ field: DocKey,
419
+ filter?: Query<any, any>,
420
+ options?: QueryOptions<RawDocType>
421
+ ): QueryWithHelpers<
422
+ Array<
423
+ DocKey extends keyof WithLevel1NestedPaths<DocType>
424
+ ? WithoutUndefined<Unpacked<WithLevel1NestedPaths<DocType>[DocKey]>>
425
+ : ResultType
426
+ >,
427
+ DocType,
428
+ THelpers,
429
+ RawDocType,
430
+ 'distinct',
431
+ TDocOverrides,
432
+ TLeanResultType
433
+ >;
280
434
 
281
435
  /** Specifies a `$elemMatch` query condition. When called with one argument, the most recent path passed to `where()` is used. */
282
- elemMatch<K = string>(path: K, val: any): this;
436
+ elemMatch(path: string, val: any): this;
283
437
  elemMatch(val: Function | any): this;
284
438
 
285
439
  /**
@@ -293,10 +447,18 @@ declare module 'mongoose' {
293
447
  equals(val: any): this;
294
448
 
295
449
  /** Creates a `estimatedDocumentCount` query: counts the number of documents in the collection. */
296
- estimatedDocumentCount(options?: QueryOptions<DocType>, callback?: Callback<number>): QueryWithHelpers<number, DocType, THelpers, RawDocType>;
450
+ estimatedDocumentCount(options?: QueryOptions<RawDocType>): QueryWithHelpers<
451
+ number,
452
+ DocType,
453
+ THelpers,
454
+ RawDocType,
455
+ 'estimatedDocumentCount',
456
+ TDocOverrides,
457
+ TLeanResultType
458
+ >;
297
459
 
298
460
  /** Specifies a `$exists` query condition. When called with one argument, the most recent path passed to `where()` is used. */
299
- exists<K = string>(path: K, val: boolean): this;
461
+ exists(path: string, val: boolean): this;
300
462
  exists(val: boolean): this;
301
463
 
302
464
  /**
@@ -309,98 +471,106 @@ declare module 'mongoose' {
309
471
 
310
472
  /** Creates a `find` query: gets a list of documents that match `filter`. */
311
473
  find(
312
- filter: FilterQuery<DocType>,
313
- projection?: ProjectionType<DocType> | null,
314
- options?: QueryOptions<DocType> | null,
315
- callback?: Callback<DocType[]>
316
- ): QueryWithHelpers<Array<DocType>, DocType, THelpers, RawDocType>;
317
- find(
318
- filter: FilterQuery<DocType>,
319
- projection?: ProjectionType<DocType> | null,
320
- callback?: Callback<DocType[]>
321
- ): QueryWithHelpers<Array<DocType>, DocType, THelpers, RawDocType>;
474
+ filter?: QueryFilter<RawDocType>,
475
+ projection?: ProjectionType<RawDocType> | null,
476
+ options?: QueryOptions<RawDocType> | null
477
+ ): QueryWithHelpers<Array<DocType>, DocType, THelpers, RawDocType, 'find', TDocOverrides, TLeanResultType>;
322
478
  find(
323
- filter: FilterQuery<DocType>,
324
- callback?: Callback<DocType[]>
325
- ): QueryWithHelpers<Array<DocType>, DocType, THelpers, RawDocType>;
326
- find(callback?: Callback<DocType[]>): QueryWithHelpers<Array<DocType>, DocType, THelpers, RawDocType>;
479
+ filter?: Query<any, any>,
480
+ projection?: ProjectionType<RawDocType> | null,
481
+ options?: QueryOptions<RawDocType> | null
482
+ ): QueryWithHelpers<Array<DocType>, DocType, THelpers, RawDocType, 'find', TDocOverrides, TLeanResultType>;
327
483
 
328
- /** Declares the query a findOne operation. When executed, the first found document is passed to the callback. */
329
- findOne(
330
- filter?: FilterQuery<DocType>,
331
- projection?: ProjectionType<DocType> | null,
332
- options?: QueryOptions<DocType> | null,
333
- callback?: Callback<DocType | null>
334
- ): QueryWithHelpers<DocType | null, DocType, THelpers, RawDocType>;
484
+ /** Executes the query as a find and also runs countDocuments, returning [documents, count]. Requires limit, and requires sort unless the schema has a `defaultSort`. */
485
+ findAndCount(): Promise<[ResultType, number]>;
486
+
487
+ /** Declares the query a findOne operation. When executed, returns the first found document. */
335
488
  findOne(
336
- filter?: FilterQuery<DocType>,
337
- projection?: ProjectionType<DocType> | null,
338
- callback?: Callback<DocType | null>
339
- ): QueryWithHelpers<DocType | null, DocType, THelpers, RawDocType>;
489
+ filter?: QueryFilter<RawDocType>,
490
+ projection?: ProjectionType<RawDocType> | null,
491
+ options?: QueryOptions<RawDocType> | null
492
+ ): QueryWithHelpers<DocType | null, DocType, THelpers, RawDocType, 'findOne', TDocOverrides, TLeanResultType>;
340
493
  findOne(
341
- filter?: FilterQuery<DocType>,
342
- callback?: Callback<DocType | null>
343
- ): QueryWithHelpers<DocType | null, DocType, THelpers, RawDocType>;
494
+ filter?: Query<any, any>,
495
+ projection?: ProjectionType<RawDocType> | null,
496
+ options?: QueryOptions<RawDocType> | null
497
+ ): QueryWithHelpers<DocType | null, DocType, THelpers, RawDocType, 'findOne', TDocOverrides, TLeanResultType>;
344
498
 
345
499
  /** Creates a `findOneAndDelete` query: atomically finds the given document, deletes it, and returns the document as it was before deletion. */
346
500
  findOneAndDelete(
347
- filter?: FilterQuery<DocType>,
348
- options?: QueryOptions<DocType> | null,
349
- callback?: (err: CallbackError, doc: DocType | null, res: any) => void
350
- ): QueryWithHelpers<DocType | null, DocType, THelpers, RawDocType>;
351
-
352
- /** Creates a `findOneAndRemove` query: atomically finds the given document and deletes it. */
353
- findOneAndRemove(
354
- filter?: FilterQuery<DocType>,
355
- options?: QueryOptions<DocType> | null,
356
- callback?: (err: CallbackError, doc: DocType | null, res: any) => void
357
- ): QueryWithHelpers<DocType | null, DocType, THelpers, RawDocType>;
501
+ filter?: QueryFilter<RawDocType>,
502
+ options?: QueryOptions<RawDocType> | null
503
+ ): QueryWithHelpers<DocType | null, DocType, THelpers, RawDocType, 'findOneAndDelete', TDocOverrides, TLeanResultType>;
504
+ findOneAndDelete(
505
+ filter?: Query<any, any>,
506
+ options?: QueryOptions<RawDocType> | null
507
+ ): QueryWithHelpers<DocType | null, DocType, THelpers, RawDocType, 'findOneAndDelete', TDocOverrides, TLeanResultType>;
358
508
 
359
509
  /** Creates a `findOneAndUpdate` query: atomically find the first document that matches `filter` and apply `update`. */
360
510
  findOneAndUpdate(
361
- filter: FilterQuery<DocType>,
362
- update: UpdateQuery<DocType>,
363
- options: QueryOptions<DocType> & { rawResult: true },
364
- callback?: (err: CallbackError, doc: DocType | null, res: ModifyResult<DocType>) => void
365
- ): QueryWithHelpers<ModifyResult<DocType>, DocType, THelpers, RawDocType>;
511
+ filter: QueryFilter<RawDocType>,
512
+ update: UpdateQuery<RawDocType>,
513
+ options: QueryOptions<RawDocType> & { includeResultMetadata: true }
514
+ ): QueryWithHelpers<ModifyResult<DocType>, DocType, THelpers, RawDocType, 'findOneAndUpdate', TDocOverrides, TLeanResultType>;
515
+ findOneAndUpdate(
516
+ filter: Query<any, any>,
517
+ update: UpdateQuery<RawDocType>,
518
+ options: QueryOptions<RawDocType> & { includeResultMetadata: true }
519
+ ): QueryWithHelpers<ModifyResult<DocType>, DocType, THelpers, RawDocType, 'findOneAndUpdate', TDocOverrides, TLeanResultType>;
366
520
  findOneAndUpdate(
367
- filter: FilterQuery<DocType>,
368
- update: UpdateQuery<DocType>,
369
- options: QueryOptions<DocType> & { upsert: true } & ReturnsNewDoc,
370
- callback?: (err: CallbackError, doc: DocType, res: ModifyResult<DocType>) => void
371
- ): QueryWithHelpers<DocType, DocType, THelpers, RawDocType>;
521
+ filter: QueryFilter<RawDocType>,
522
+ update: UpdateQuery<RawDocType>,
523
+ options: QueryOptions<RawDocType> & { upsert: true } & ReturnsNewDoc
524
+ ): QueryWithHelpers<DocType, DocType, THelpers, RawDocType, 'findOneAndUpdate', TDocOverrides, TLeanResultType>;
372
525
  findOneAndUpdate(
373
- filter?: FilterQuery<DocType>,
374
- update?: UpdateQuery<DocType>,
375
- options?: QueryOptions<DocType> | null,
376
- callback?: (err: CallbackError, doc: DocType | null, res: ModifyResult<DocType>) => void
377
- ): QueryWithHelpers<DocType | null, DocType, THelpers, RawDocType>;
526
+ filter: Query<any, any>,
527
+ update: UpdateQuery<RawDocType>,
528
+ options: QueryOptions<RawDocType> & { upsert: true } & ReturnsNewDoc
529
+ ): QueryWithHelpers<DocType, DocType, THelpers, RawDocType, 'findOneAndUpdate', TDocOverrides, TLeanResultType>;
530
+ findOneAndUpdate(
531
+ filter?: QueryFilter<RawDocType>,
532
+ update?: UpdateQuery<RawDocType>,
533
+ options?: QueryOptions<RawDocType> | null
534
+ ): QueryWithHelpers<DocType | null, DocType, THelpers, RawDocType, 'findOneAndUpdate', TDocOverrides, TLeanResultType>;
535
+ findOneAndUpdate(
536
+ filter?: Query<any, any>,
537
+ update?: UpdateQuery<RawDocType>,
538
+ options?: QueryOptions<RawDocType> | null
539
+ ): QueryWithHelpers<DocType | null, DocType, THelpers, RawDocType, 'findOneAndUpdate', TDocOverrides, TLeanResultType>;
378
540
 
379
- /** Declares the query a findById operation. When executed, the document with the given `_id` is passed to the callback. */
380
- findById(
381
- id: mongodb.ObjectId | any,
382
- projection?: ProjectionType<DocType> | null,
383
- options?: QueryOptions<DocType> | null,
384
- callback?: Callback<DocType | null>
385
- ): QueryWithHelpers<DocType | null, DocType, THelpers, RawDocType>;
541
+ /** Declares the query a findById operation. When executed, returns the document with the given `_id`. */
386
542
  findById(
387
543
  id: mongodb.ObjectId | any,
388
- projection?: ProjectionType<DocType> | null,
389
- callback?: Callback<DocType | null>
390
- ): QueryWithHelpers<DocType | null, DocType, THelpers, RawDocType>;
391
- findById(
392
- id: mongodb.ObjectId | any,
393
- callback?: Callback<DocType | null>
394
- ): QueryWithHelpers<DocType | null, DocType, THelpers, RawDocType>;
544
+ projection?: ProjectionType<RawDocType> | null,
545
+ options?: QueryOptions<RawDocType> | null
546
+ ): QueryWithHelpers<DocType | null, DocType, THelpers, RawDocType, 'findOne', TDocOverrides, TLeanResultType>;
395
547
 
396
548
  /** Creates a `findByIdAndDelete` query, filtering by the given `_id`. */
397
- findByIdAndDelete(id?: mongodb.ObjectId | any, options?: QueryOptions<DocType> | null, callback?: (err: CallbackError, doc: DocType | null, res: any) => void): QueryWithHelpers<DocType | null, DocType, THelpers, RawDocType>;
549
+ findByIdAndDelete(
550
+ id: mongodb.ObjectId | any,
551
+ options: QueryOptions<RawDocType> & { includeResultMetadata: true }
552
+ ): QueryWithHelpers<ModifyResult<DocType>, DocType, THelpers, RawDocType, 'findOneAndDelete', TDocOverrides, TLeanResultType>;
553
+ findByIdAndDelete(
554
+ id?: mongodb.ObjectId | any,
555
+ options?: QueryOptions<RawDocType> | null
556
+ ): QueryWithHelpers<DocType | null, DocType, THelpers, RawDocType, 'findOneAndDelete', TDocOverrides, TLeanResultType>;
398
557
 
399
558
  /** Creates a `findOneAndUpdate` query, filtering by the given `_id`. */
400
- findByIdAndUpdate(id: mongodb.ObjectId | any, update: UpdateQuery<DocType>, options: QueryOptions<DocType> & { rawResult: true }, callback?: (err: CallbackError, doc: any, res?: any) => void): QueryWithHelpers<any, DocType, THelpers, RawDocType>;
401
- findByIdAndUpdate(id: mongodb.ObjectId | any, update: UpdateQuery<DocType>, options: QueryOptions<DocType> & { upsert: true } & ReturnsNewDoc, callback?: (err: CallbackError, doc: DocType, res?: any) => void): QueryWithHelpers<DocType, DocType, THelpers, RawDocType>;
402
- findByIdAndUpdate(id?: mongodb.ObjectId | any, update?: UpdateQuery<DocType>, options?: QueryOptions<DocType> | null, callback?: (CallbackError: any, doc: DocType | null, res?: any) => void): QueryWithHelpers<DocType | null, DocType, THelpers, RawDocType>;
403
- findByIdAndUpdate(id: mongodb.ObjectId | any, update: UpdateQuery<DocType>, callback: (CallbackError: any, doc: DocType | null, res?: any) => void): QueryWithHelpers<DocType | null, DocType, THelpers, RawDocType>;
559
+ findByIdAndUpdate(
560
+ id: mongodb.ObjectId | any,
561
+ update: UpdateQuery<RawDocType>,
562
+ options: QueryOptions<RawDocType> & { includeResultMetadata: true }
563
+ ): QueryWithHelpers<any, DocType, THelpers, RawDocType, 'findOneAndUpdate', TDocOverrides, TLeanResultType>;
564
+ findByIdAndUpdate(
565
+ id: mongodb.ObjectId | any,
566
+ update: UpdateQuery<RawDocType>,
567
+ options: QueryOptions<RawDocType> & { upsert: true } & ReturnsNewDoc
568
+ ): QueryWithHelpers<DocType, DocType, THelpers, RawDocType, 'findOneAndUpdate', TDocOverrides, TLeanResultType>;
569
+ findByIdAndUpdate(
570
+ id?: mongodb.ObjectId | any,
571
+ update?: UpdateQuery<RawDocType>,
572
+ options?: QueryOptions<RawDocType> | null
573
+ ): QueryWithHelpers<DocType | null, DocType, THelpers, RawDocType, 'findOneAndUpdate', TDocOverrides, TLeanResultType>;
404
574
 
405
575
  /** Specifies a `$geometry` condition */
406
576
  geometry(object: { type: string, coordinates: any[] }): this;
@@ -413,33 +583,33 @@ declare module 'mongoose' {
413
583
  get(path: string): any;
414
584
 
415
585
  /** Returns the current query filter (also known as conditions) as a POJO. */
416
- getFilter(): FilterQuery<DocType>;
586
+ getFilter(): QueryFilter<RawDocType>;
417
587
 
418
588
  /** Gets query options. */
419
- getOptions(): QueryOptions<DocType>;
589
+ getOptions(): QueryOptions<RawDocType>;
420
590
 
421
591
  /** Gets a list of paths to be populated by this query */
422
592
  getPopulatedPaths(): Array<string>;
423
593
 
424
594
  /** Returns the current query filter. Equivalent to `getFilter()`. */
425
- getQuery(): FilterQuery<DocType>;
595
+ getQuery(): QueryFilter<RawDocType>;
426
596
 
427
597
  /** Returns the current update operations as a JSON object. */
428
598
  getUpdate(): UpdateQuery<DocType> | UpdateWithAggregationPipeline | null;
429
599
 
430
600
  /** Specifies a `$gt` query condition. When called with one argument, the most recent path passed to `where()` is used. */
431
- gt<K = string>(path: K, val: any): this;
601
+ gt(path: string, val: any): this;
432
602
  gt(val: number): this;
433
603
 
434
604
  /** Specifies a `$gte` query condition. When called with one argument, the most recent path passed to `where()` is used. */
435
- gte<K = string>(path: K, val: any): this;
605
+ gte(path: string, val: any): this;
436
606
  gte(val: number): this;
437
607
 
438
608
  /** Sets query hints. */
439
609
  hint(val: any): this;
440
610
 
441
611
  /** Specifies an `$in` query condition. When called with one argument, the most recent path passed to `where()` is used. */
442
- in<K = string>(path: K, val: any[]): this;
612
+ in(path: string, val: any[]): this;
443
613
  in(val: Array<any>): this;
444
614
 
445
615
  /** Declares an intersects query for `geometry()`. */
@@ -449,32 +619,91 @@ declare module 'mongoose' {
449
619
  j(val: boolean | null): this;
450
620
 
451
621
  /** Sets the lean option. */
452
- lean<LeanResultType = RawDocType extends Document ? LeanDocumentOrArray<ResultType> : LeanDocumentOrArrayWithRawType<ResultType, Require_id<RawDocType>>>(val?: boolean | any): QueryWithHelpers<LeanResultType, DocType, THelpers, RawDocType>;
622
+ lean(): QueryWithHelpers<
623
+ ResultType extends null
624
+ ? GetLeanResultType<TLeanResultType, ResultType, QueryOp> | null
625
+ : GetLeanResultType<TLeanResultType, ResultType, QueryOp>,
626
+ DocType,
627
+ THelpers,
628
+ RawDocType,
629
+ QueryOp,
630
+ TDocOverrides,
631
+ TLeanResultType
632
+ >;
633
+ lean(
634
+ val: true | LeanOptions
635
+ ): QueryWithHelpers<
636
+ ResultType extends null
637
+ ? GetLeanResultType<TLeanResultType, ResultType, QueryOp> | null
638
+ : GetLeanResultType<TLeanResultType, ResultType, QueryOp>,
639
+ DocType,
640
+ THelpers,
641
+ RawDocType,
642
+ QueryOp,
643
+ TDocOverrides,
644
+ TLeanResultType
645
+ >;
646
+ lean(
647
+ val: false
648
+ ): QueryWithHelpers<
649
+ ResultType extends AnyArray<any>
650
+ ? DocType[]
651
+ : ResultType extends null
652
+ ? DocType | null
653
+ : DocType,
654
+ DocType,
655
+ THelpers,
656
+ RawDocType,
657
+ QueryOp,
658
+ TDocOverrides,
659
+ TLeanResultType
660
+ >;
661
+ lean<LeanResultType = TLeanResultType>(): QueryWithHelpers<
662
+ ResultType extends null
663
+ ? LeanResultType | null
664
+ : LeanResultType,
665
+ DocType,
666
+ THelpers,
667
+ RawDocType,
668
+ QueryOp,
669
+ TDocOverrides,
670
+ LeanResultType
671
+ >;
672
+ lean<LeanResultType = TLeanResultType>(
673
+ val: boolean | LeanOptions
674
+ ): QueryWithHelpers<
675
+ ResultType extends null
676
+ ? LeanResultType | null
677
+ : LeanResultType,
678
+ DocType,
679
+ THelpers,
680
+ RawDocType,
681
+ QueryOp,
682
+ TDocOverrides,
683
+ LeanResultType
684
+ >;
453
685
 
454
686
  /** Specifies the maximum number of documents the query will return. */
455
687
  limit(val: number): this;
456
688
 
457
689
  /** Specifies a `$lt` query condition. When called with one argument, the most recent path passed to `where()` is used. */
458
- lt<K = string>(path: K, val: any): this;
690
+ lt(path: string, val: any): this;
459
691
  lt(val: number): this;
460
692
 
461
693
  /** Specifies a `$lte` query condition. When called with one argument, the most recent path passed to `where()` is used. */
462
- lte<K = string>(path: K, val: any): this;
694
+ lte(path: string, val: any): this;
463
695
  lte(val: number): this;
464
696
 
465
697
  /**
466
698
  * Runs a function `fn` and treats the return value of `fn` as the new value
467
699
  * for the query to resolve to.
468
700
  */
469
- transform<MappedType>(fn: (doc: ResultType) => MappedType): QueryWithHelpers<MappedType, DocType, THelpers, RawDocType>;
701
+ transform<MappedType>(fn: (doc: ResultType) => MappedType): QueryWithHelpers<MappedType, DocType, THelpers, RawDocType, QueryOp, TDocOverrides, TLeanResultType>;
470
702
 
471
703
  /** Specifies an `$maxDistance` query condition. When called with one argument, the most recent path passed to `where()` is used. */
472
704
  maxDistance(path: string, val: number): this;
473
705
  maxDistance(val: number): this;
474
706
 
475
- /** Specifies the maxScan option. */
476
- maxScan(val: number): this;
477
-
478
707
  /**
479
708
  * Sets the [maxTimeMS](https://www.mongodb.com/docs/manual/reference/method/cursor.maxTimeMS/)
480
709
  * option. This will tell the MongoDB server to abort if the query or write op
@@ -483,53 +712,108 @@ declare module 'mongoose' {
483
712
  maxTimeMS(ms: number): this;
484
713
 
485
714
  /** Merges another Query or conditions object into this one. */
486
- merge(source: Query<any, any> | FilterQuery<DocType>): this;
715
+ merge(source: QueryFilter<RawDocType>): this;
716
+ merge(source: Query<any, any>): this;
487
717
 
488
718
  /** Specifies a `$mod` condition, filters documents for documents whose `path` property is a number that is equal to `remainder` modulo `divisor`. */
489
- mod<K = string>(path: K, val: number): this;
719
+ mod(path: string, val: number): this;
490
720
  mod(val: Array<number>): this;
491
721
 
492
722
  /** The model this query was created from */
493
- model: typeof Model;
723
+ model: Model<any>; // Can't use DocType, causes "Type instantiation is excessively deep"
494
724
 
495
725
  /**
496
726
  * Getter/setter around the current mongoose-specific options for this query
497
727
  * Below are the current Mongoose-specific options.
498
728
  */
499
- mongooseOptions(val?: MongooseQueryOptions): MongooseQueryOptions;
729
+ mongooseOptions(val?: QueryOptions<RawDocType>): QueryOptions<RawDocType>;
500
730
 
501
731
  /** Specifies a `$ne` query condition. When called with one argument, the most recent path passed to `where()` is used. */
502
- ne<K = string>(path: K, val: any): this;
732
+ ne(path: string, val: any): this;
503
733
  ne(val: any): this;
504
734
 
505
735
  /** Specifies a `$near` or `$nearSphere` condition */
506
- near<K = string>(path: K, val: any): this;
736
+ near(path: string, val: any): this;
507
737
  near(val: any): this;
508
738
 
509
739
  /** Specifies an `$nin` query condition. When called with one argument, the most recent path passed to `where()` is used. */
510
- nin<K = string>(path: K, val: any[]): this;
740
+ nin(path: string, val: any[]): this;
511
741
  nin(val: Array<any>): this;
512
742
 
513
743
  /** Specifies arguments for an `$nor` condition. */
514
- nor(array: Array<FilterQuery<DocType>>): this;
744
+ nor(array: Array<QueryFilter<RawDocType>>): this;
515
745
 
516
746
  /** Specifies arguments for an `$or` condition. */
517
- or(array: Array<FilterQuery<DocType>>): this;
747
+ or(array: Array<QueryFilter<RawDocType>>): this;
518
748
 
519
749
  /**
520
750
  * Make this query throw an error if no documents match the given `filter`.
521
751
  * This is handy for integrating with async/await, because `orFail()` saves you
522
752
  * an extra `if` statement to check if no document was found.
523
753
  */
524
- orFail(err?: NativeError | (() => NativeError)): QueryWithHelpers<NonNullable<ResultType>, DocType, THelpers, RawDocType>;
754
+ orFail(err?: NativeError | (() => NativeError)): QueryWithHelpers<NonNullable<ResultType>, DocType, THelpers, RawDocType, QueryOp, TDocOverrides, TLeanResultType>;
525
755
 
526
756
  /** Specifies a `$polygon` condition */
527
757
  polygon(path: string, ...coordinatePairs: number[][]): this;
528
758
  polygon(...coordinatePairs: number[][]): this;
529
759
 
530
760
  /** Specifies paths which should be populated with other documents. */
531
- populate<Paths = {}>(path: string | string[], select?: string | any, model?: string | Model<any, THelpers>, match?: any): QueryWithHelpers<UnpackedIntersection<ResultType, Paths>, DocType, THelpers, UnpackedIntersection<RawDocType, Paths>>;
532
- populate<Paths = {}>(options: PopulateOptions | (PopulateOptions | string)[]): QueryWithHelpers<UnpackedIntersection<ResultType, Paths>, DocType, THelpers, UnpackedIntersection<RawDocType, Paths>>;
761
+ populate(
762
+ path: string | string[],
763
+ select?: string | any,
764
+ model?: string | Model<any, THelpers>,
765
+ match?: any
766
+ ): QueryWithHelpers<
767
+ ResultType,
768
+ DocType,
769
+ THelpers,
770
+ RawDocType,
771
+ QueryOp,
772
+ TDocOverrides,
773
+ TLeanResultType
774
+ >;
775
+ populate(
776
+ options: PopulateOptions | (PopulateOptions | string)[]
777
+ ): QueryWithHelpers<
778
+ ResultType,
779
+ DocType,
780
+ THelpers,
781
+ RawDocType,
782
+ QueryOp,
783
+ TDocOverrides,
784
+ TLeanResultType
785
+ >;
786
+ populate<Paths>(
787
+ path: string | string[],
788
+ select?: string | any,
789
+ model?: string | Model<any, THelpers>,
790
+ match?: any
791
+ ): QueryWithHelpers<
792
+ MergePopulatePaths<RawDocType, ResultType, QueryOp, Paths, THelpers, TDocOverrides>,
793
+ DocType,
794
+ THelpers,
795
+ UnpackedIntersection<RawDocType, Paths>,
796
+ QueryOp,
797
+ TDocOverrides,
798
+ UnpackedIntersection<TLeanResultType, Paths>
799
+ >;
800
+ populate<Paths>(
801
+ options: PopulateOptions | (PopulateOptions | string)[]
802
+ ): QueryWithHelpers<
803
+ MergePopulatePaths<RawDocType, ResultType, QueryOp, Paths, THelpers, TDocOverrides>,
804
+ DocType,
805
+ THelpers,
806
+ UnpackedIntersection<RawDocType, Paths>,
807
+ QueryOp,
808
+ TDocOverrides,
809
+ UnpackedIntersection<TLeanResultType, Paths>
810
+ >;
811
+
812
+ /** Add pre middleware to this query instance. Doesn't affect other queries. */
813
+ pre(fn: Function): this;
814
+
815
+ /** Add post middleware to this query instance. Doesn't affect other queries. */
816
+ post(fn: Function): this;
533
817
 
534
818
  /** Get/set the current projection (AKA fields). Pass `null` to remove the current projection. */
535
819
  projection(fields?: ProjectionFields<DocType> | string): ProjectionFields<DocType>;
@@ -537,31 +821,70 @@ declare module 'mongoose' {
537
821
  projection(): ProjectionFields<DocType> | null;
538
822
 
539
823
  /** Determines the MongoDB nodes from which to read. */
540
- read(pref: string | mongodb.ReadPreferenceMode, tags?: any[]): this;
824
+ read(mode: string | mongodb.ReadPreferenceMode, tags?: any[]): this;
541
825
 
542
826
  /** Sets the readConcern option for the query. */
543
827
  readConcern(level: string): this;
544
828
 
545
829
  /** Specifies a `$regex` query condition. When called with one argument, the most recent path passed to `where()` is used. */
546
- regex<K = string>(path: K, val: RegExp): this;
830
+ regex(path: string, val: RegExp): this;
547
831
  regex(val: string | RegExp): this;
548
832
 
549
- /**
550
- * Declare and/or execute this query as a remove() operation. `remove()` is
551
- * deprecated, you should use [`deleteOne()`](#query_Query-deleteOne)
552
- * or [`deleteMany()`](#query_Query-deleteMany) instead.
553
- */
554
- remove(filter?: FilterQuery<DocType>, callback?: Callback<mongodb.UpdateResult>): Query<mongodb.UpdateResult, DocType, THelpers, RawDocType>;
555
-
556
833
  /**
557
834
  * Declare and/or execute this query as a replaceOne() operation. Same as
558
835
  * `update()`, except MongoDB will replace the existing document and will
559
836
  * not accept any [atomic](https://www.mongodb.com/docs/manual/tutorial/model-data-for-atomic-operations/#pattern) operators (`$set`, etc.)
560
837
  */
561
- replaceOne(filter?: FilterQuery<DocType>, replacement?: DocType | AnyObject, options?: QueryOptions<DocType> | null, callback?: Callback): QueryWithHelpers<any, DocType, THelpers, RawDocType>;
838
+ replaceOne(
839
+ filter?: QueryFilter<RawDocType>,
840
+ replacement?: DocType | AnyObject,
841
+ options?: QueryOptions<RawDocType> | null
842
+ ): QueryWithHelpers<any, DocType, THelpers, RawDocType, 'replaceOne', TDocOverrides, TLeanResultType>;
843
+ replaceOne(
844
+ filter?: Query<any, any>,
845
+ replacement?: DocType | AnyObject,
846
+ options?: QueryOptions<RawDocType> | null
847
+ ): QueryWithHelpers<any, DocType, THelpers, RawDocType, 'replaceOne', TDocOverrides, TLeanResultType>;
848
+
849
+ /**
850
+ * Sets this query's `sanitizeProjection` option. With `sanitizeProjection()`, you can pass potentially untrusted user data to `.select()`.
851
+ */
852
+ sanitizeProjection(value: boolean): this;
853
+
854
+ /**
855
+ * Enable or disable schema level projections for this query. Enabled by default.
856
+ * Set to `false` to include fields with `select: false` in the query result by default.
857
+ */
858
+ schemaLevelProjections(value: boolean): this;
562
859
 
563
860
  /** Specifies which document fields to include or exclude (also known as the query "projection") */
564
- select(arg: string | any): this;
861
+ select<RawDocTypeOverride extends { [P in keyof RawDocType]?: any } = {}>(
862
+ arg: string | readonly string[] | Record<string, number | boolean | string | object>
863
+ ): QueryWithHelpers<
864
+ IfEquals<
865
+ RawDocTypeOverride,
866
+ {},
867
+ ResultType,
868
+ ResultType extends any[]
869
+ ? ResultType extends HydratedDocument<any>[]
870
+ ? HydratedDocument<RawDocTypeOverride>[]
871
+ : RawDocTypeOverride[]
872
+ : (ResultType extends HydratedDocument<any>
873
+ ? HydratedDocument<RawDocTypeOverride>
874
+ : RawDocTypeOverride) | (null extends ResultType ? null : never)
875
+ >,
876
+ DocType,
877
+ THelpers,
878
+ IfEquals<
879
+ RawDocTypeOverride,
880
+ {},
881
+ RawDocType,
882
+ RawDocTypeOverride
883
+ >,
884
+ QueryOp,
885
+ TDocOverrides,
886
+ IfEquals<RawDocTypeOverride, {}, TLeanResultType, RawDocTypeOverride>
887
+ >;
565
888
 
566
889
  /** Determines if field selection has been made. */
567
890
  selected(): boolean;
@@ -587,15 +910,16 @@ declare module 'mongoose' {
587
910
  set(path: string | Record<string, unknown>, value?: any): this;
588
911
 
589
912
  /** Sets query options. Some options only make sense for certain operations. */
590
- setOptions(options: QueryOptions<DocType>, overwrite?: boolean): this;
913
+ setOptions(options: QueryOptions<RawDocType>, overwrite?: boolean): this;
591
914
 
592
915
  /** Sets the query conditions to the provided JSON object. */
593
- setQuery(val: FilterQuery<DocType> | null): void;
916
+ setQuery(val: QueryFilter<RawDocType> | null): void;
917
+ setQuery(val: Query<any, any> | null): void;
594
918
 
595
- setUpdate(update: UpdateQuery<DocType> | UpdateWithAggregationPipeline): void;
919
+ setUpdate(update: UpdateQuery<RawDocType> | UpdateWithAggregationPipeline, cloneUpdate?: boolean): void;
596
920
 
597
921
  /** Specifies an `$size` query condition. When called with one argument, the most recent path passed to `where()` is used. */
598
- size<K = string>(path: K, val: number): this;
922
+ size(path: string, val: number): this;
599
923
  size(val: number): this;
600
924
 
601
925
  /** Specifies the number of documents to skip. */
@@ -605,11 +929,11 @@ declare module 'mongoose' {
605
929
  slice(path: string, val: number | Array<number>): this;
606
930
  slice(val: number | Array<number>): this;
607
931
 
608
- /** Specifies this query as a `snapshot` query. */
609
- snapshot(val?: boolean): this;
610
-
611
932
  /** Sets the sort order. If an object is passed, values allowed are `asc`, `desc`, `ascending`, `descending`, `1`, and `-1`. */
612
- sort(arg?: string | { [key: string]: SortOrder | { $meta: 'textScore' } } | [string, SortOrder][] | undefined | null): this;
933
+ sort(
934
+ arg?: string | Record<string, SortOrder | { $meta: any }> | [string, SortOrder][] | undefined | null,
935
+ options?: { override?: boolean }
936
+ ): this;
613
937
 
614
938
  /** Sets the tailable option (for use with capped collections). */
615
939
  tailable(bool?: boolean, opts?: {
@@ -626,22 +950,35 @@ declare module 'mongoose' {
626
950
  /** Converts this query to a customized, reusable query constructor with all arguments and options retained. */
627
951
  toConstructor<RetType = typeof Query>(): RetType;
628
952
 
629
- /** Declare and/or execute this query as an update() operation. */
630
- update(filter?: FilterQuery<DocType>, update?: UpdateQuery<DocType> | UpdateWithAggregationPipeline, options?: QueryOptions<DocType> | null, callback?: Callback<UpdateWriteOpResult>): QueryWithHelpers<UpdateWriteOpResult, DocType, THelpers, RawDocType>;
631
-
632
953
  /**
633
954
  * Declare and/or execute this query as an updateMany() operation. Same as
634
- * `update()`, except MongoDB will update _all_ documents that match
635
- * `filter` (as opposed to just the first one) regardless of the value of
636
- * the `multi` option.
955
+ * `update()`, except MongoDB will update _all_ documents that match `filter`
637
956
  */
638
- updateMany(filter?: FilterQuery<DocType>, update?: UpdateQuery<DocType> | UpdateWithAggregationPipeline, options?: QueryOptions<DocType> | null, callback?: Callback<UpdateWriteOpResult>): QueryWithHelpers<UpdateWriteOpResult, DocType, THelpers, RawDocType>;
957
+ updateMany(
958
+ filter: QueryFilter<RawDocType>,
959
+ update: UpdateQuery<RawDocType> | UpdateWithAggregationPipeline,
960
+ options?: QueryOptions<RawDocType> | null
961
+ ): QueryWithHelpers<UpdateWriteOpResult, DocType, THelpers, RawDocType, 'updateMany', TDocOverrides, TLeanResultType>;
962
+ updateMany(
963
+ filter: Query<any, any>,
964
+ update: UpdateQuery<RawDocType> | UpdateWithAggregationPipeline,
965
+ options?: QueryOptions<RawDocType> | null
966
+ ): QueryWithHelpers<UpdateWriteOpResult, DocType, THelpers, RawDocType, 'updateMany', TDocOverrides, TLeanResultType>;
639
967
 
640
968
  /**
641
969
  * Declare and/or execute this query as an updateOne() operation. Same as
642
970
  * `update()`, except it does not support the `multi` or `overwrite` options.
643
971
  */
644
- updateOne(filter?: FilterQuery<DocType>, update?: UpdateQuery<DocType> | UpdateWithAggregationPipeline, options?: QueryOptions<DocType> | null, callback?: Callback<UpdateWriteOpResult>): QueryWithHelpers<UpdateWriteOpResult, DocType, THelpers, RawDocType>;
972
+ updateOne(
973
+ filter: QueryFilter<RawDocType>,
974
+ update: UpdateQuery<RawDocType> | UpdateWithAggregationPipeline,
975
+ options?: QueryOptions<RawDocType> | null
976
+ ): QueryWithHelpers<UpdateWriteOpResult, DocType, THelpers, RawDocType, 'updateOne', TDocOverrides, TLeanResultType>;
977
+ updateOne(
978
+ filter: Query<any, any>,
979
+ update: UpdateQuery<RawDocType> | UpdateWithAggregationPipeline,
980
+ options?: QueryOptions<RawDocType> | null
981
+ ): QueryWithHelpers<UpdateWriteOpResult, DocType, THelpers, RawDocType, 'updateOne', TDocOverrides, TLeanResultType>;
645
982
 
646
983
  /**
647
984
  * Sets the specified number of `mongod` servers, or tag set of `mongod` servers,