0
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

  • `forEach()` doesn't do anything with the return value of its callback function. Basically it will not wait for one iteration to asynchronously finish before starting the nest one. Use a standard `for...of` loop instead – Phil Mar 08 '23 at 06:11
  • @Phil nevermind looks like I was mistaken, I tried it again just in case and it worked. Thanksthanks for the answer, sadly the mongodb collection apparently only allows iteration by forEach. Using for... of gave me error ("[collection] is not iterable". Any other ideas? – villaincs Mar 09 '23 at 00:19
  • But it's not a collection? You converted it to an array via `toArray()` – Phil Mar 09 '23 at 00:29
  • @Phil yes I was wrong, the for of works now. Thanks for the help – villaincs Mar 09 '23 at 00:38

0 Answers0