Search code examples
javascriptnode.jsexpressmongoose

search for category in reference document in nodejs


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


Solution

  • 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" }],