0

I need to calculate the rating average of an article, and the rating are in an array of objects

Here is my schema / model:

module.exports = mongoose.model('Article', {
    title : String,
    text : String,
    star : { type: Number, default: 3.5}
    ...
});

var userSchema = mongoose.Schema({
     email        : String,
     password     : String,
     name         : String,
     rating       : {type : Array, default: []}
});
module.exports = mongoose.model('User', userSchema);

where object in rating array are like { "rate" : "X", "articleID" : "Y" }

Now in this function i need to calculate the rating average

function recalculateArticleRate(articleIDD) {
    console.log("Recalculate article rate");
    User.aggregate([
        { $match: { "rating.articleID" : articleIDD } },
        { $unwind: "$rating" },
        { $group : {_id : "$_id", avgRate : {  $avg : "$rating.rate" } } }
    ], function (err, result) {
        if (err) {
            console.log(err);
            return;
        }
        console.log(result);
    });
}

This is the result object:

[ { _id: 58f519acfcb29003b572048b, avgRate: 3 },
{ _id: 58f5093159c45002f10ea7da, avgRate: 3 } ]

Doing this I get the average of all users evalutation, but i want the average of the rating of all users when rating.articleID = articleIDD. How I can do that with Mongoose?

2

1 Answer 1

0
function recalculateArticleRate(articleIDD) {
    User.aggregate([
        { $unwind: "$rating" },
        { $match: { "rating.articleID" : articleIDD } },
        { $group : {_id : null, avgRate : {  $avg : "$rating.rate" } } }
    ], function (err, result) {
        if (err) {
            console.log(err);
            return;
        }
    });
}

Put unwind before and _id = null (as recommended by Veeram) solved my problem !

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.