How to perform a bulk update in nodejs using Sequelize

While Sequelize doesn’t provide a bulkUpdate() method, both update() and bulkCreate() methods allow you to update multiple rows with a single method.
If you need to update multiple rows with the same values, you can use the update() method

When you need to update multiple rows with different values, you can use the bulkCreate() method.
Bulk update with update() method.

If you need to update multiple rows with the same values, you can use the update() method

When you need to update multiple rows with different values, you can use the bulkCreate() method.
Bulk update with update() method
The update() method is the Sequelize way of generating and executing an UPDATE statement.

When you need to update multiple rows with the same value, you need to add a where option with the right condition to update the rows.

For example, suppose you want to update the status of all rows as active. You can use the following update() method:
Bulk update with bulkCreate() method.
await User.update(
{ status: “active” },
{
where: {
status: [“pending”, “disabled”],
},
}
);
Bulk update with bulkCreate() method
Although the bulkCreate() method is used to INSERT many rows to the table, it has the updateOnDuplicate option to update your rows when there’s a conflict to perform the insert.
Suppose you want to update the status column as follows:
1. id of 2 status as disabled
2. id of 3 status as pending
await User.bulkCreate(
[
{ id: 2, status: “disabled” },
{ id: 3, status: “pending” },
],
{
updateOnDuplicate: [“status”],
}
);
The updateOnDuplicate option accepts an array of values. you need to put the name of the attribute (or column) you wish to update as a string inside the array.

If you don’t add the column name into the updateOnDuplicate option, then the different values in your bulkCreate() method will be ignored.

Leave a comment

Your email address will not be published. Required fields are marked *