【问题标题】:Nodejs mongodb find and update multiple documents in transactionNodejs mongodb在事务中查找和更新多个文档
【发布时间】:2020-10-01 10:18:36
【问题描述】:

我有一个 mongo 4.2 副本集。我有 N 个进程同时运行并试图读取一个集合。这个集合就像一个队列。我想读取 100 个元素并在事务中更新它们,这样其他进程就不会尝试读取它们。

我的代码是:

const collection = client.db("test").collection(TEST_COLLECTION);

const session = client.startSession();

try {

    let data = null;

    await session.withTransaction(async () => {
        console.log("starting transaction")

        data = await collection.find({ runId: null }, { _id: 1, limit: 100 }).toArray();

        const idList = data.map(item => item._id.toHexString());

        await collection.updateMany(
            { runId: { $in: idList } },
            { $set: { runId: runId } },
            { session });

        console.log("Successful transaction")
    });

    data.map(item => {
        // process element one by one and update them (no need for transaction here)
    })

} catch (e) {
    console.error("The transaction was aborted due to an unexpected error: " + e);
} finally {
    await session.endSession();
    console.log("Closing transaction")
}

这是我现在得到的代码。问题是 find() 不会接受选项,所以我无法通过会话。这意味着它不会成为交易的一部分。

mongodb 文档指出:在使用驱动程序时,事务中的每个操作都必须与会话相关联(即,将会话传递给每个操作)。

所以我假设这实际上不是事务性的,只是更新部分不能解决我的问题。有没有办法将两者都包含在我的交易中?对此有什么想法吗?其他/更好的选择?

谢谢

编辑: 所以当它击中我时,我盯着我的问题看了 15 分钟。如果我首先使用交易进行更新。然后即使在事务之外使用 runId 进行查询,我也可以实现我的目标。我对吗?就这么简单吗?

EDIT2: Edit1 很愚蠢,现在我不能限制为 100 个项目。回到起点。

EDIT3: 我正在使用本机 mongodb nodejs 驱动程序。

【问题讨论】:

    标签: node.js mongodb transactions acid


    【解决方案1】:

    要在事务中使用find,请使用session 方法传递会话:

    doc = await Customer.findOne({ name: 'Test' }).session(session);
    

    见Transactions in Mongoose

    【讨论】:

    • 感谢您的回答!我忘了提到我使用的是本机 mongodb 驱动程序而不是 mongoose。
    • 我检查了本机驱动程序也具有此功能(mongodb.github.io/node-mongodb-native/3.6/api/…),但我想获得多个文档而不仅仅是一个。所以这就是为什么我想使用 find()
    • 本机驱动程序的find 接受会话作为选项。
    猜你喜欢
    • 2020-04-10
    • 2023-01-30
    • 2020-08-09
    • 2018-05-11
    • 2019-07-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-08
    相关资源
    最近更新 更多