【问题标题】:mongodb typescript type checkingmongodb typescript 类型检查
【发布时间】:2021-11-14 19:30:23
【问题描述】:

在节点中,我使用的是 mongodb 客户端,findMany 查询返回一个文档数组。

我真正需要的是我应该能够确定返回的 Array 是否包含返回类型所期望的所有字段。

我已经定义了一个类型,例如 Game like

export type Game {
 name: string;
 description: string;
 ...
} 

我的查询看起来像

const  games = (await this.games.find({}).toArray()) as Game[];

但我没有找到任何机制来确定响应是否包含Game 类型所需的所有字段。

【问题讨论】:

    标签: node.js typescript mongodb


    【解决方案1】:

    您可以确保返回数组中的文档包含所有使用$exists 的字段。

    const games = (await this.games.find({field1: {$exists: true}, field2: {$exists: true}}).toArray()) as Game[];

    或使用 Game 的按键使其充满活力。

    【讨论】:

      猜你喜欢
      • 2012-09-29
      • 2015-04-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-12-30
      • 2018-10-31
      • 2018-07-29
      相关资源
      最近更新 更多