i'm writing a webshop in Node with Express and Mongoose. The Mongoose Models are "Product" and "Item". Every Item belongs to a Product. I want to count the Items of a Product (Stock) and serve this information to the view.
The Problem is, that the res.render part is executed before the forEach Loop is done. So "product.stock" is undefined
exports.getProducts = (req, res, next) => {
Product.find()
.lean()
.then(products => {
products.forEach(product => {
Item.countDocuments({productId: product._id})
.then( count => {
product.stock = count
})
});
res.render('shop/product-list', {
path: '/products',
pageTitle: "All Products",
products: products
})
})
.catch(err => { return next(err) })
};