'Create and update in the same sequelize transaction
I want to insert a new row and immediately update it, all within the same sequelize transaction, is this possible?
My code so far:
let transaction;
try {
transaction = await dbcontext.sequelize.transaction();
const newRole = await dbcontext.Role.create({
name: "New Role"
}, { transaction });
await dbcontext.Role.update(
{
name: "New name",
},
{
where: {
id: newRole.id,
},
}, { transaction }
);
await transaction.commit();
console.log("Role commited");
} catch (error) {
console.log("Rollback in progress");
if (transaction) {
await transaction.rollback();
}
console.log(error);
}
Solution 1:[1]
update has only two parameters so the transaction option should be indicated right next to the where option:
await dbcontext.Role.update(
{
name: "New name",
},
{
where: {
id: newRole.id,
},
transaction,
}
);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Anatoly |
