【问题标题】:knex transaction not working in nodejsknex事务在nodejs中不起作用
【发布时间】:2017-12-16 01:17:16
【问题描述】:

我在环回中使用 knex 进行 mysql 的 DB 操作。 我的任务是使用事务更新 2 表。 当我在一个表中输入新条目时,我想使用该条目的 id 进行第二次查询操作。

但是当事务抛出错误时,如果第二个表条目抛出错误,它不会回滚数据/删除第一个表条目。但在我的情况下,事务总是提交而不是回滚我把我的示例代码放在下面:

addTest : (data) => {
  return new promise(function(resolve, reject) {
    knex.transaction(function(t) {
       return knex('foo')
       .transacting(t)
       .insert({
          foo_id: data.foo_id ? data.foo_id : null,
          foo_name: data.foo_name ? data.foo_name : null,
          date_entered : new Date()
        })
       .then(function() {
          return knex('bar')
          .transacting(t)
          .insert({
            bar_id: data.bar_id ? data.bar_id : null,
            bar_name : data.bar_name ? data.bar_name : null
          })

       })
       .then(t.commit) 
        .catch(function(e) {
          t.rollback();
          throw e;
        })      
    })
    .then(function() {
     // it worked
     // resolve('sucess');
     console.log('success');
    })
    .catch(function(e) {
     // it failed
     console.log('error'+e);
    }); 
  });
}

请给我合适的建议。 谢谢你

【问题讨论】:

    标签: mysql node.js loopbackjs knex.js


    【解决方案1】:

    您可以避免自己致电t.committ.rollback。见the docs

    让你的代码在事务函数中像这样

    return t.insert({}).into('foo').returning('id') .then( function(idArray) { return t.insert({fooId: idArray[0]}).into('bar') })

    这让 knex 根据该承诺的结果自行处理提交和回滚。另外,请注意我是如何获得插入的fooId 并将其应用于insertion 的bar 对象。问题中提到了这一点。

    【讨论】:

    • 您未定义的绑定是因为您的数据库中没有列;查询无法插入。如果没有看到您用于获取该错误的代码(以及您的数据库表的定义),其余所有内容都很难理解
    • 根据文档,如果 knex.transaction(function(t) { 返回一个 Promise(就像你的那样),它将根据该承诺的分辨率自动调用 t.committ.rollback。您的代码也调用它可能是您的问题的原因(超出未定义的绑定并且未在第二个查询中使用第一个插入的 id)。要么自己调用t.committ.rollback,不返回promise,要么返回promise链,让Knex处理事务的解决。
    • .returning() is not supported by mysql and will not have any effect. 根据文档,在 mysql 中返回('id')将不起作用
    猜你喜欢
    • 2022-01-15
    • 2018-04-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-18
    • 2018-04-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多