push nested loop async await mongodb code example
Example: push nested loop async await mongodb
//Import ObjectId method
ObjectId = require('mongodb').ObjectID;
//Get a promise from DB
const getCollectionItem = (Collection, id) => {
return Collection.find({_id:ObjectId(id)});
}
//Iterate over a list of items to store them in a final list
const forLoopPromisses = async (Collection, idList) => {
let finalList = [];
for (let index = 0; index < idList.length; index++) {
const id = idList[index];
//store the promise
const promss = await getCollectionItem(id);
//you can push promss to a list or do whatever to it next
//Useful to do conditional updates & deletions
//Useful to do what u can't through mongodb aggregate
finalList.push(promss);
}
return finalList;
}