Hello team,
I want to understand how to implement data concurrency in MongoDB using Nodejs and Mongoose.
Query:
I have 2 collections. In my program, I want to perform the below queries:
Step1: Fetch a key “key1” from collection-1
Step2: If “key1” is true then perform some action in collection-2
else perform some action in collection-3.
My attempted code:
const session = await mongoose.startSession();
try{
session.startTransaction();
let key1 = await coll1.findOne({},{key1:1}, {session}); // step1
if(key1){
await coll2.updateOne({}, {}, {session}); // step2
} else {
await coll3.updateOne({}, {}, {session}); // step2
}
await session.commitTransaction();
} catch (error) {
await session.abortTransaction();
throw error;
} finally {
session.endSession();
}
I have written this code in Nodejs even using transactions. but not able to handle data concurrency properly. I have seen many wrong entries in collection-2 and collection-3.