I want to update database inside a for loop.But before my database update for loop ends. (#node js, #mongoose)
-
var patientObj = JSON.parse(JSON.stringify(patients));
for (var i = 0; i < patientObj.length; i++) {
var patientIds = "00" + (i + 1);
var patientNewIdObj = { barCodeId: patientIds}
var currentPatientId = patientObj[i]._id;modelPatient.findOneAndUpdate({ _id: currentPatientId }, patientNewIdObj, { new: true, safe: true }).exec(function (err, patientRet) { if (err) { callBack(callBackResponse.callbackWithDefaultError(err)); } else if (patientRet == null || patientRet == undefined) { callBack(callBackResponse.callbackWithfalseMessage('Invalid patient ID')); } else { callBack(callBackResponse.callbackWithData(patientRet)); } });
}
-
@root FYI
-
Maybe that's because of the loop runs without waiting for your delete process finished. Try an await function.
-
how to use await function for this code.
var patientObj = JSON.parse(JSON.stringify(patients)); for (var i = 0; i < patientObj.length; i++) { var patientIds = "00" + (i + 1); var patientNewIdObj = { barCodeId: patientIds} var currentPatientId = patientObj[i]._id; modelPatient.findOneAndUpdate({ _id: currentPatientId }, patientNewIdObj, { new: true, safe: true }).exec(function (err, patientRet) { if (err) { callBack(callBackResponse.callbackWithDefaultError(err)); } else if (patientRet == null || patientRet == undefined) { callBack(callBackResponse.callbackWithfalseMessage('Invalid patient ID')); } else { callBack(callBackResponse.callbackWithData(patientRet)); } }); }
-
-