How to create or update with Node.js Sequelize?

Sometimes, we want to create or update with Node.js Sequelize.

In this article, we’ll look at how to create or update with Node.js Sequelize.

How to create or update with Node.js Sequelize?

To create or update with Node.js Sequelize, we can use the findOne method to check if the object exists before we update it.

For instance, we write

const upsert = async (values, condition) => {
  const obj = await Model
    .findOne({
      where: condition
    })
  if (obj) {
    return obj.update(values);
  }
  return Model.create(values);
}

to call findOne with an object with the condition we’re looking for.

Then if obj exists, we call obj.update to update the object with the values.

Otherwise, we call create with values to create the object with the values.

Then we call upsert in an async function like

await upsert({
  first_name: 'jane'
}, {
  id: 1234
})

Conclusion

To create or update with Node.js Sequelize, we can use the findOne method to check if the object exists before we update it.