首页 > 解决方案 > NestJS/TypeORM 错误:插入记录时作为 UUID 传递的值不是字符串

问题描述

我创建了一个 NestJS 示例应用程序,它使用 TypeORM 来访问 Postgres 数据库。

可以从此链接找到完整的代码

有两个这样的实体。

@Entity({ name: 'posts' })
export class PostEntity {
  @PrimaryGeneratedColumn('uuid')
  id?: string;

  @Column()
  title: string;

  @Column({ nullable: true })
  content?: string;

  @OneToMany((type) => CommentEntity, (comment) => comment.post, {
    cascade: true,
  })
  comments?: Promise<CommentEntity[]>;

  @ManyToOne((type) => UserEntity, { nullable: true })
  @JoinColumn({ name: 'author_id' })
  author?: UserEntity;

  @RelationId((post: PostEntity) => post.author)
  authorId?: string;

  @CreateDateColumn({ name: 'created_at', type: 'timestamp', nullable: true })
  createdAt?: Date;

  @UpdateDateColumn({ name: 'updated_at', type: 'timestamp', nullable: true })
  updatedAt?: Date;
}

@Entity({ name: 'comments' })
export class CommentEntity {
  @PrimaryGeneratedColumn('uuid')
  id: string;

  @Column()
  content: string;

  @ManyToOne((type) => PostEntity, (p) => p.comments)
  @JoinColumn({ name: 'post_id' })
  post: PostEntity;

  @RelationId((comment: CommentEntity) => comment.post)
  postId?: string;

  @CreateDateColumn({ name: 'created_at', type: 'timestamp' })
  createdAt: Date;
}

通过 GraphQL 端点添加评论时,将调用以下代码

  addComment(id: string, comment: string): Observable<Comment> {
    const entity = new CommentEntity();
    Object.assign(entity, {
      content: comment,
      postId: id,
    });
    return from(this.commentRepository.save(entity)).pipe(
      map((c) => {
        return { id: c.id, content: c.content } as Comment;
      }),
    );
  }

运行 e2e 测试时,它将因错误消息而失败(我添加了一个console.log以在响应正文中打印 GraphQL 错误):

addComment errors: [{"message":"The value passed as UUID is not a string"}]

标签: postgresqlgraphqlnestjstypeorm

解决方案


推荐阅读