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?