最新消息: 电脑我帮您提供丰富的电脑知识,编程学习,软件下载,win7系统下载。

使用异步等待的Nodejs Sequelize事务不回滚

IT培训 admin 3浏览 0评论

使用异步/等待的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

使用异步/等待的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

发布评论

评论列表 (0)

  1. 暂无评论