How can i combine two update requests into one?

I now have a code that works.

await Users.update({ selected: false }, { where: { userId: req.body.userId } });
await Users.update(
  {
    selected: req.body.selected,
    descr: req.body.note
  },
  {
    where:
    {
      entId: req.body.id,
      userId: req.body.userId
    }
  }
);

But what if it is possible to combine these two queries into one? I need the ‘selected’ and ‘note’ field that I pass to change conditionally in the table. And all other ‘selected’ fields inherent to the user in the table became false. Unfortunately, I did not find anything like that in the documentation. Thank you in advance for your help!

Answer

Unfortunately there is no such method like bulkUpdate in Sequelize so you need to call update twice and better to use a transaction to make these two queries as a one atomic operation.

await Sequelize.transaction(async transaction => {
  await Users.update({ selected: false }, { where: { userId: req.body.userId }, transaction });
  await Users.update(
    {
      selected: req.body.selected,
      descr: req.body.note
    },
    {
      where:
      {
        entId: req.body.id,
        userId: req.body.userId
      },
      transaction
    }
  );
});

Leave a Reply

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