TypeORM upsert - create if not exist
Solution 1:
As pointed out by Tomer Amir, there is currently a partial solution for real upsert and a feature request is ATM opened on TypeORM's repository :
TypeORM upsert feature request
Partial solution :
await connection.createQueryBuilder()
.insert()
.into(Post)
.values(post2)
.onConflict(`("id") DO NOTHING`)
.execute();
await connection.createQueryBuilder()
.insert()
.into(Post)
.values(post2)
.onConflict(`("id") DO UPDATE SET "title" = :title`)
.setParameter("title", post2.title)
.execute();
Old answer actually points to the "update" way of doing what OP was asking for :
There's already a method for it : Repository<T>.save()
, of which documentation says :
Saves all given entities in the database. If entities do not exist in the database then inserts, otherwise updates.
But if you do not specify the id or unique set of fields, the save method can't know you're refering to an existing database object.
So upserting with typeORM is :
let contraption = await thingRepository.save({id: 1, name : "New Contraption Name !"});
Solution 2:
For anyone finding this in 2021, Typeorm's Repository.save()
method will update or insert if it finds a match with a primary key. This works in sqlite too.
From the documentation:
/**
* Saves all given entities in the database.
* If entities do not exist in the database then inserts, otherwise updates.
*/
Solution 3:
For anyone looking for a way to upsert multiple records and is using Postgres and TypeORM, you're able to access the row you're attempting to update/insert via the excluded keyword.
const posts = [{ id: 1, title: "First Post" }, { id: 2, title: "Second Post" }];
await connection.createQueryBuilder()
.insert()
.into(Post)
.values(posts)
.onConflict(`("id") DO UPDATE SET "title" = excluded."title"`)
.execute();
Solution 4:
Use INSERT IGNORE to ignore duplicates on MySQL and Postgres:
await connection.createQueryBuilder()
.insert()
.into(Post)
.values(post)
.orIgnore()
.execute();
Solution 5:
this might help when ONCONFLICT
doesn't work with MySQL. From Github
await getConnection()
.createQueryBuilder()
.insert()
.into(GroupEntity)
.values(updatedGroups)
.orUpdate({ conflict_target: ['id'], overwrite: ['name', 'parentId', 'web', 'avatar', 'description'] })
.execute();