Reputation: 1151
As Documented on TypeOrm FrameWork Repository.save
should save/insert new values and ignore/update the existing once,
But now I'm facing a problem that it's thrown a duplication error
on existing value and stoping the whole inserting! ( I have a unique column called key
)
My entity:
import { Entity, Column, PrimaryGeneratedColumn, ManyToOne, JoinColumn, PrimaryColumn } from 'typeorm';
import { Source } from '../sources/source.entity';
@Entity({ name: 'articles' })
export class Article {
@PrimaryGeneratedColumn()
id: number;
@Column()
title: string;
@Column({
nullable: true
})
image: string | null;
@Column({
type: "text",
})
url: string;
@Column({
type: "varchar",
unique: true
})
key: string;
@Column({
type: 'datetime',
nullable: true
})
date: Date | null;
@ManyToOne(type => Source, source => source.articles, {eager: true})
@JoinColumn({name: 'source'})
source: Source;
@Column({
type: `text`,
nullable: true
})
description: string | null
}
My Service:
constructor(
@InjectRepository(Article) private readonly articleRepository: Repository<Article>,
private readonly articlesScraper: BlogScraperService
) {
}
async clonningFromScraper() {
let articles = await this.articlesScraper.articles('1');
articles = articles.map(article => ({ ...article, key: decodeURIComponent(article.url).substring(0, 255) }));
return this.articleRepository
.save(articles);
}
Upvotes: 2
Views: 9972
Reputation: 844
If you are going to update the same record, which includes a unique constraint ( in your case, key ), first, you need to find the record from the DB and attach the ID to the new record that you want to update via the save method.
Upvotes: 0
Reputation: 1151
I have ended up solving this by RAW SQL query using the following
return this.articleRepository.query(
"INSERT IGNORE INTO articles ( title, date, url, image, source, description, _key ) VALUES ?", [querableArticles]);
Upvotes: 4