Sling Academy
Home/Node.js/Sequelize: How to Update Record and Return the Result

Sequelize: How to Update Record and Return the Result

Last updated: December 29, 2023

Introduction

Sequelize is a powerful ORM (Object-Relational Mapper) for Node.js, which supports a variety of SQL databases. It helps developers build robust and scalable applications by providing a high-level API to interact with the database using JavaScript objects. One common operation when working with databases is updating records. This tutorial covers how to update records in Sequelize and how to retrieve the updated records in the process.

Basic Update Operations

To begin with, let us see how to perform a basic update operation in Sequelize. Consider we have a model User.

const { Model, DataTypes } = require('sequelize');
class User extends Model {}
User.init({
  username: DataTypes.STRING,
  email: DataTypes.STRING
}, { sequelize, modelName: 'user' });

Updating a user can be as simple as:

await User.update({ email: '[email protected]' }, {
  where: { username: 'johndoe' }
});

This will update the email address of the user with the username ‘johndoe’. However, this does not by default return the updated record.

Returning Updated Records

To get the updated record, you have to specify an additional option:

await User.update({ email: '[email protected]' }, {
  where: { username: 'johndoe' },
  returning: true
});

This will return an array containing two elements, the first is the number of affected rows, and the second is the actual updated records.

Handling the Results

With the data returned, you can handle the results. The update operation returns a promise, which you can handle with async/await or .then():

const [affectedCount, affectedRows] = await User.update(
  { email: '[email protected]' },
  { where: { username: 'johndoe' }, returning: true }
);
// affectedCount is the number of affected rows
// affectedRows is the array of updated records

Advanced Usage

More advanced scenarios may require you to perform updates based on certain conditions, transactions, or hooks. For instance, you may want to automatically update timestamp fields or have custom validation logic.

await sequelize.transaction(async (t) => {
  const options = { where: { username: 'johndoe' }, returning: true, transaction: t };
  const [affectedCount, affectedRows] = await User.update(
    { email: '[email protected]' }, options
  );
});

By using a transaction, we ensure that the update operation is safely executed within the context of the transaction which can be rolled back if anything within it fails.

Error Handling

As with any database operations, error handling is crucial. Ensure you have try/catch blocks or proper error handling mechanisms in place:

try {
  const [affectedCount, affectedRows] = await User.update(
    { email: '[email protected]' },
    { where: { username: 'johndoe' }, returning: true }
  );
} catch (error) {
  console.error('Update failed:', error);
}

This will catch any exceptions thrown during the update operation and log them accordingly.

Conclusion

In conclusion, updating records and fetching the updated data in Sequelize is straightforward once you are familiar with the syntax and options available. Always make sure to handle promises correctly and manage transactions and errors adequately. With these practices, you’ll be able to make the most out of Sequelize when managing data persistence in your applications.

Next Article: How to use regular expressions in Sequelize.js queries

Previous Article: How to use LIMIT and OFFSET in Sequelize.js

Series: Sequelize.js Tutorials

Node.js

You May Also Like

  • NestJS: How to create cursor-based pagination (2 examples)
  • Cursor-Based Pagination in SequelizeJS: Practical Examples
  • MongooseJS: Cursor-Based Pagination Examples
  • Node.js: How to get location from IP address (3 approaches)
  • SequelizeJS: How to reset auto-increment ID after deleting records
  • SequelizeJS: Grouping Results by Multiple Columns
  • NestJS: Using Faker.js to populate database (for testing)
  • NodeJS: Search and download images by keyword from Unsplash API
  • NestJS: Generate N random users using Faker.js
  • Sequelize Upsert: How to insert or update a record in one query
  • NodeJS: Declaring types when using dotenv with TypeScript
  • Using ExpressJS and Multer with TypeScript
  • NodeJS: Link to static assets (JS, CSS) in Pug templates
  • NodeJS: How to use mixins in Pug templates
  • NodeJS: Displaying images and links in Pug templates
  • ExpressJS + Pug: How to use loops to render array data
  • ExpressJS: Using MORGAN to Log HTTP Requests
  • NodeJS: Using express-fileupload to simply upload files
  • ExpressJS: How to render JSON in Pug templates