0
router.post('/validateCart', (req, res) => {
    let cart = req.body

    var warnings = []
    var warning = {}
    var dbCart = []
    var updatedProduct = {}

    cart.forEach(eachProduct => {
        Products.findOne({ _id: eachProduct.product._id })
            .then(product => {
                if (product.inStock) {
                    if (product.price === eachProduct.product.price) {
                        dbCart.push(eachProduct)
                    } else {
                        updatedProduct.product = product
                        updatedProduct.quantity = eachProduct.quantity
                        warning.product = product
                        warning.definition = 'Product price has changed.'
                        dbCart.push(updatedProduct)
                    }

                }
                else {
                    warning.product = product
                    warning.definition = 'This item is out of stock.'
                }
                warning.product = 'test'

                if (Object.keys(warning).length > 0) {
                    warnings.push(warning)
                }
                updatedProduct = {}
                warning = {}

            })
            .catch(err => console.log(err))
    })
    console.log(dbCart)

})

I am trying to validate products in my shopping cart, however when i try to compare products that are in my shopping cart and database and add warnings, I cant return a new array. console.log(dbCart, warnings) both return initial state. Can someone tell me where my mistake is?

ertemishakk
  • 517
  • 3
  • 14
  • Does this answer your question? [Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference](https://stackoverflow.com/questions/23667086/why-is-my-variable-unaltered-after-i-modify-it-inside-of-a-function-asynchron) – VLAZ Jul 27 '20 at 12:31
  • @VLAZ unrelated – ertemishakk Jul 27 '20 at 13:17
  • You are performing asynchronous operations so you will not see any change until those operations finish. However, your code expects everything to happen synchronously - after `.forEach` the arrays to be changed. This cannot happen as the DB lookup still wouldn't be finished. You need to only run the `console.log(dbCart)` *after* `Products.findOne({ _id: eachProduct.product._id }).then()` has completed. – VLAZ Jul 27 '20 at 13:21
  • Your comment helped, thanks @VLAZ – ertemishakk Jul 28 '20 at 10:35

0 Answers0