TypeScript 中的查询
¥Queries in TypeScript
Mongoose 的 查询类 是一个可链式查询构建器,用于表示 MongoDB 查询。当你在模型上调用 find()
、findOne()
、updateOne()
、findOneAndUpdate()
等函数时,Mongoose 将返回一个查询实例。查询具有一个返回 Promise 的 .then()
函数,因此你可以将它们与 await
一起使用。
¥Mongoose's Query class is a chainable query builder that represents a MongoDB query.
When you call find()
, findOne()
, updateOne()
, findOneAndUpdate()
, etc. on a model, Mongoose will return a Query instance.
Queries have a .then()
function that returns a Promise, so you can use them with await
.
在 TypeScript 中,Query 类采用以下泛型参数:
¥In TypeScript, the Query class takes the following generic parameters:
class Query<
ResultType, // The type of the result of the query, like `DocType[]`
DocType, // The hydrated document type of the query's associated model
THelpers = {}, // Query helpers
RawDocType = unknown, // The "lean" document type of the query's associated model
QueryOp = 'find', // The operation that will be executed, like 'find', 'findOne', 'updateOne', etc.
TDocOverrides = Record<string, never> // Methods and virtuals on the hydrated document
>
TypeScript 中使用 lean()
¥Using lean()
in TypeScript
lean()
方法 指示 Mongoose 跳过 hydrating 的结果文档,从而使查询速度更快、内存利用率更高。在使用查询 transform()
函数时,lean()
在 TypeScript 中有一些注意事项。通常,我们建议在使用 transform()
函数之前调用 lean()
,以确保类型准确。
¥The lean()
method tells Mongoose to skip hydrating the result documents, making queries faster and more memory efficient.
lean()
comes with some caveats in TypeScript when working with the query transform()
function.
In general, we recommend calling lean()
before using the transform()
function to ensure accurate types.
// Put `lean()` **before** `transform()` in TypeScript because `transform` modifies the query ResultType into a shape
// that `lean()` does not know how to handle.
const result = await ProjectModel
.find()
.lean()
.transform((docs) => new Map(docs.map((doc) => [doc._id.toString(), doc])));
// Do **not** do the following
const result = await ProjectModel
.find()
.transform((docs) => new Map(docs.map((doc) => [doc._id.toString(), doc])))
.lean();
通常,如果你在 lean()
推断正确类型时遇到问题,可以尝试将 lean()
移到查询链的更早位置。
¥In general, if you're having trouble with lean()
inferring the correct type, you can try moving lean()
earlier in the query chain.