首页 > 解决方案 > mongodb typescript 类型检查

问题描述

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

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

我已经定义了一个类型,例如游戏

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

我的查询看起来像

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

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

标签: node.jstypescriptmongodb

解决方案


您可以确保返回数组上的文档包含所有使用$exists.

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

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


推荐阅读