typegraphql - 如何使用 GraphQL 配置 Typegoose 以将子文档引用到另一个文档的一部分?
问题描述
我有一个集合User
,其中包含两个Country
作为子文档嵌入的集合字段。Country
集合用作枚举器,用于在将其插入集合之前进行引用User
。我想将此逻辑应用于我的 GraphQL 和 Typegoose 项目。
在 user.schema.ts 文件中:
import { Field, InputType, ObjectType } from 'type-graphql';
import { prop as Property, Ref } from '@typegoose/typegoose';
import { Country } from './country.model';
@ObjectType()
@InputType('UserInput')
export class User {
@Field(type => ID)
@Property({ required: true })
public _id!: string;
@Field(type => Country)
@Property({ ref: 'Country', required: true })
public country!: Ref<Country>;
}
在 country.schema.ts 文件中:
import { Field, ID, InputType, Int, ObjectType } from 'type-graphql';
import { modelOptions, prop as Property, Ref } from '@typegoose/typegoose';
@modelOptions({ schemaOptions: { collection: 'Country' } })
@ObjectType()
@InputType('CountryInput')
export class Country {
@Field(type => ID)
@Property({ required: true })
_id!: string;
@Field()
@Property({ required: true })
name!: string;
@Field()
@Property({ required: true })
alpha2!: string;
@Field()
@Property({ required: true })
alpha3!: string;
@Field()
@Property({ required: true })
numeric!: string;
}
用户集合有一个名为“Country”的子文档。子文档只有“国家”集合中的“id”和“name”。
{
"_id" : "7392798430",
"country" : {
"id" : "69",
"name" : "Switzerland"
}
}
这是“Country”集合中的文档的样子:
{
"_id" : "6786876687",
"name" : "Switzerland",
"alpha2" : "CH",
"alpha3" : "CHE",
"numeric" : "789"
}
我希望每次创建用户时都能引用国家/地区表。目前,我正在尝试以国家/地区作为属性来查询用户,它给了我错误:
不能为不可为空的字段 User.country 返回 null。每个用户都已经有一个国家/地区子文档。它们都不是空的。这是必需的。
我什至无法正常查询它。我想通过先查询它来测试,然后将它插入到用户表中国家表中不可用的国家,以测试它是否会抛出错误。
如果这很重要,我正在使用 NestJS。
解决方案
推荐阅读
- php - PHP 文件大小只检查第一张图片
- powershell - ForEach 方法后 PowerShell 长度的奇怪行为
- mysql - SQL 跳过 select 的第一个值
- python - 使用 qt Creator 时单击按钮时如何运行 .py 文件
- telegram - 电报 - 发布链接未在网络中打开
- javascript - 如何在 VueJS 中的表格行单击上加载不同的组件?
- python - 在帧之间移动小部件(tkinter & python 3)
- batch-file - 由于不正确的编码或错误,无法让我的批处理脚本工作
- python - 在重定向链接中完成登录表单后如何下载文件
- android - 我无法更新 apk 和图标 google play 发布者