计算猫鼬的平均值

Hir*_*del 2 mongoose mongodb node.js express

我试图在我的评论中计算所有评级的平均值但结果.平均值始终为0.我不知道问题是什么.这是我的产品架构:

var productSchema = new Schema({
_id : String,
Rating : {  type: Number, default:0 },
Comments :[
{
    type: Schema.ObjectId,
    ref: 'comments'
}
],
});
Run Code Online (Sandbox Code Playgroud)

这是我的评论架构:

var commentSchema = new Schema({
Rating : {  type: Number, default:0 },
Helpful : {  type: Number, default:0 },
User :{
type: Schema.ObjectId,
ref: 'users'
 },
Content: String,
});
Run Code Online (Sandbox Code Playgroud)

这是我在节点中的代码:

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;
                    });
                }
Run Code Online (Sandbox Code Playgroud)

Joh*_*yHK 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) {...});
});
Run Code Online (Sandbox Code Playgroud)