how to use find function in nodejs

Viewed 42
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.

1 Answers

Ok thank you all for your time. I found out the solution which is: First of all below is my schema as Product which includes another schema named Category:

const productSchema = mongoose.Schema({ 
name: { type: String, required: true }, 
category: { type: mongoose.Schema.Types.Mixed, ref: "Category", required: true } }); 

And to get all the products related to a particular category, We need to add our query inside quotes like this:

let tempProducts = []; 
tempProducts = await Product.find({ "category._id": id}); 

This is how I achieved as I wanted and working as expected.

Related