Расчет среднего в мангусте
Я пытаюсь вычислить среднее значение всех оценок в моих комментариях, но результат. Среднее всегда равно 0. Я не знаю, в чем проблема. вот моя схема для продукта:
var productSchema = new Schema({
_id : String,
Rating : { type: Number, default:0 },
Comments :[
{
type: Schema.ObjectId,
ref: 'comments'
}
],
});
Вот моя схема комментариев:
var commentSchema = new Schema({
Rating : { type: Number, default:0 },
Helpful : { type: Number, default:0 },
User :{
type: Schema.ObjectId,
ref: 'users'
},
Content: String,
});
И это мой код в узле:
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;
});
}
1 ответ
Решение
Вы не можете ссылаться $Comments.Rating
потому что комментарии находятся в отдельной коллекции, и документы по продукту просто содержат ссылку на них.
Поэтому вместо этого вам нужно эмулировать объединение, выполнив пару шагов:
// 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) {...});
});