我使用带有nest.js 的node.js 后端和typeorm 进行数据库操作。
我获取一个包含要保存在 mySQL 数据库中的对象列表的 JSON。该数据库将每天更新,但我只想保存该表中尚未存在的数据。我认为 typeorm 的 repository.save()
已经做到了这一点,但事实并非如此。
save
- Saves a given entity or array of entities. If the entity already exist in the database, it is updated. If the entity does not exist in the database, it is inserted.
也许是因为我在保存时生成了一个 uuid 列,而typorm认为它是一个不同的项目?有人可以帮我解决这个问题吗?
async writeNewEPG(epgData: EpgDataDTO[]){
const data = await this.epgDataRepository.create(epgData);
const response = await this.epgDataRepository.save(data);
return response;
}
实体:
import { Entity, Column, PrimaryColumn, PrimaryGeneratedColumn } from 'typeorm';
@Entity('epg_data')
export class EpgDataEntity {
@PrimaryColumn()
@PrimaryGeneratedColumn('uuid')
uuid: string;
@Column({type: "text", nullable: true})
sname: string;
@Column({type: "text", nullable: true})
title: string;
@Column({type: "int", nullable: true})
begin_timestamp: number;
}
最佳答案
我以前遇到过这个问题;所以我通常首先检查项目是否存在
async writeNewEPG(epgData: EpgDataDTO[]){
let oldData = await this.epgDataRepository.find(epgData);
if (oldDate) {
... update data entity ( oldData.sname = epgData.sname; etc)
} else {
... create new data entity ( oldData = new EpgDataEntity(); )
}
const response = await this.epgDataRepository.save(oldData);
return response;
}
这似乎是对所有内容进行硬编码。
我也尝试过 await Repository.updateOne(oldData)
,有时我会遇到意外的错误。
渴望找出正确答案。
关于mysql - Typeorm 插入数据,即使它存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53906041/