I am trying to send an array of document IDs as JSON response but the array I obtain as the response is empty. How can I make sure the array is populated first by the document IDs before it is sent as the response?
exports.createItem = async (req,res,next) => {
let itemsIds = [];
req.body.forEach( async element => {
let doc = await Item.findOneAndUpdate({
type: element.type,
color: element.color,
size: element.size
}, {
$inc:{stock: element.stock}
}, {upsert:true, new: true});
itemsIds.push(doc._id);
});
res.status(200).json({
success: true,
itemsIds: itemsIds
})
}
I want to make sure the res.status(200).json({...}) method runs only after all the doc ids are pushed to the mongo DB. Right now I just get the itemsIds as [ ] in the response. How I can make sure itemsIds array is populated by the doc ids first before sending the response?