【发布时间】:2021-08-05 09:54:35
【问题描述】:
我创建了一个 NestJS 并将 TypeORM 用于 RDBMS(我在我的项目中使用了 postgres)。
Post 是 @Entity 类,PostRepository 是 Repository 类 Post。
我试图创建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 的实例。
【问题讨论】: