Sequelize: How to Update a Record by ID

Updated: December 29, 2023 By: Guest Contributor Post a comment

Overview

Sequelize is a powerful Object-Relational Mapper (ORM) for Node.js, which supports multiple dialects of SQL. One common task when working with ORMs is updating records in the database. This tutorial will guide you through the process of using Sequelize to update a record by its identifier (ID), including various scenarios you might encounter.

Prerequisites

Before proceeding with this tutorial, you should have the following:

  • A basic understanding of Node.js and how to use npm packages.
  • An existing Node.js project with Sequelize installed and configured.
  • A model defined in Sequelize that you wish to update.

Basic Update

To perform a basic update on a record, you will utilize the update method provided by Sequelize models. It allows you to set new values for the fields of the record that matches the given ID.

const User = require('./models').User;

async function updateUser(userId, newUserData) {
  const result = await User.update(newUserData, {
    where: { id: userId }
  });

  return result;
}

In the code snippet above, we define an updateUser function that accepts a user ID and a data object containing the new values for the user’s fields. The update method takes two arguments: an object with new values and an options object where we specify the ID of the user to update.

Update with Validation and Hooks

Sometimes, you may want to perform validations or trigger lifecycle hooks when updating a record. This can be accomplished by passing additional options to the update method.

async function updateUserWithValidation(userId, newUserData) {
  const result = await User.update(newUserData, {
    where: { id: userId },
    validate: true,
    individualHooks: true
  });

  return result;
}

In the above function, the validate option ensures that the new data is validated against the model’s rules, and the individualHooks option triggers model hooks for the update operation.

Updating Multiple Records

Sequelize also allows updating multiple records that match certain criteria. Here’s an example of how to update multiple users within a specific group.

async function updateMultipleUsers(groupId, newUserData) {
  const result = await User.update(newUserData, {
    where: { groupId: groupId }
  });

  return result;
}

Note that when updating multiple records, hooks and validations are not applied by default. You need to enable them explicitly if required.

Advanced Updates with Transactions

In situations where consistency is critical, you might want to perform updates within a transaction. This ensures that if any part of the operation fails, none of the updates are applied.

const { sequelize } = require('./models');

async function updateUserWithinTransaction(userId, newUserData) {
  let result;
  await sequelize.transaction(async (transaction) => {
    result = await User.update(newUserData, {
      where: { id: userId },
      transaction
    });
  });

  return result;
}

We create a new transaction using sequelize.transaction and pass it to the update method as part of the options. If an error occurs, the transaction will be rolled back automatically.

Handling Update Responses

The update method returns an array containing two elements: the first is the number of affected rows, and the second is the actual affected rows (when returning: true is set for supported dialects).

const updatedInfo = await User.update(newUserData, {
  where: { id: userId },
  returning: true // Only supported for PostgreSQL
});

console.log(updatedInfo); // [affectedCount, affectedRows]

Handling the result properly allows you to determine the success of the operation and take further actions if needed.

Conclusion

In conclusion, updating records by ID in Sequelize entails using the update method of a model and involves specifying the values to be updated and the criteria of the record to find. Whether updating a single record or multiple records, it’s possible to perform validations, trigger hooks, or even wrap the operation in a transaction to ensure data consistency. With Sequelize, you have a robust tool at your disposal that simplifies interaction with your database, allowing you to write cleaner and more maintainable application code.