DEV Community

Sanket N Jain
Sanket N Jain

Posted on

How to write multiple queries in mongoose?

I have written this query but it is not correct.

router.get("/product/:name", function(req, res){
Product.findById(req.params.name).populate("reviews").exec(function(err, foundProduct){
    if(err){
        console.log(err);
    }
    else{
        foundProduct.aggregate([{"$lookup": {"from": "reviews", "localField": "reviews", "foreignField": "_id", "as": "reviews"}}, {"$unwind": "$reviews"}, {"$group": {"_id": null, "ratingAvg": {"$avg": "$reviews.rating"}}}], function(err, result){
        if(err){
            console.log(err);
        }
        else{
            result.forEach(function(element){
                var rate = Math.round(element.ratingAvg);
                foundProduct.updateOne({avgRating: rate});
                res.render("product", {product: foundProduct});
            });
        }
    })
    }
})
})

Here is what I want:

Find the product with that id
populate the reviews in the product model associated with that product id
calculate the average rating by taking all the ratings associated with that product id
as the default avgRating in the product model is zero, so update the avgRating with the average rating calculated in the previous step.
now render the foundProduct which contains the updated avgRating.

Here is the product model:

var productSchema = new mongoose.Schema({
category: String,
name: String,
price: Number,
image: String,
description: String,
stock: Number,
avgRating: {type: Number, default: 0},
reviews: [
    {
        type: mongoose.Schema.Types.ObjectID, ref: 'Review'
    }
]
})

Top comments (1)

Collapse
 
gmcamposano profile image
gmcamposano

Hi sir. Your code can be simplified using async/await. Thank you for your post.