我正在尝试将 Typegoose 与 GrqphQL、MongoDB 和 Nest.js 一起使用。我想创建一个可以创建帖子的突变。我为简单的Post创建了模型、服务和解析器。当我尝试运行我的突变来创建一个帖子时,我收到了这个错误:
PostModel 验证失败:部分:Cast to Array 的值失败:
[ [Object: null prototype] { title: 'section 1', body: [ 'section test lalal' ], code: [ "console.log('hello world!)" ], image: [ 'kanow.svg' ] } ]
在路径“部分”
我不知道为什么会收到我尝试使用的此错误:ref,itemsRefs(用于类和字符串值。您可以在此处阅读有关此内容的更多信息:typegoose arrayProp)。创建新属性后PostModel
,我console.log
可以看到每个属性sections
都是一个空数组,但它不应该,因为在里面postInput
我可以找到这个 JSON:
[Object: null prototype] {
title: 'refactored post',
image: 'rest.jpg',
tags: [ 'ref, ref' ],
sections: [
[Object: null prototype] {
title: 'section 1',
body: [Array],
code: [Array],
image: [Array]
}
]
}
我认为这个 json 看起来不错,所以它不应该是这个错误的来源。
我想知道我做错了什么以及为什么它不起作用。下面我附上了一些代码。如果您需要其他任何内容,请在评论中告诉我。
GraphQL 突变:
mutation {
createPost(postInput: {
image: "rest.jpg",
title: "refactored post"
tags: ["ref, ref"]
sections: [{
title: "section 1"
body: ["section test lalal"]
code: ["console.log('hello world!)"]
image: ["kanow.svg"]
}]
}) {
_id
title
tags
sections {
title
body
code
image
}
}
}
post.service.ts:
@Injectable()
export class PostsService {
constructor(@InjectModel(PostModel) private readonly postModel: ReturnModelType<typeof PostModel>) {
}
async create(postInput: CreatePostInput): Promise<DocumentType<PostModel>> {
const createdPost: DocumentType<PostModel> = new this.postModel(postInput);
return await createdPost.save();
}
...
}
post.model.ts:
@ObjectType()
export class PostModel {
@Field(() => ID)
readonly _id: ObjectId;
@Field()
@prop({required: true})
title: string;
@Field()
@prop({nullable: true})
image: string;
@Field(() => [String])
@arrayProp({items: String})
tags: string[];
@Field(() => [SectionModel])
@arrayProp({ref: 'SectionModel'})
sections: Ref<SectionModel>[];
}
section.model.ts:
@ObjectType()
export class SectionModel {
@Field()
@prop({ required: true })
title: string;
@Field(() => [String])
@arrayProp({ items: String })
body: string[];
@Field(() => [String])
@arrayProp({ items: String })
code: string[];
@Field(() => [String])
@arrayProp({ items: String })
image: string[];
}
创建 post.input.ts:
@InputType()
export class CreatePostInput {
@Field()
readonly title!: string;
@Field()
readonly image!: string;
@Field(() => [String])
readonly tags!: string[];
@Field(() => [CreateSectionInput])
readonly sections!: CreateSectionInput[];
}
更新 1
我发现如果我在部分正文中传递一个空数组,那么创建帖子就没有问题。我在下面附上示例查询:
mutation {
createPost(postInput: {
image: "newly created.jpg",
title: "newly created"
tags: ["newly created, ref"]
sections: []
}) {
_id
image
title
tags
sections {
title
body
code
image
}
}
}