Home > Blockchain >  how to use find function in nodejs
how to use find function in nodejs

Time:09-11

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.

CodePudding user response:

Try to change your category ref type to ObjectId:

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

You should be able to query your products by category with:

const id = req.query.categoryId;

let products = await Product.find({ category: id });

If you need to also populate the category field you can do it with:

let products = await Product.find({ category: id }).populate('category').exec();

CodePudding user response:

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 } }); 

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

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

This is working as expected.

  • Related