Kha*_*yễn 6 postgresql typescript typeorm
我正在使用Repository typeorm 类来处理我的 Postgres 数据库。
我的问题是在调用 时feedRepository.save(feeds),feedRepository声明为feedRepository: Repository<Feed>, 的某些元素feeds可能无法插入。如何强制 typeorm 跳过无效实体并继续插入有效实体?
P/S:我有特别的理由不使用for loop一一插入数据。
您可以通过使用实体列表将多个实体保存为存储库中的参数,如文档中所述:
/**
* Saves all given entities in the database.
* If entities do not exist in the database then inserts, otherwise updates.
*/
save<T extends DeepPartial<Entity>>(entities: T[], options?: SaveOptions): Promise<T[]>;
/**
* Saves a given entity in the database.
* If entity does not exist in the database then inserts, otherwise updates.
*/
save<T extends DeepPartial<Entity>>(entity: T, options?: SaveOptions): Promise<T>;
Run Code Online (Sandbox Code Playgroud)
您应该首先使用验证工具(例如https://github.com/typestack/class-validator)验证您的实体class-validator
您还可以isValid(): boolean在您的实体类中实现一个方法,您可以使用该方法来确定您的数据是否正确,然后根据此功能过滤列表。
您将只花费计算时间来使用验证器检查您的实体,因此它应该非常快,比处理来自数据库的异常或过度调整 typeorm 好得多。
您在保存大量新行时遇到问题。你必须把它们分成小块。
Typeorm 有一个保存选项块
/**
* Breaks save execution into chunks of a given size.
* For example, if you want to save 100,000 objects but you have issues with saving them,
* you can break them into 10 groups of 10,000 objects (by setting { chunk: 10000 }) and save each group separately.
* This option is needed to perform very big insertions when you have issues with underlying driver parameter number limitation.
*/
chunk?: number;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
17575 次 |
| 最近记录: |