Categories API

To allow users to select a specific category to search in, we will set up an API that retrieves all the distinct categories present in the Product collection in the database. A GET request to /api/products/categories will return an array of unique categories.

mern-marketplace/server/routes/product.routes.js:

router.route('/api/products/categories')      .get(productCtrl.listCategories)

The listCategories controller method queries the Product collection with a distinct call against the category field.

mern-marketplace/server/controllers/product.controller.js:

const listCategories = (req, res) => {  Product.distinct('category',{},(err, products) => {    if (err) {      return res.status(400).json({ error: errorHandler.getErrorMessage(err) ...

Get Full-Stack React Projects now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.