如何在没有循环的情况下使用nestJS将大量数据插入postgres



我是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类并填充其属性,而无需create辅助方法。

有多种方法可以做到这一点,只需阅读typeorm文档即可。

最新更新