Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CannotDetermineEntityError when saving entities with TypeORM

Tags:

typeorm

nestjs

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.

like image 645
Hantsy Avatar asked Jun 10 '26 00:06

Hantsy


2 Answers

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.

like image 117
Micael Levi Avatar answered Jun 11 '26 22:06

Micael Levi


You can alternatively specify the target type as per the error message like so:

await manager.save(Post, d)

From the documentation of save() I see there is such a method as:

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

nest version 9.1.8

like image 21
mwangox Avatar answered Jun 11 '26 21:06

mwangox



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!