0
app.get("/cart", isLoggedIn, async function(req, res){
    var cartsretrieved = [];
    for(var i = 0; i < req.user.cart.length; i++){
        Product.findById(req.user.cart[i]._id, function(err, product){
            if(err){
                req.flash("error", "An Error has occured, Please try again later.");
                return res.redirect("/");
            }
            else if(i == req.user.cart.length - 1){
                return res.render("cart", {product: cartsretrieved});
            }
            cartsretrieved.push(product);
        });
    }
});

I am trying to make it easier on the db instead of storing every element with all it's objects i stored the id only and when i need the objects i store it to an array and render it but the code down isn't working so how can i make it thanks for reading

mmostafa
  • 25
  • 6
  • 1
    Main issue is [JavaScript closure inside loops – simple practical example](https://stackoverflow.com/questions/750486/javascript-closure-inside-loops-simple-practical-example) but this won't work reliably anyway because you can't assume that the callbacks are executed in order. – Guy Incognito May 21 '20 at 18:05
  • so what can i do to make it work in this case – mmostafa May 22 '20 at 03:23
  • Why do you fetch the documents one by one? Would be much easier to get all of them at the same time and you wouldn't need all that manual work. – Guy Incognito May 22 '20 at 06:15
  • because they are stored as ids in the db not the whole object so how will i fetch them one time – mmostafa May 23 '20 at 07:02
  • `Product.find({ id: { $in: req.user.cart.map(cart => cart._id) } })` – Guy Incognito May 23 '20 at 07:14

0 Answers0