Node.js 猫鼬平均数的计算

Node.js 猫鼬平均数的计算,node.js,mongodb,express,mongoose,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(

我试图计算我评论中所有评分的平均值,但结果是。平均值总是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;
                    });
                }

您不能引用
$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) {...});
});