ค้นหาเว็บไซต์

postgresql - การบันทึกรายการของ Entity โดยใช้ TypeORM


ฉันกำลังใช้คลาส Repository ของ typeorm เพื่อทำงานกับฐานข้อมูล Postgres ของฉัน

ปัญหาของฉันคือเมื่อเรียกใช้ feedRepository.save(feeds) โดยที่ feedRepository ถูกประกาศเป็น feedRepository: Repository<Feed> บางองค์ประกอบของ feeds อาจไม่ถูกต้องสำหรับการแทรก ฉันจะบังคับให้ typeorm ข้ามเอนทิตีที่ไม่ถูกต้องและดำเนินการแทรกเอนทิตีที่ถูกต้องต่อไปได้อย่างไร?

ป.ล.: ฉันมีเหตุผลเฉพาะในการไม่ใช้ for loop เพื่อแทรกข้อมูลทีละรายการ

คำตอบ #1

คุณสามารถบันทึกหลายเอนทิตีพร้อมกันได้โดยการใช้รายการของเอนทิตีที่จะบันทึกเป็นพารามิเตอร์ในรีโพซิทอรีตามที่อธิบายไว้ในเอกสาร:

/**
 * 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>;

คุณควรตรวจสอบเอนทิตีของคุณก่อนโดยใช้เครื่องมือตรวจสอบเช่น class-validator https://github.com/typestack/class-validator

คุณยังสามารถสร้างเมธอด isValid(): boolean ในคลาสเอนทิตี้ของคุณได้ ซึ่งคุณสามารถใช้เพื่อตรวจสอบว่าข้อมูลของคุณถูกต้องหรือไม่ จากนั้นกรองรายการตามฟังก์ชันนี้

คุณจะต้องใช้เวลาในการประมวลผลเพียงเพื่อตรวจสอบเอนทิตีของคุณกับตัวตรวจสอบ ดังนั้นมันควรจะค่อนข้างเร็ว ดีกว่าการจัดการข้อยกเว้นที่มาจากฐานข้อมูลหรือการปรับแต่ง typeorm เกินไปมาก

คำตอบ #2

คุณกำลังมีปัญหาในการบันทึกแถวใหม่จำนวนมาก คุณต้องแบ่งพวกมันออกเป็นชุด

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;

บทความที่เกี่ยวข้อง