I'm currently working on a function that loops through an array and updates the model for each ID, then adds the result to another array.
This is the code snippet I have:
async function getSortedAnimals() {
var i = 0;
var sortedAnimals = [];
ids.forEach(async (id) => {
i++;
const animal = await this.animalModel.findOneAndUpdate(
{ _id: id },
{
$set: {
order: i,
},
},
);
sortedAnimals.push(animal);
});
console.log(sortedAnimals);
return sortedAnimals;
} //function
After logging the sortedAnimals array, it appears to be empty. I can't figure out why! It seems like the loop does not wait for the async operations to complete before moving forward.
Does anyone have any suggestions or solutions for this issue?