使用异步/等待的Nodejs Sequelize事务不回滚
let transaction;
try {
transaction = await connection.sequelize.transaction();
const employee = await Employee.findOne({
where: {
uuid: req.params.uuid
}
});
if (employee) {
await Account.destroy( {
where: {
uuid: employee.accountUuid
}
}, {transaction});
await Employee.destroy({
where: {
uuid: req.params.uuid
}
}, {transaction});
await transactionmit();
return res.status(200).json({
messages: messages.MSG_SUCCESS
});
} else {
return res.status(404).json({
message: constants.EMPLOYEE + messages.MSG_NOT_FOUND
});
}
} catch (error) {
if (transaction) await transaction.rollback();
return res.status(500).json({
message: messages.MSG_CANNOT_DELETE + constants.EMPLOYEE
});
}
我使用这段代码来创建交易。在删除员工失败之前,它可以正常工作。它确实在console.log中调用回滚,但是该帐户仍在数据库中删除。
回答如下:交易应在与where
对象相同的对象中传递。
await Account.destroy({
where: {
uuid: employee.accountUuid
},
transaction
});
参考:Sequelize destroy