Search code examples
nestjstypeorm

CannotDetermineEntityError when saving entities with TypeORM


I created a NestJS and used TypeORM for the RDBMS(I used postgres in my project).

Post is an @Entity class, PostRepository is a Repository class for Post.

I was trying to create OnModuleInit service to initialize some data.

@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);
      });
    });
  }
}

When starting up the application, I got the following error.


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.

But the above save was accepting an instance of Post.


Solution

  • I think it is pretty much what the error says. You cannot pass literal objects to .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;
      })
    

    the above might solve this.