代码之家  ›  专栏  ›  技术社区  ›  Hantsy

使用TypeForm保存实体时无法确定标题错误

  •  0
  • Hantsy  · 技术社区  · 5 年前

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

    Post 是一个 @Entity 班 PostRepository 是一个 Repository 上课 邮递 .

    我试图创造 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 正在接受一个 邮递 .

    0 回复  |  直到 5 年前
        1
  •  2
  •   Micael Levi    5 年前

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

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