I have below query with mongodb. I am getting array of exercises from the front end and I need to insert them one by one. And also in every exercise I am getting sets so I need to loop again through them and need to create multiple exercise on the behalf of sets as well
Here is the code in my nodejs file
const createExercises = payload.exercises.map(async(exercise) => {
for (let i = 1 ; i <= exercise.sets ; i++) {
console.log(i)
return (await Exercise.findOneAndUpdate(
{ user, exerciseName: exercise.exerciseName, workoutName: payload.workoutName, sets: i },
{ $set: {
exerciseName: exercise.exerciseName, sets: i
}},
{ upsert: true }
))
}
})
console.log(createExercises)
await Promise.all(createExercises)
return reply({ success: true, message: 'success' })
But the problem is I am not able to wait for the response. What I am missing here.
Edit -->
Now the problem is I am getting this in console for console.log(i) and console.log(createExercises)
1
[ Promise {<pending>, domain: Domain { } } ]
2
3
4
5
What should I see
1
2
3
4
5
[ Promise {<pending>, domain: Domain { } } ]
Thanks!!!
returnfrom the first iteration of your loop?!mapcallback - or rather, do you want to return anything at all?exerciseshould be created in database and then I should go further inreplyreturnand it should work, sequentially awaiting everyfindOneOrUpdatein your loop, and running all the loops concurrently for all your exercises