Building an e-Commerce website with Node – Part 32 – Create route to Render Faker data in a page in Node.js

In order to render in a page all of the products created by Faker we have to create a new route. Go to the routes folder and open main.js file. In the main.js file type the following code.

router.get('/products/:id', function(req, res, next) {
  Product
    .find({ category: req.params.id })
    .populate('category')
    .exec(function(err, products) {
      if (err) return next(err);
      res.render('main/category', {
        products: products
      });
    });
});

One important thing has to be understood; :id is strong related to req.params.id. If we replace :id with 1234 then the .find({ category: req.params.id }) will become .find({ category: 1234 }).

Next we are using .populate. It can be used only if the data is an object ID (take a look at ProductSchema in the product.js file). Basically, .populate grabs the data and puts it on the page.

Leave a Reply