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.