Home > OS >  how to insert bulk of data into postgres by using nestJS without loop
how to insert bulk of data into postgres by using nestJS without loop

Time:08-15

i am beginner in nestJS. how can I insert the bulk of data into Postgres without using a loop. can anybody share a piece of code that will be helpful for me? thanks.

import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { Feature } from './feature.entity';

@Injectable()
export class AppService {
  constructor(@InjectRepository(Feature) private readonly featureRepository: Repository<Feature>){}

  async addData(data: any){
    
    for(let i = 0; i< data.length; i  ){
      await this.featureRepository.manager.query('INSERT INTO public.feature(id, name, phone) VALUES ($1, $2, $3)', [data[i].id, data[i].name, data[i].phone])
    }
    return true;
  }
}

CodePudding user response:

you can inject DataSource to your service. and use it for saving multiple entities at once.

@Injectable()
export class AppService {
  constructor(@InjectRepository(Feature) private readonly featureRepository: Repository<Feature>, private readonly dataSource: DataSource){}

  async addData(data: any){
    const features: Feature[] = []
    for(let i = 0; i< data.length; i  ){
      features.push(this.featureRepository.create({/* put your data here */})
    }
    return await this.dataSource.manager.save(features)
  }
}

actually, you don't even need the featureRepository you can instantiate Feature class and fill its property without needing the create helper method.

There is multiple approaches to do it, just read the typeorm documentation.

  • Related