DEV Community

husain-nahar
husain-nahar

Posted on

Using find function nodejs

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
    }
});
Enter fullscreen mode Exit fullscreen mode

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);
                }
        });
Enter fullscreen mode Exit fullscreen mode

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)

Collapse
 
thomasbnt profile image
Thomas Bnt

Hello ! Don't hesitate to put colors on your codeblock like this example for have to have a better understanding of your code 😎

console.log('Hello world!');
Enter fullscreen mode Exit fullscreen mode

Example of how to add colors and syntax in codeblocks

Collapse
 
husainahar profile image
husain-nahar

Ok thank you all for your time. I found out the solution which is:

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

And to get all the products related to a particular category:

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

This is working as expected.