Building an e-Commerce website with Node – Part 42 – Add product to cart in Node.js

Let’s create a post route so we can add to the cart a specific product. Under routes folder open the main.js file and type the following code under the last stream.on ... piece of code.

router.post('/product/:product_id', function(req, res, next) {
  Cart.findOne({ owner: req.user._id }, function(err, cart) {
    cart.items.push({
      item: req.body.product_id,
      price: parseFloat(req.body.priceValue),
      quantity: parseInt(req.body.quantity)
    });

    cart.total = (cart.total + parseFloat(req.body.priceValue)).toFixed(2);

    cart.save(function(err) {
      if (err) return next(err);
      return res.redirect('/cart');
    });
  });
});

First we have to find the owner of the cart then we push all the items based on the request to the array of items. Basically, we push the items to the cart.

In the cart.total we parse the value of the items to a “Float” and limit the decimals to 2. Finally we want to save it to the cart. If there is an error return a callback with the error. If there isn’t any error then redirect the user to the cart page.

Leave a Reply