【发布时间】: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