我有一个集合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。