Building an e-Commerce website with Node – Part 41 – Add cart quantity middleware in Node.js

Now, we are going to create a middleware that counts the length of the products in our cart. Basically, it tells you the quantity of the products you have into the cart.

We are going to create a new folder (under the root folder) and call it middlewares. In it, create a file and call it middleware.js. Type in this file the following code.

var Cart = require('../models/cart');

module.exports = function(req, res, next) {

  if (req.user) {
    var total = 0;
    Cart.findOne({ owner: req.user._id }, function(err, cart) {
      if (cart) {
        for (var i = 0; i < cart.items.length; i++) {
          total += cart.items[i].quantity;
        }
        res.locals.cart = total;
      } else {
        res.locals.cart = 0;
      }
      next();
    })
  } else {
    next();
  }
}

If there is a logged in user then create a new variable to store the total of the product.
We use the Mongoose function findOne to search for the user with the same id as the cart owner.
If the cart exist then loop the items and increment the total by the quantity of the products. We set it then to a local variable named cart.

The next thing we have to do is to modify the server.js file. Open it and add the following code to it.

var cartLength = require('./middlewares/middlewares');

I added the above line of code at the line 19 and at the line 51 add the following code.

app.use(cartLength);

Now we have to add the cart icon on the right side of our navigation bar. Go to views/partials folder and open the navbar.js file. Just above the last </ul> tag type the following code.

<% if (user) { %>
        <li><a href="/cart" class="glyphicon glyphicon-shopping-cart"><span class="badge"><%= cart %></span></a></li>
      <% } else { %>
        <li><a href="/cart" class="glyphicon glyphicon-shopping-cart"><span class="badge">0</span></a></li>
      <% } %>

Leave a Reply