From d294d2706b4fc12625520f616035bd553e81c402 Mon Sep 17 00:00:00 2001 From: Sibunnayak Date: Thu, 28 Mar 2024 09:53:01 +0530 Subject: [PATCH] category wise product find controller updated --- resources/Products/ProductController.js | 15 +++++++++++---- 1 file changed, 11 insertions(+), 4 deletions(-) diff --git a/resources/Products/ProductController.js b/resources/Products/ProductController.js index 887ed0c..777b8fa 100644 --- a/resources/Products/ProductController.js +++ b/resources/Products/ProductController.js @@ -1,7 +1,7 @@ import { Product } from "./ProductModel.js"; import cloudinary from "../../Utils/cloudinary.js"; import { v4 as uuidv4 } from "uuid"; - +import { CategoryModel } from "../Category/CategoryModel.js"; export const createProduct = async (req, res) => { try { if (!req.files) { @@ -240,13 +240,20 @@ export const deleteProduct = async (req, res) => { }); } }; + export const getProductsByCategory = async (req, res) => { const { categoryName } = req.params; // Assuming category name is in the route + // console.log(categoryName); try { - const products = await Product.find({ - category: categoryName, - }).sort({ createdAt: -1 }); + // Find the category object by name first + const category = await CategoryModel.findOne({ categoryName }); + + if (!category) { + throw new Error("Category not found"); + } + const products = await Product.find({ category: category._id }).populate('category'); + // console.log(products); if (products && products.length > 0) { return res.status(200).json({