首页 > 解决方案 > 如何防止“MongoError:事务 1 已提交。”?

问题描述

问题

使用 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()

标签: javascriptnode.jsmongodb

解决方案


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


推荐阅读