NodeJS - Express cannot read property of null

Viewed 877

Good day. I am building an API in NodeJs. Below is the method that is giving me the error.

exports.getCartItems = (req, res) => {
  Cart.findOne({ user: req.user._id })
    .populate("cartItems.product", "_id name price productPictures")
    .exec((error, cart) => {
      if (error) return res.status(400).json({ error });
      if (cart) {
        let cartItems = {};
        cart.cartItems.forEach((item, index) => {
          console.log(item.product); //This gives result, when I remove everything else
          cartItems[item.product._id.toString()] = {
            _id: item.product._id.toString(),
            name: item.product.name,
            img: item.product.productPictures[0].img,
            price: item.product.price,
            qty: item.quantity,
          };  
        });
        
        res.status(200).json({ cartItems });
      }
    });
  //}
};

I get the error

      ^
TypeError: Cannot read property 'name' of null

However, when I console.log item.product, I get results. This is shwon in the image below. Please, what I'm I doing wrong?

enter image description here

Thanks.

0 Answers
Related