在使用 TypeORM 时,我在共享代码存储库中遇到意外行为。
这是导致问题的代码片段:
const filteredProducts = //bulky data.
const productChunks = chunkArray(filteredProducts, 100);
for (const productChunk of productChunks) {
await this.productPriceRepo.insert(productChunk);
console.log('Dumped in Database ', productChunk.length);
}
products.push(filteredProducts);
问题是由
filteredProducts
变量引起的。插入之前,其结构与插入之后不同:
{
"name":"",
"category":"",
"brand":"",
"properties":{
"color":"",
"grade":,
"carrier":"",
"storage":""
},
"price":,
"amazonDate":"",
"country":"",
"resource":"",
"asin":"",
"engine":"",
"url":"",
// After insertion, additional fields are added:
"id": '59c891e',
"createdAt": ,
"updatedAt":
}
此外,我的代码库中有一个
Base
实体类,其中包括 id
、createdAt
和 updatedAt
字段。
export abstract class Base {
@PrimaryGeneratedColumn('uuid')
id: string;
@CreateDateColumn()
createdAt: Date;
@UpdateDateColumn()
updatedAt: Date;
}
我的问题是 TypeORM 插入是否需要这种行为,特别是考虑到
filteredProducts
在插入过程中没有直接使用。
任何见解或指导将不胜感激。
首先。不应这样保存多个插入内容。你应该使用过渡。原因是如果某些项目未保存 - 整个事务应该回滚。在这种情况下,您可以避免数据库中的不一致。
async createMany(users: User[]) {
const queryRunner = this.dataSource.createQueryRunner();
await queryRunner.connect();
await queryRunner.startTransaction();
try {
// your for loop in here...
await queryRunner.commitTransaction();
} catch (err) {
// since we have errors lets rollback the changes we made
await queryRunner.rollbackTransaction();
} finally {
// you need to release a queryRunner which was manually instantiated
await queryRunner.release();
}
}
参见:Nestjs文档