|
| 1 | +# Queries in TypeScript |
| 2 | + |
| 3 | +Mongoose's [Query class](../api/query.html) is a chainable query builder that represents a MongoDB query. |
| 4 | +When you call `find()`, `findOne()`, `updateOne()`, `findOneAndUpdate()`, etc. on a model, Mongoose will return a Query instance. |
| 5 | +Queries have a `.then()` function that returns a Promise, so you can use them with `await`. |
| 6 | + |
| 7 | +In TypeScript, the Query class takes the following generic parameters: |
| 8 | + |
| 9 | +```ts |
| 10 | +class Query< |
| 11 | + ResultType, // The type of the result of the query, like `DocType[]` |
| 12 | + DocType, // The hydrated document type of the query's associated model |
| 13 | + THelpers = {}, // Query helpers |
| 14 | + RawDocType = unknown, // The "lean" document type of the query's associated model |
| 15 | + QueryOp = 'find', // The operation that will be executed, like 'find', 'findOne', 'updateOne', etc. |
| 16 | + TDocOverrides = Record<string, never> // Methods and virtuals on the hydrated document |
| 17 | +> |
| 18 | +``` |
| 19 | + |
| 20 | +## Using `lean()` in TypeScript |
| 21 | + |
| 22 | +The [`lean()` method](../tutorials/lean.html) tells Mongoose to skip [hydrating](../api/model.html#model_Model-hydrate) the result documents, making queries faster and more memory efficient. |
| 23 | +`lean()` comes with some caveats in TypeScript when working with the query `transform()` function. |
| 24 | +In general, we recommend calling `lean()` before using the `transform()` function to ensure accurate types. |
| 25 | + |
| 26 | +```ts |
| 27 | +// Put `lean()` **before** `transform()` in TypeScript because `transform` modifies the query ResultType into a shape |
| 28 | +// that `lean()` does not know how to handle. |
| 29 | +const result = await ProjectModel |
| 30 | + .find() |
| 31 | + .lean() |
| 32 | + .transform((docs) => new Map(docs.map((doc) => [doc._id.toString(), doc]))); |
| 33 | + |
| 34 | +// Do **not** do the following |
| 35 | +const result = await ProjectModel |
| 36 | + .find() |
| 37 | + .transform((docs) => new Map(docs.map((doc) => [doc._id.toString(), doc]))) |
| 38 | + .lean(); |
| 39 | +``` |
| 40 | + |
| 41 | +In general, if you're having trouble with `lean()` inferring the correct type, you can try moving `lean()` earlier in the query chain. |
0 commit comments