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({