I have a cluster with 1 primary and 2 secondary nodes. Also, I have an atlas function witch uses a multi-document transaction. I faced a problem when I do an update and then read this document using .find()
I always get not updated version of this document. Here is the function:
exports = async function({ query, headers, body}, response) {
const collection = context.services.get("mongodb-atlas").db("zakhar").collection("w");
// clean up and insert init data
await collection.deleteMany({});
await collection.insertOne({"name": 1, "category": "toy"});
await collection.insertOne({"name": 2, "category": "toy"});
await collection.insertOne({"name": 3, "category": "game"});
await collection.insertOne({"name": 4, "category": "game"});
const session = context.services.get("mongodb-atlas").startSession();
const transactionOptions = {
readPreference: "primary",
readConcern: { level: "local" },
writeConcern: { w: "majority" }
};
try {
await session.withTransaction(async () => {
await updateStatus(session);
}, transactionOptions);
return 'ok';
} catch (err) {
await session.abortTransaction();
throw err;
} finally {
await session.endSession();
}
};
async function updateStatus(session, ){
const collection = context.services.get("mongodb-atlas").db("zakhar").collection("w");
const countBeforeUpdate = await collection.find({"category": "toy"}, {}, { session }).toArray();
console.log("countBeforeUpdate: " + countBeforeUpdate.length);
const query = {"name": 1};
const update = {"$set": {"category": "game"}};
await collection.updateOne(query, update, { session })
.then(result => {
const { matchedCount, modifiedCount } = result;
console.log("matchedCount: " + matchedCount);
console.log("modifiedCount: " + modifiedCount);
});
const countAfterUpdate = await collection.find({"category": "toy"}, {}, { session }).toArray();
console.log("countAfterUpdate: " + countAfterUpdate.length);
}
And it is an output, but I expect countAfterUpdate: 1
"countBeforeUpdate: 2",
"matchedCount: 1",
"modifiedCount: 1",
"countAfterUpdate: 2"
I tried to use all other transaction options(readPreference, readConcern, writeConcern), but nothing changed. Also tried to use session.startTransaction(...)
instead of withTransaction()
the question on stackoverflow