NestJS+Apollo Server GraphQL返回对象数组时非空字段报错求助
问题原因分析
核心问题是GraphQL类型声明与实际返回数据结构不匹配:
- 在
ValidatePostRespTypeDto中,data字段通过@Field(() => ValidatePostDto)声明为单个ValidatePostDto对象,但实际你返回的是ValidatePostDto数组。 - GraphQL会严格按照你声明的类型解析返回值,它把整个数组当成了单个
ValidatePostDto对象,而数组本身并没有uuid属性,因此抛出Cannot return null for non-nullable field ValidatePostDto.uuid.错误。
解决方案
修改ValidatePostRespTypeDto中data字段的GraphQL类型声明,明确指定为数组类型:
import { Field, ObjectType } from "@nestjs/graphql"; @ObjectType() export class ValidatePostDto { @Field() uuid: string; // 建议用小写string,和TypeScript原生类型保持一致 @Field() title: string; @Field() body: string; @Field({ nullable: true }) tags?: string; @Field({ nullable: true }) links?: string; @Field({ nullable: true }) attachment?: string; @Field() createdAt: Date; @Field({ nullable: true }) modifiedAt?: Date; } @ObjectType() export class ValidatePostRespTypeDto { // 用[]包裹类型,声明data为数组结构 @Field(() => [ValidatePostDto]) data: ValidatePostDto[]; @Field() count: number; }
额外优化建议
- 统一类型写法:把代码中的
String改为string,TypeScript推荐使用小写的原生类型别名,避免构造函数类型带来的潜在问题。 - 校验Service返回值:确认
postService.getPostData方法返回的data确实是Post实体数组,且实体字段与ValidatePostDto的字段名称完全匹配(比如uuid字段是否存在且非空)。
验证修改
重新启动服务后,执行原GraphQL查询:
query{ getPost(getPostData: {page: 1, limit: 100}) { count data { uuid title body createdAt tags links attachment modifiedAt } } }
此时GraphQL会正确解析数组中的每个ValidatePostDto对象,不再抛出字段为null的错误。
内容的提问来源于stack exchange,提问作者Nick
相关产品推荐
相关产品推荐

