I use xlsx package to import some data from an excel file and I want to do a bulk update with these data. These data are already in database and if the user import again the same file with some update, I would like it to update only the modified rows.
Currently, I'm doing a loop on the objects and I check if the data has been modified. This is not necessarily very optimised.
Do you think I can use the upsert() function or is there a way to do this?
CodePudding user response:
To perform a bulk update with TypeORM in a NestJS application, you can use the update method of the Repository class.
Here is an example of how you can use the update method to update multiple records in a database table:
import { Injectable } from '@nestjs/common';
import { Repository } from 'typeorm';
import { Entity } from './entity.entity';
@Injectable()
export class EntityService {
constructor(private readonly entityRepository: Repository<Entity>) {}
async updateEntities(entities: Entity[], updates: object): Promise<void> {
await this.entityRepository.update(
entities.map(entity => entity.id),
updates,
);
}
}
and then call your updateEntities like this:
const entities = [{ id: 1, field1: 'old value' }, { id: 2, field1: 'old value' }];
const updates = { field1: 'new value', field2: 'new value' };
await entityService.updateEntities(entities, updates);