skip to Main Content

category schema

const CategorySchema = mongoose.Schema(
  {
    catName: { type: String, required: true }
  },
  { timestamps: true }
);

Product Schema

const ProductSchema = new mongoose.Schema(
  {
    brand: { type: String, required: true },
    title: { type: String, required: true },
    categories: { type: mongoose.Schema.Types.ObjectId, ref: "Category" },
  },
  { timestamps: true }
);

**
This is my code to search for category name while knowing that the data stored in my product model is a reference Id from category model**

const qCategory = req.query.category;

else if (qCategory) {
      products = await Product.find({
        categories: {
          catName: qCategory
        }
      }).populate("categories");
    }

I have tried whatever I know, Please help me out.

I need to search by categories

2

Answers


  1. You need to get the id of the category first, then use this id to query the products:

    const qCategory = req.query.category;    
    
    const category = await Category.findOne({ catName: qCategory });
    
    if (category) {
        products = await Product.find({ categories: category._id }).populate("categories");
    }
    

    Also I think you wanna change the name to singular category, because currently it allows to store just one.

    If you want to store multiple you need to change for this:

    categories: [{ type: mongoose.Schema.Types.ObjectId, ref: "Category" }],
    
    Login or Signup to reply.
  2. You can try this:

    router.get("/search/:key", async (req, res) => {
        try {
    
            const category = await Category.findOne({ catName: req.params.key });
    
            let products = await Product.find({
                $or: [
                    { title: { $regex: req.params.key, $options: "i" } },
                    { brand: { $regex: req.params.key, $options: "i" } },
                    { categories: category?._id }
                ]
            });
        } catch {
    
        }
    });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search