router.post('/createGroups',async (req)=>{
const {leagueID,teams} = req.body
await Promise.all(teams.map((group,rank)=>{
group.map(async(t,index)=>{
if(index === 0){
console.log(index,rank,t)
const createdGroup = new Group({league:leagueID, group:{team:t}, rank:rank+1})
return await createdGroup.save()
}else{
console.log(index,rank,t)
return await Group.findOneAndUpdate(
{league:req.body.leagueID, rank:rank+1},
{$push:{
group:{
$each:[{team:t}]
}
}
})
}
})
}))
})
I am trying to loop over group, take the 1st element, insert a document, wait until the document is inserted, then update the same document to add the remaining elements into the nested array (group).
Basically, I want it to wait until each promise is resolved before proceeding with next item.
I am not sure about my approach so suggestions for how I can achieve this are welcome?