Update OR Create function for Sequelize

March 18, 2019

A lot of times when creating records in a database, we'd like to know whether the record already existed, or at least partially did, and now we can add some more attributes to it.

This is when a update or create function is useful.

JS Function to update or create records in Sequelize

const updateOrCreate = (model, where, newItem, beforeCreate) => {
    // Try to find record using findOne
    return model
        .findOne({ where })
        .then(item => {
            if (!item) {
                // Item doesn't exist, so we create it

                // Custom promise to add more data to the record
                // Being saved (optional)
                Promise.resolve(beforeCreate)
                    .then(() =>
                        model.create(newItem)
                            .then(item => ({ item, created: true }))
                    )
            }

            // Item already exists, so we update it
            return model
                .update(newItem, {where: where})
                .then(item => ({ item, created: false }))
        })
}

We can call the function like so:

updateOrCreate(
    EmployeeModel,
    {
        id: {
            [Op.eq]: employeeID
        }
    },
    {
        status: "full-time"
    }
)