router.get("/api/cart", auth, async (req, res) => {
try {
const user = await User.findById(req.user._id);
items = [];
await user.cartProducts.forEach(async (product) => {
var item = await Item.findById(product._id);
items.push(item);
console.log(items);
});
console.log(items)
res.send(items);
} catch (e) {
res.status(500).send(e);
}
});
I want to send the data of the all the products selected by the user back in the array. The first console log shows the array with the products. While, the second shows the empty array. Moreover, api is working good no issues with it. Personally, I think issue is with my javascript concepts.
await
doesn't work with .forEach
. You need to use for
:
items = [];
for(let product of user.cartProducts) {
let item = await Item.findById(product._id);
items.push(item);
}
console.log(items)
res.send(items);
EDIT :
Also, this method is going to kill your database. If you need to fetch 100 products, then you're doing 100 requests to the DB.
You can achieve the same result in one request :
const ids = user.cartProducts.map( p => p._id ); // Array of _id
const items = await Item.find({
_id : {
$in : ids
})
.lean() // Returns simple JSON, faster