how to update an instance in sequelize code example
Example 1: create or update in sequelize
async function updateOrCreate (model, where, newItem) {
// First try to find the record
const foundItem = await model.findOne({where});
if (!foundItem) {
// Item not found, create a new one
const item = await model.create(newItem)
return {item, created: true};
}
// Found an item, update it
const item = await model.update(newItem, {where});
return {item, created: false};
}
Example 2: update data in sequelize
const objectToUpdate = {
title: 'Hello World',
description: 'Hello World'
}
models.Locale.findAll({ where: { title: 'Hello World'}}).then((result) => {
if(result){
// Result is array because we have used findAll. We can use findOne as well if you want one row and update that.
result[0].set(objectToUpdate);
result[0].save(); // This is a promise
}
})