async function myFunction() {\
await pickCollection.deleteMany({}); // clear collection
let voters = await voterCollection.find({}).toArray();
voters.forEach(async (voter) => {
for (let pick of voter.ballot) {
let document = await pickCollection.find({id: pick.id});
if (!document) {
await pickCollection.insertOne(pick);
continue;
}
await pickCollection.updateOne({id: pick.id}, ....); //increment pick's votersCount
}
}
}
I am using MongoDB and wrote this to check if the pick exists in the collection, update it if so and insert if not. The result is not an organized collection of unique picks that are updated accordingly but a mess with identical but separate picks that are sporadically updated.
Logging values in certain order is printed out randomely so it must be the flow of the promises. Is it because existing picks are treated as new because it was checked before the original was actually inserted? The await is supposed to wait for it to insert which in that case is not happening. How do I make it wait? Thanks