【问题标题】:How to prevent "MongoError: Transaction 1 has been committed."?如何防止“MongoError:事务 1 已提交。”?
【发布时间】:2020-07-09 18:43:39
【问题描述】:

问题

使用 MongoDB 4.2,我正在尝试执行 50,000 个事务(50,000 个数组突变)。就像 90 % 是成功的,但剩下的我得到了:

MongoError:事务 1 已提交。

很遗憾,我什至不明白错误信息!

方法

一位 Reddit 用户建议升级到 4.2 以克服 16 MB oplog 的限制。但这没有帮助。

代码

我认为这里无关紧要,但为了完整起见我的 Node.js 代码:

const rowCollection = client.db('docemur').collection('row')
session.startTransaction()

// Reorder rows according to columns
await rowCollection
  .find({ table: table._id }, { session })
  .forEach(async row => {
    // Reorder the row array
    row.row = sortBy(row.row, unsorted => {
      return findIndex(columns, sorted => unsorted.column === sorted.identifier)
    })

    // Update the now ordered row
    await rowCollection
      .updateOne(
        { _id: row._id },
        { $set: { row: row.row } },
        { session }
      )
  })

await session.commitTransaction()
session.endSession()

【问题讨论】:

  • 更新这么多文档时需要使用bulkWrite
  • @DanStarns 这实际上是一个非常棒的想法。它会更快,可能会解决我的问题。非常感谢!
  • 很酷的东西!我更新了答案!
  • 我还是要测试一下 ;) 很快就会报告。
  • @Julian 你能把上面的代码转换成bulkWrite吗?万一你有代码。我也遇到了同样的错误并尝试了 bulkWrite 但仍然遇到同样的错误

标签: javascript node.js mongodb


【解决方案1】:

更新这么多文档时需要使用bulkWrite

【讨论】:

    猜你喜欢
    • 2014-05-09
    • 1970-01-01
    • 1970-01-01
    • 2015-07-31
    • 1970-01-01
    • 2012-05-26
    • 1970-01-01
    • 2022-07-12
    相关资源
    最近更新 更多