1

I added the productArray array and need the data from products into that array. When I console.log it inside the loop it's working, but taking it out doesn't work. I am rendering it in ejs.

exports.getOrderById = (req, res, next) => {
  let user = req.user
  User.findById(user._id).exec((err, purchase)=>{
    if(err){
      return res.status(400).json('Error')
    }
   else {
     let item = purchase.order
     let productArray = []
     item.forEach(function(items){
       Product.findById(items.productId._id).exec((err, products)=>{
          productArray.push({
           productName: products.name,
           productPrice: products.price
         })
         console.log(productArray[0].productName)
        })  

      })       
     res.render('cart', {item: [item], products: [productArray]} )
   }
  })
};

1 Answers1

0

It is happening because you are passing to the findById a callback function which will run some time in the javascript console.log(productArray[0].productName)

This means that as soon as you call findById function passing those arguments, JS run the bottom console.log which in that case the productArray it's still empty.

Try this:

exports.getOrderById = (req, res, next) => {
  let user = req.user
  User.findById(user._id).exec((err, purchase)=>{
    if(err){
      return res.status(400).json('Error')
    }
   else {
     let item = purchase.order
     let productArray = []
     item.forEach(function(items){
       Product.findById(items.productId._id).exec((err, products)=>{
          productArray.push({
           productName: products.name,
           productPrice: products.price
         })
        })  

      })      
     res.render('cart', {item: [item], products: [productArray]} )
     console.log(productArray[0].productName)
   }
  })
};

Hope this helps.

Always Helping
  • 14,316
  • 4
  • 13
  • 29