I am building an App and I have a problem inside a for loop.
Inside my function I got two arrays as arguments (payload.data.start and payload.data.end) and I am trying to push it inside the mongodb. My code looks like this
async function emplaceAval (state, payload, blockInfo, context) {
for(var i=0 ; i<payload.data.start.length ; i++) // start and end have the same length
{
const user =await User.findOne({ 'account': payload.data.account })
user.availability.push({start: new Date(payload.data.start[i]+'Z') , end: new Date(payload.data.end[i]+'Z')});
await user.save();
}
}
The problem is that lots of times I lose data. By losing data I mean that the i changes before user.save take place.
I consider to use forEach , but I have two arrays that need to be save together , so I cant .
The second solution I thought is to create an index array . For example if the length of my arrays is 5 , I will create an indexTable=[0 , 1 , 2 , 3 , 4 ] and I will use asyncForEach to this array. But i dont think that this solution is the preferable. Any ideas? Thanks in advance
await&function (err, user)are not compatible with each other,.. IOW: if you want mongoDb to use promise, don't use callbacks. eg. try..const user = await User.findOne({ 'account': payload.data.account });await user.save();Also could you show us your updated code, just update your question.that the i changes before user.save, looking at your revised code, that shouldn't now be happening,. But I would changevar itolet ianyway, this will create a block scoped variable, so I won't be lost even if your async op's go out of sync.awaitonly works if function returns a promise. Just changingvartoletis dummy solution as this will solve problem of closure not promise. Do read more about async-await and promise. Also check what doesuser.saveand other functions called inside for-loop returns.$pushoperation with$each. Show the data you want to update and the expected change made to the document(s), You're concentrating on Promises where that is no the part of the problem which actually needs resolving.