TypeORM upsert - create if not exist

BeyondTheSea picture BeyondTheSea · Oct 14, 2017 · Viewed 35.2k times · Source

Does TypeORM include some functionnality to avoid this :

let contraption = await thingRepository.findOne({ name : "Contraption" });

if(!contraption) // Create if not exist
{
    let newThing = new Thing();
    newThing.name = "Contraption"
    await thingRepository.save(newThing);
    contraption = newThing;
}

Something like :

let contraption = await thingRepository.upsert({ name : "Contraption" });

Answer

BeyondTheSea picture BeyondTheSea · Nov 1, 2017

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 !"});