I'm trying to map through an array that is returned by mongoose.find() method and i want to push certain objects after querying them from the database and i want to send the resultant array to the response in node . But inside the map method if i log the array , the array is getting updated properly , but if i log it outside the map , the array is empty .
const getProductDetails = async(productId) => {
return new Promise(async(resolve,reject) => {
try{
const matchedProduct = await Product.findById(productId);
resolve(matchedProduct._doc);
}catch(err){
reject({message:err});
}
})
}
const getUserOrders = async (userId) => {
const resArray = [];
try{
const userOrders = await Orders.find({userId:userId})
userOrders.map(order => {
order.Products.map(product => {
getProductDetails(product.ProductId)
.then(response => {
console.log(response)
const productObj = {
...response,
Date:order.Date,
isOrderProcessed:order.isOrderProcessed,
isOrderShipped:order.isOrderShipped,
isOrderDelivered:order.isOrderDelivered
}
resArray.push(productObj);
})
.catch(err => console.log(err))
})
})
return resArray;
}catch(err){
console.log(err);
return {message:err}
}
}
router.get('/getOrders/:userId',async(req,res) => {
try{
const userOrders = await getUserOrders(req.params.userId);
res.status(200).send(userOrders);
}catch(err){
res.status(400).send({message:err});
}
});
Before i send the array , if i try to log the array , the array is empty . But after pushing the orderObj inside the array if i try to log the array , it gets updated correctly after each step . Can anyone tell me what i'm doing wrong ?