0

My array's values get deleted automatically and can't get to know why.

I am working on a e-commerce website for a client and I am working on cart feature. My app connects to the Mongodb using mongoose, i have passport for authentication. When i hit '/cart' route, my code finds the user from the mongodb database using it's username stored in cookie, then go through the 'inCart' field and fetch the product's document id's after which i use findById to find that product and save it into a array the code works till here and my array holds the documents but as soon as my findById loop exits, the array is empty again IDK why.

I have spent so much time figuring the why but i can't get to the answer and so any solution is a huge thanks.

My App Js - cart route code:

array has values till line number 18, and then from line 20 array gets empty

app.get("/cart", function (req, res){
    var userID = req.cookies["userEmail"];
    var cartProducts = [];

    User.findOne({username: userID}, function (err, user){
        if (err){
            console.log(err);
        } else {
            user['inCart'].forEach(function (productId) {
                Product.findById(productId, function (err, doc){
                    if (err) {
                        console.log(err);
                    } else {
                        // console.log(doc)
                        cartProducts.push(doc);
                        // console.log(cartProducts)
                    };
                    // console.log(cartProducts) - works
                });
                // console.log(cartProducts); - not working from here
            });
        };
    });
    // console.log(cartProducts)

    res.render("cart", { cart: cartProducts })
});

Results: Console log of line 18

Console log of line 20

Andreas
  • 21,535
  • 7
  • 47
  • 56

0 Answers0