使用 TypeORM 保存实体时无法确定实体错误

时间:2021-05-15 14:10:14

标签: nestjs typeorm

我创建了一个 NestJS 并为 RDBMS 使用了 TypeORM(我在我的项目中使用了 postgres)。

Post@Entity 类,PostRepositoryRepositoryPost 类。

我试图创建 OnModuleInit 服务来初始化一些数据。

@Injectable()
export class PostsDataInitializer implements OnModuleInit {
  private data: Post[] = [
    {
      title: 'Generate a NestJS project',
      content: 'content',
    },
    {
      title: 'Create GrapQL APIs',
      content: 'content',
    },
    {
      title: 'Connect to Postgres via TypeORM',
      content: 'content',
    },
  ];

  constructor(private readonly postRepository: PostRepository) {}
  async onModuleInit(): Promise<void> {
    await this.postRepository.manager.transaction(async (manager) => {
      // NOTE: you must perform all database operations using the given manager instance
      // it's a special instance of EntityManager working with this transaction
      // and don't forget to await things here
      await manager.delete(Post, {});
      console.log('deleted: {} ');
      this.data.forEach(async (d) => await manager.save(d as Post));
      const savedPosts = await manager.find<Post>(Post);
      savedPosts.forEach((p) => {
        console.log('saved: {}', p);
      });
    });
  }
}

启动应用程序时,出现以下错误。


CannotDetermineEntityError: Cannot save, given value must be instance of entity class, instead object literal is given. Or you must specify an entity target to method call.

但是上面的 save 正在接受 Post 的一个实例。

1 个答案:

答案 0 :(得分:2)

我认为这与错误所说的差不多。您不能将文字对象传递给 .save

  private data = [
    {
      title: 'Generate a NestJS project',
      content: 'content',
    },
    {
      title: 'Create GrapQL APIs',
      content: 'content',
    },
    {
      title: 'Connect to Postgres via TypeORM',
      content: 'content',
    },
  ].map(data => {
    const post = new Post();
    Object.assign(post, data);
    return post;
  })

以上可能会解决这个问题。

相关问题