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){
User.find({'rating': {$elemMatch: {articleID : articleIDD}}}, function (err, result) {
console.log(result);
});
}
This is the result object:
[ { _id: 58f1448b92805b0cc2358536,
email: 'mail',
name: 'name',
__v: 0,
rating:
[ [Object],
[Object],
[Object],
[Object]]
} ]
Doing this I get all users who evaluated the article, but how can I calculate the average directly with Mongoose?
via Gabriele Picco
No comments:
Post a Comment