Search code examples
javascriptmongodbfindmern

can`t filter by category in mongoDB in a MERN app


It's an e-commerce project using MERN stack. I'm trying to filter by category but it's the only one that doesnt'matches. For example, if I use find() to search by name it works, but white category says that the object doesn't have that property.

this is the route:

router.get("/category/:category", async (req, res) => {
  const { category } = req.params;
  try {
    let products;
    if (category == "all") {
      products = await Product.find().sort([["date", 1]]);
    } else {
      products = await Product.find({ category: category });
      // console.log(products)
    }
    res.status(200).json(products);
  } catch (e) {
    res.status(400).send(e.message);
  }
});

with console.log(products) shows the files I've created when i search all:

{
    _id: new ObjectId("63fe4acfeaff1da586c3076f"),
    name: 'mtb',
    description: 'mountain-bike',
    price: '120000',
    category: 'Mountain-Bike',
    pictures: [ [Object] ],
    __v: 0
}

Solution

  • Make sure that:

    • the :category is set exactly to Mountain-Bike.
    • you use the endpoint like this: /category/Mountain-Bike