Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

calculating average in Mongoose

I'm trying to calculate the average of all ratings in my comments but the result.Average is always 0. I don't know what's the problem. here is my Schema for Product:

var productSchema = new Schema({
_id : String,
Rating : {  type: Number, default:0 },
Comments :[
{
    type: Schema.ObjectId,
    ref: 'comments'
}
],
});

Here is my Comment schema:

var commentSchema = new Schema({
Rating : {  type: Number, default:0 },
Helpful : {  type: Number, default:0 },
User :{
type: Schema.ObjectId,
ref: 'users'
 },
Content: String,
});

And this is my code in node :

function getRating(id){ 
                     Product.aggregate([ { $match: { _id:id }}, { $unwind: "$Comments" }, 
                     { $group: { _id: "$_id", average: { $avg: "$Comments.Rating" } }} ], function (err,result)                  {
                if (err) {
                        console.log(err);
                }       
                        console.log(result);
                        return result.average;
                    });
                }
like image 731
Hirad Roshandel Avatar asked Oct 16 '25 14:10

Hirad Roshandel


1 Answers

You can't reference $Comments.Rating because the comments are in a separate collection and the product docs just contain a reference to them.

So instead you need to emulate a join using a couple steps:

// 1. Get the product's Comments array of comment ids.
Product.findOne(id, 'Comments', function(err, product) {
    // 2. Filter Comments to just those in product.Comments and average the Rating
    Comments.aggregate([
        {$match: {_id: {$in: product.Comments}}},
        {$group: {_id: product._id, average: {$avg: '$Rating'}}}
    ], function (err, result) {...});
});
like image 94
JohnnyHK Avatar answered Oct 19 '25 03:10

JohnnyHK



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!