使用 TypeORM 保存实体时出现 CannotDetermineEntityError

Han*_*tsy 7 typeorm nestjs

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

Post是一个@Entity类,PostRepository是 的一个RepositoryPost

我试图创建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);
      });
    });
  }
}

Run Code Online (Sandbox Code Playgroud)

启动应用程序时,我收到以下错误。


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.

Run Code Online (Sandbox Code Playgroud)

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

Mic*_*evi 9

我认为这几乎就是错误所说的。您不能将文字对象传递给.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;
  })
Run Code Online (Sandbox Code Playgroud)

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


小智 7

您也可以根据错误消息指定目标类型,如下所示:

await manager.save(Post, d)
Run Code Online (Sandbox Code Playgroud)

从 save() 的文档中我看到有这样的方法:

save<Entity, T extends DeepPartial<Entity>>(targetOrEntity: EntityTarget<Entity>, entity: T, options?: SaveOptions): Promise<T & Entity>;
Run Code Online (Sandbox Code Playgroud)

巢版本9.1.8