I am currently facing an issue while trying to retrieve multiple objects from MongoDB using mongoose. In my database, I have two primary collections known as user and order.
The user collection consists of an array called 'order history', which in turn contains orders.
Whenever I attempt to add an order to the orders array, it gets pushed successfully. However, the problem arises when I try to access these orders outside of the loop, as the asynchronous operation within the loop results in an empty array.
CODE
userModel.findOne({'username': username }, function (err, user) {
if(user){
var orders = []
for(var i=0;i<user.orderHistory.length;i++){
var orderId = user.orderHistory[i].orderId
var order = orderModel.findOne({'id': orderId}).exec()
order.then(function(order){
orders.push(order)
})
}
orders.then(function(order){
console.log(order)
})
}
})
If anyone has a solution on how I can access orders outside of the loop, please let me know. Thank you!