How to handle multiple Nodejs requests reading, modifying and updating the same document in MongoDB at same time?

Viewed 258

I have the following code where I am using MongoDB and Nodejs. I read data from collection, perform some arithmetic operations on the data and then update the document. My issue is that when multiple requests come at the same time it causes some data to be lost. How can I avoid this?

//Read the Document

const commissionRecord = await CommissionTable.getCommissionRecord(

publicKey

);

// Check if A record Exists or Not

if (commissionRecord.responseData.exists === true) {

// Assigning values to variables

commissionLimit =

commissionRecord.responseData.data.commissionLimit;

commission = commissionRecord.responseData.data.commission;

}

// Perform Arithmetic Operations

commissionLimit = parseInt(commissionLimit) + parseInt(amount);

if (commissionLimit >= 20) {

remainder = commissionLimit % 20;

commission =

parseInt(commission) + Math.floor(commissionLimit / 20);

commissionLimit = parseInt(remainder);

}

if (commissionRecord.responseData.exists === true) {

//Update the document

const result = await CommissionTable.updateCommissionNormal(

publicKey,

commission,

commissionLimit

);

if (result.success) {

return result;

}

The problem is that when all the requests come at the same time then they all read the data together and the updates are all made based on their read data. How to solve this situation?

1 Answers

To avoid race conditions you can use a mutex, Nodejs has a module async-mutex https://www.npmjs.com/package/async-mutex The Idea is to lock all processes to not run a specific function same time, all processes will work async until calling to this function, for this function will be created queue

Related