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?
{ $group : {_id : null, avgRate : { $avg : "$rating.rate" } } }