Saving a list of Entity using TypeORM

22,453

You can save multiple entities at once by using a list of entities to save as parameter in the repository as described in the doc :

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

You should validate your entities first by using validation tools such as class-validator https://github.com/typestack/class-validator

You can also implement a method isValid(): boolean in your entity class that you can use to determine if your data is correct and then filtering the list according to this function.

You will only spend compute time to check your entities with validators, so it should be quite quick, a lot better than to deal with exceptions coming from the database or with overtuning typeorm.

Share:
22,453
Kha Nguyễn
Author by

Kha Nguyễn

Updated on July 15, 2022

Comments

  • Kha Nguyễn
    Kha Nguyễn almost 2 years

    I'm using Repository class of typeorm to work with my Postgres database.

    My problem is when calling feedRepository.save(feeds), with feedRepository declared as feedRepository: Repository<Feed>, some elements of feeds may be invalid for insertion. How can I force typeorm to skip invalid entities and continue to insert valid ones?

    P/S: I have particular reasons for not using for loop to insert data one by one.

  • Dharita Chokshi
    Dharita Chokshi over 5 years
    Does typeORM guarantees sequence of entities while returning the result of save<T extends DeepPartial<Entity>>(entities: T[], options?: SaveOptions): Promise<T[]>; ??
  • Karl Adler
    Karl Adler about 2 years
    any idea how to get that to work using active record pattern?