【问题标题】:calculating average in Mongoose计算猫鼬的平均值
【发布时间】:2015-01-04 19:07:43
【问题描述】:

我正在尝试计算我的 cmets 中所有评分的平均值,但结果。平均值始终为 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;
                    });
                }

【问题讨论】:

    标签: node.js mongodb express mongoose


    【解决方案1】:

    您不能引用 $Comments.Rating,因为 cmets 位于单独的集合中,并且产品文档仅包含对它们的引用。

    因此,您需要通过几个步骤来模拟连接:

    // 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) {...});
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-01-14
      • 2017-02-06
      • 2012-06-19
      相关资源
      最近更新 更多