计算猫鼬的平均值

时间:2014-11-07 21:47:08

标签: node.js mongodb express mongoose

我正在尝试计算评论中所有评分的平均值,但结果是。平均值始终为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 个答案:

答案 0 :(得分:7)

您无法引用$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) {...});
});
相关问题