To allow users to select a specific category to search in, we will first set up an API that retrieves all the distinct categories present in the Products collection in the database. A GET request to /api/products/categories will return an array of unique categories, and this route is declared as shown here:
mern-marketplace/server/routes/product.routes.js:
router.route('/api/products/categories')
.get(productCtrl.listCategories)
The listCategories controller method queries the Products collection with a distinct call against the category field, as shown in the following code:
mern-marketplace/server/controllers/product.controller.js:
const listCategories = async (req, res) => {
try {
let products = await Product.distinct('category',{})
res.json(products)
} catch (err){
return res.status(400).json({
error: errorHandler.getErrorMessage(err)
})
}
}
This categories API can be used in the frontend with a corresponding fetch method to retrieve the array of distinct categories and displayed in the view. This can be paired with a search API to allow users to search for products by its name in a specific category. In the next section, we will discuss this search API.