How to display list of categories in Node and Express?

Hi guys I am working on a small inventory app and I can’t figure out how to properly display my categories.

For example if I have items that all fall into the category named “category” how do I make sure that I can only display “category” once in a nav bar?

I have tried to use map and filter before rendering the page but I only see the correct results in the console. When I tried to put it on the page I get an error of can’t read length of undefined.

Below is what I have now and shows what I mean by displaying the category more than once. I know why it’s displaying like this I just can’t figure out how to display the category just once.

Thanks in advance.

This is my index.js

var express = require('express');
var router = express.Router();
var items = require('../models/itemsSchema');

/* GET home page. */

router.get('/', (req, res, next) => {
  items.find({})
    .then((items) => {
      res.render('index', {
        items: items
      });
    })
    .catch((err) => {
      if (err) {
        res.end("ERROR!");
      }
    });
});

module.exports = router;

index.pug

extends layout

block content
  h1.page-title HomePage

  div.category-container
    each category in items
      a.category-title(href='/category/'+category.category)=category.category
      br

  div.items-container
    each item in items
      div.item-container
        img(src=item.imageurl, width="280" height="280")
        br
        a.item-name(href='/item/'+item._id) #{item.name}
        p=item.description
        p=item.category

I’m not 100% sure what you want and I don’t see where in the code that error could be. Do you have a repo?

I’m not sure why but now it works.

This is what I meant when I tried to use map. For some reason I would get an error on my index.pug page. When I would console.log categories i would see my list of categories but I couldn’t get it on the page.

.then((items) => {
      const categories = [...new Set(items.map(category => category.category))]
      res.render('index', {
        items: items,
        categories: categories
      });
    })

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.