【发布时间】:2022-12-27 22:50:10
【问题描述】:
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;
}
}
【问题讨论】:
-
It'd be helpful if you added more details such as how are you currently inserting any data into postgres from your app, are you using any ORM etc? Details along with sn-ps of existing code would be very helpful in understanding
-
yeah, i added a sample of code that I am using. this is not actual code but i am using this style for coding
-
can you help me with a better style of coding without loop. because my application inserts thousands of records into the database at once
-
you can generate a string of values first using the for loop, then you can insert all the values at once which should result in a much faster query. For example INSERT INTO table(a, b, c) VALUES (6, 5, 7), (1, 2, 6), (8, 6, 5) ...
标签: javascript node.js postgresql nestjs