gpt4 book ai didi

node.js - 在 TypeScript 中返回数组的 Mongoose 查询上使用 `lean`

转载 作者:太空宇宙 更新时间:2023-11-03 23:02:04 26 4
gpt4 key购买 nike

我有两个 Mongoose 查询,并决定最好对它们使用 .lean()

对于返回单个文档的,它似乎工作得很好:

let something:Something;
SomethingDocument.findOne({_id:theId}).lean().then( (res) => { something = res;});

问题是当我尝试将它与返回多个结果的查询一起使用时:

let somethings:Something[];
SomethingDocument.find({color:'blue'}).lean().then( (res) => { somethings = res;});

第二次调用出现错误:

Type 'Object' is not assignable to type 'Something[]'.
The 'Object' type is assignable to very few other types. Did you mean to use the 'any' type instead?
Property 'length' is missing in type 'Object'.

如果我尝试进行类型转换,它只会提示类型“Object”中缺少“length”属性。

当我期望得到一组结果时,如何使用lean

...请注意,如果我简单地省略lean,那么一切都会起作用。

最佳答案

Mongoose 类型定义不太好,恕我直言,因此您可以使用以下方法修复它:

let somethings:Something[];
SomethingDocument.find({color:'blue'}).lean().then((res) => { somethings = res as any;});

顺便说一句,如果可以的话,我建议使用 await (你必须将 TS 编译为现代 Ecma 版本):

const somethings = await SomethingDocument.find({color:'blue'}).lean() as Something[];

请注意,前一个版本会捕获 .catch 上的错误,但第二个版本会抛出异常。

关于node.js - 在 TypeScript 中返回数组的 Mongoose 查询上使用 `lean`,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45221722/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com