[英]how to insert bulk of data into postgres by using nestJS without loop
我是nestJS的初学者。 如何在不使用循环的情况下将大量数据插入 Postgres。 任何人都可以分享一段对我有帮助的代码吗? 谢谢。
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;
}
}
您可以将DataSource
注入您的服务。 并使用它一次保存多个实体。
@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)
}
}
实际上,您甚至不需要featureRepository
,您可以实例化Feature
class 并填充其属性,而无需create
辅助方法。
有多种方法可以做到这一点,只需阅读typeorm
文档即可。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.