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
You need to get the id of the category first, then use this id to query the products:
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:
You can try this: