【发布时间】:2020-06-27 04:45:28
【问题描述】:
我对如何使用 GraphQL 查询 mongodb 中的 ref 集合有疑问。 我有两个系列:People 和 Cat。人们将拥有零或一只猫,而猫将属于一个人。
首先,我使用graphql创建一个People,然后复制返回的People的ID。
接下来,我将那个人的 ID 传递给 CreateCatService 来创建一只猫,这样这个创建的猫就属于之前创建的人了。
现在的问题是我无法查询 ref(嵌套)集合的数据。
mutation {
createCat(
input: {
name: "my cat"
age: 1
breed: "test"
people: "5e6edf120e27eb369db9ceaa" <----- People's id
}
) {
id
name
people {
name <--- return null ???
}
}
}
如果我查询猫,嵌套的人为空,它显示错误:"message": "ID cannot represent value: <Buffer 5e 6e df
{
cats {
name
people {
id
}
}
}
下面是我的架构和代码生成 typedef。
export const PeopleSchema = new mongoose.Schema({
name: String,
cat: {type: mongoose.SchemaTypes.ObjectId, ref: "Cat"}
})
export const CatSchema = new mongoose.Schema({
name: String,
age: Number,
breed: String,
people: {type: mongoose.Schema.Types.ObjectId, ref: 'People'}
});
@ObjectType()
export class PeopleType {
@Field(() => ID)
id: string;
@Field()
name: string;
@Field(type => CatType, { nullable: true })
cat?: CatType
}
@ObjectType()
export class CatType {
@Field(() => ID)
id: string;
@Field()
readonly name: string;
@Field(() => Int)
readonly age: number;
@Field()
readonly breed: string;
@Field(type => PeopleType, {nullable: true})
readonly people?: PeopleType;
}
我的猫输入:
@InputType()
export class CatInput {
@Field()
readonly name: string;
@Field(() => Int)
readonly age: number;
@Field()
readonly breed: string;
@Field()
readonly people: string; // this will be the people's id
}
我的 CreateCatService
async create(createCatDto: CatInput): Promise<Cat> {
const createdCat = new this.catModel(createCatDto);
return await createdCat.save();
我的 CatResolver
@Mutation(() => CatType)
async createCat(@Args('input') input: CatInput) {
return this.catsService.create(input);
【问题讨论】:
标签: mongodb graphql nestjs typegraphql