To update several records at once (from the same table/model) you can use the Model.bulkUpdate()
. Note that by default the bulk hooks will run but the "individual" hooks will not, unless you specify individualHooks: true
in the options. You may also want to specify validate: true
to trigger any custom validators.
If you want to update multiple tables/Models at the same time you should pass them to Promise.all()
to resolve them asynchronously. Regarding the example in your question - you generally want to avoid using await
in a for
loop. This will cause it to run the Promises (which are asynchronous) sequentially, effectively making them synchronous. If each db call takes 1 second, and you make 3, then the total time will be ~3 seconds. If you use the following code to run them concurrently you should see a total time of ~1sec - 3x faster.
const inputs = [
{
model: 'TableOne',
data: {
id: 'id-1',
field1: 'data0',
field2: 'data1',
field3: 'data2',
},
},
{
model: 'TableTwo',
data: {
id: 'id-2',
field1: 'data3',
field2: 'data4',
field3: 'data5',
},
},
];
// loop over the inputs and return an array of promises, one for each update
const promises = inputs.map(input) => {
const { model, data } = input;
return db[model].update(data, { where: { id: data.id } });
});
// resolve all the db calls at once
await Promise.all(promises);