【问题标题】:CannotDetermineEntityError when saving entities with TypeORM使用 TypeORM 保存实体时出现无法确定实体错误
【发布时间】:2021-08-05 09:54:35
【问题描述】:

我创建了一个 NestJS 并将 TypeORM 用于 RDBMS(我在我的项目中使用了 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 的实例

【问题讨论】:

    标签: nestjs typeorm


    【解决方案1】:

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

    以上方法可以解决这个问题。

    【讨论】:

    • 我使用d as Post 将其转换为Post,为什么这不起作用。 typescript 中的对象字面量和实例有什么区别?
    • 区别不在于ts,而在于js。 new Foo() 对象将是 instance of Foo,而仅具有 Foo 形状的文字对象则不会。并且 TypeORM 期望使用 Foo 的实例
    • btw 强类型语言中的类型转换允许我们转换类型。由于 javascript 不是强类型的,所以您使用的 type 断言 在运行时将不再存在。见this example
    猜你喜欢
    • 1970-01-01
    • 2019-04-03
    • 1970-01-01
    • 1970-01-01
    • 2014-09-05
    • 1970-01-01
    • 2012-10-01
    • 1970-01-01
    • 2014-02-19
    相关资源
    最近更新 更多