如何在TypeORM GraphQL Schema中声明对象数组?
解决NestJS GraphQL中用户关联帖子数组的类型错误
问题出在Users类的posts字段声明上,有两个核心问题:
- TypeScript的
[Post]是元组类型,不是数组类型,应该写成Post[] - NestJS GraphQL无法自动推断数组的泛型类型,必须在
@Field装饰器里显式指定类型
修正后的完整代码:
import { Field, ObjectType } from "@nestjs/graphql"; @ObjectType() class Post { @Field() id: string; @Field() title: string; @Field() description: string; } @ObjectType() export class Users { @Field() id: string; @Field() email: string; @Field() token: string; @Field() name: string; @Field({ nullable: true }) role: string; // 显式指定为Post数组类型,按需设置nullable规则 @Field(() => [Post], { nullable: 'itemsAndList' }) posts: Post[]; }
关键说明:
@Field(() => [Post]):通过工厂函数返回数组类型,让GraphQL正确识别这是一个Post列表nullable: 'itemsAndList':允许整个posts列表为null,同时列表中的单个Post项也可为null;如果只需要允许整个列表为空,用nullable: true;不需要为空则直接去掉该配置- 类型从
[Post]改为Post[]:符合TypeScript数组的标准写法,避免元组类型的误解
如果你的项目同时使用TypeORM操作Postgres,还需要在实体类中配置一对多关系,示例如下(供参考):
// user.entity.ts import { Entity, PrimaryGeneratedColumn, Column, OneToMany } from 'typeorm'; import { Post } from './post.entity'; @Entity() export class User { @PrimaryGeneratedColumn('uuid') id: string; @Column() email: string; // 其他字段... @OneToMany(() => Post, post => post.user) posts: Post[]; }
内容的提问来源于stack exchange,提问作者Abhinav Sharma
相关产品推荐
相关产品推荐

