I'm new to javascript and i'm having a hard time making my response return to wait for my mongodb query finish running inside a forEach loop.
My code is currrently:
exports.applyThesaurus = (req, res, next) => {
let numModified = 0;
var prom = new Promise((resolve,reject) => {
req.file.forEach((obj,idx) => {
wos.updateMany(
{ creator: req.userData.userId},
{ $set: { [req.body.field+".$[element]"] : obj.replaceWith } },
{ arrayFilters: [ { "element": { $in: obj.replaced } } ] }
).then((result) => {
console.log(result.nModified)
numModified += result.nModified
})
.catch((err) => {
res.status(500).json('There was an error while applying the thesaurus.');
})
if( idx === req.file.length -1) {
resolve()
}
})
})
prom.then(() => {
console.log('im returning');
res.status(200).json({message: numModified + ' itens replaced successfully'});
})
}
What happens is that the "i'm returning" console log triggers before the one logging result.nModified
I need to be able to run all the updateMany queries and then respond with the number of updated itens.
Any tips? Thank you very much!