Building an e-Commerce website with Node – Part 30 – Add a middleware to render categories in Node.js

We have to add another middleware to render the categories on the navigation bar. This middleware has to use a new variable which is category.

First we need to require the category file. In the server.js file type the following code.

var Category = require('./models/category');

Next we have to create the middleware, also in the server.js file.

app.use(function(req, res, next) {
  Category.find({}, function(err, categories) {
    if (err) return next(err);
    res.locals.categories = categories;
    next();
  });
});

This middleware finds all the categories, that’s why there is an empty query (Category.find({} … ).
It also stores the list of categories in a local variable named categories (res.locals.categories = categories;).

To display the categories in the navigation bar we are going to use the newly created variable, categories.

Go to views/partials and open navbar.ejs. Add the following code above the line <% if (!user) { %>.

<li><a class="dropdown-toggle" data-toggle="dropdown" href="#">Categories</a>
          <ul class="dropdown-menu">
            <% for (var i = 0; i < categories.length; i++)  { %>
              <li><a href="/products/<%= categories[i]._id %>"><%= categories[i].name %></a></li>
            <% } %>
          </ul>
        </li>

Here we are looping the categories data. That’s because Mongoose is responding the data in an array form. The category.length is the length of the categories; if you have four categories the length will be four, which means four data in the array.

Leave a Reply