const categorySchema = mongoose.Schema({ name: { required: true, type: String } }); const productSchema = mongoose.Schema({ name: { type: String, required: true }, category: { type: mongoose.Schema.Types.Mixed, ref: "Category", required: true } });
As you see above I have two models where I am using Category inside Product.
Now I want to fetch all the products by passing a particular Category or its id as _id which gets generated by default by mongodb.
Although I am achieving the desired result do this below:
const id = req.query.categoryId;//getting this from GET REQUEST let tempProducts = []; let products = await Product.find({}); products.forEach(product => { if (product.category._id===id){ tempProducts.push(product); } });
It gets me what I want to achieve but still I want to know how to get it using "find" function. or this what I am doing is the only way.
Top comments (2)
Hello ! Don't hesitate to put colors on your
codeblock
like this example for have to have a better understanding of your code 😎Ok thank you all for your time. I found out the solution which is:
And to get all the products related to a particular category:
This is working as expected.