NestJS GraphQL解析器返回对象数组:无法获取suppliers字段
解决方案
1. 定义Supplier的GraphQL DTO
首先为suppliers数组内的对象创建独立的GraphQL类型DTO,确保每个字段都用@Field装饰器暴露:
import { ObjectType, Field, ID } from '@nestjs/graphql'; @ObjectType() export class SupplierDto { @Field(() => ID) _id: string; @Field() supplierName: string; // 替换为你实际的供应商字段,比如contact、address等 // 所有需要在GraphQL中返回的供应商字段,都要添加@Field装饰器 }
2. 修正ResultIngredientDto的suppliers字段
在ResultIngredientDto中给suppliers字段添加@Field装饰器,并指定其类型为SupplierDto的数组:
import { ObjectType, Field, ID } from '@nestjs/graphql'; import { SupplierDto } from './supplier.dto'; // 导入上面定义的SupplierDto @ObjectType() export class ResultIngredientDto { @Field(() => ID) _id: string; @Field() ingredient_name: string; // 关键修改:添加@Field并声明数组类型 @Field(() => [SupplierDto]) suppliers: SupplierDto[]; }
3. 验证修改
重启NestJS服务后,在Apollo Playground重新查询Ingredient接口,即可正常获取suppliers数组字段。
原理:GraphQL仅识别被@Field标记的字段,即便数据库返回了完整数据,未标记的字段不会被纳入GraphQL Schema,因此Playground无法查询到。控制台能打印完整数据是因为Node.js可读取对象所有属性,但GraphQL响应严格遵循定义的Schema返回。
内容的提问来源于stack exchange,提问作者Buddhika
相关产品推荐
相关产品推荐

