Skip to content

Instantly share code, notes, and snippets.

@CosmoAbdon
Created November 6, 2020 14:53
Show Gist options
  • Save CosmoAbdon/764da3d7296876f2cd1f7b7115faf363 to your computer and use it in GitHub Desktop.
Save CosmoAbdon/764da3d7296876f2cd1f7b7115faf363 to your computer and use it in GitHub Desktop.
Sequelize bulkUpdate.
const bulkUpdate = async (model, dataValues, conditional) => {
const transformValue = (...values) => values.map((v) => JSON.stringify(v));
const checkValue = ([A, B]) => A === B;
const promises = dataValues.map((value) =>
model.update({ ...value }, { where: { [conditional]: value[conditional] } })
);
const results = await Promise.all(promises);
const size = results.filter((r) => checkValue(transformValue(r, [0]))).length;
return size;
};
export default bulkUpdate;
@CosmoAbdon
Copy link
Author

You can use it, calling the method:

const amountFailed = await bulkUpdate(Stock, productsFiltered, 'stock_id');

Since you gonna need to check if theres something which wasn't on the database or something related, you can easily check it using:

if (amountFailed > 0) {
      return res.status(206).json({
        error: `Theres ${amountFailed} products which was not registered previously`,
      });
    }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment