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.'/product/:product_id', function(req, res, next) {
  Cart.findOne({ owner: req.user._id }, function(err, cart) {
      item: req.body.product_id,
      price: parseFloat(req.body.priceValue),
      quantity: parseInt(req.body.quantity)
    }); = ( + parseFloat(req.body.priceValue)).toFixed(2); {
      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 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