Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

bulkUpdate in sequelize orm

How can we implement bulkUpdate like bulkCreate in sequelize orm, I searched the whole documentation of sequelize but didn't find anything related to bulkUpdate, so I tried to loop update in for loop, it works but is there any other way to update in bulk

like image 347
akshay bagade Avatar asked Feb 27 '19 06:02

akshay bagade


People also ask

How do you do a bulkUpdate in Sequelize?

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

What is Sequelize in PostgreSQL?

Sequelize is a Node. js-based Object Relational Mapper that makes it easy to work with MySQL, MariaDB, SQLite, PostgreSQL databases, and more. An Object Relational Mapper performs functions like handling database records by representing the data as objects.

How do I create a Sequelized database?

The init function is creating the database before sequelize is called. It first opens a connection to postgres and creates the database. If the database already exists, an error will be thrown which we are ignoring. Once it is created we initialize sequelize and send it to the callback.


2 Answers

You can, if you want to update a lot of records with the same values! example: I want to update field "activationStatus" for 10 users at 1 time, 1 user = 1 record in DB and I have Array of user IDs then:

User.update({ activationStatus: 'active'}, {           where: {               id: [1,2,3,4,5,6,7,8,9,10]           }       }); 

it will be analogue of SQL query:

UPDATE User SET activationStatus = 'active' WHERE id IN(1,2,3,4,5,6,7,8,9,10); 

you can find more info about Sequelize Operator Aliases HERE

like image 44
Oleksandr Grin Avatar answered Oct 20 '22 12:10

Oleksandr Grin


Use the bulkCreate to bulkUpdate method.

bulkCreate([...], { updateOnDuplicate: ["name"] }) 

updateOnDuplicate is an array of fields that will be updated when the primary key (or may be unique key) match the row. Make sure you have at least one unique field (let say id) in your model and in the dataArray both for upsert.

For reference refer here

like image 69
Sakthi Panneerselvam Avatar answered Oct 20 '22 13:10

Sakthi Panneerselvam