I am working with node.js and express. The problem arises while working with the routes. I have created an array named productList which I want to populate with json objects but my code is not working. The first console.log statement successfully logs the array of json objects but the second console.log statement logs the empty array.
router.get('/', (req, res) => {
var productList = [] ;
Products.find()
.then(products => {
products.forEach(product => {
productList.push(product) ;
console.log(productList) ; // First console.log
})
})
.catch(err => res.status(400).json({'error': "Something wrong happened !!"}));
console.log(productList) ; // Second console.log
res.render("products", {productList}) ;
});
Here Products is the name of a Document that is created successfully. I think the problem is related with the scoping of productList array. I don't understand what's wrong going on here. Please help.