mysql - Typeorm 插入数据,即使它存在

标签 mysql node.js typescript nestjs typeorm

我使用带有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/

相关文章:

typescript - 从可空类型中提取不可空类型定义

php - MySQL查询错误: "You have an error in your SQL syntax; ..."

node.js - 将链接放入 console.log()。 Node .js

node.js - Node.js 10 的 TypeScript tsconfig 设置?

javascript - bcrypt-nodejs 抛出的“不正确的参数” - Passport

web-applications - Node.js 应用程序可以有静态 URL 吗?

typescript - 如何在 Typescript 接口(interface)中为函数定义返回类型 void?

php - 删除 mysql 搜索中区分大小写的内容

mysql - SQL select 计算两个条件

php - 更改复杂的 INNER JOIN 查询并使用 PHP 显示它