在以 TypeScript 返回数组的 mongoose 查询上使用 `lean`

Wil*_*lyC 2 mongoose mongodb node.js typescript

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

对于返回单个文档的文档,它似乎工作正常:

let something:Something;
SomethingDocument.findOne({_id:theId}).lean().then( (res) => { something = res;});
Run Code Online (Sandbox Code Playgroud)

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

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

第二个调用给出了错误:

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'.
Run Code Online (Sandbox Code Playgroud)

如果我尝试进行类型转换,它只会抱怨“对象”类型中缺少“长度”属性。

lean当我期望一系列结果时如何使用?

...请注意,如果我只是省略lean它所有的作品。

lil*_*zek 5

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

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

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

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

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

  • Await 在您的代码中引入了语法更改。这是一个新的整体讨论的主题,所以你应该更好地研究它的用法和使用它的含义。我指出它是因为更清晰易读且更短。顺便说一句,您还可以将 `await` 与 `Promise.all` 的结果一起使用。 (3认同)