首页 > 解决方案 > 使用 TypORM 返回一个类型数组

问题描述

我是第一次使用 typeorm。我正在创建用户 - 配置文件一对一的关系。当我尝试查询时profiles,我得到了错误Cannot return null for non-nullable field Profile.firstName

我的用户实体

@ObjectType()
@Entity("users")
export class User extends BaseEntity{

    @Field()
    @PrimaryGeneratedColumn("uuid")
    id: string;

    @Field()
    @OneToOne(() => Profile, profile => profile.user) 
    @JoinColumn()
    profile: Profile;

    @Field()
    @Column({ nullable: true }) 
    profileId: string;

}

我的个人资料实体:

@ObjectType()
@Entity("profile")
export class Profile extends BaseEntity{

    @Field()
    @PrimaryGeneratedColumn("uuid")
    id: string;

    @OneToOne(() => User, user => user.profile)
    user: User;
}

我的个人资料解析器查询

@Resolver()
export class ProfileResolver {

  @Query(() => Profile)
  async profiles(
  ) {
    const profiles = await Profile.find()
    console.log("Profiles", profiles) // This contains the right data
    return profiles
  }
}

当我第一次注册用户时,我确保首先创建一个配置文件,然后将其附加到用户。

创建用户时我的注册突变

  @Mutation(() => Boolean)
  async register(
    @Arg('email') email: string,
    @Arg('password') password: string
  ) {
      const hashedPassword = await hash(password, 12)
      const profile: Profile = Profile.create()
      await profile.save()
      const user: User =  User.create({
        email,
        password: hashedPassword,
        profileId: profile.id,
        profile: profile
      })
      console.log(user) // It contains the user with a relative profile

我还尝试在此处添加该字段:

const profile: Profile = Profile.create({firstName: "test})

但我总是得到错误:

Cannot return null for non-nullable field Profile.firstName

当我运行查询时:

query{
  profiles{
    firstName
  }
}

我检查了其他类似的问题,但我没有设法解决它

标签: graphqltypeorm

解决方案


推荐阅读