node.js - 在 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({
Rating : {  type: Number, default:0 },
Helpful : {  type: Number, default:0 },
User :{
type: Schema.ObjectId,
ref: 'users'
 },
Content: String,
});

这是我在 Node 中的代码:

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

关于node.js - 在 Mongoose 中计算平均值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26810599/

相关文章:

javascript - 自定义 JSON.stringify 无法将对象作为一个整体进行字符串化,但在迭代一层时有效

mysql - 数据聚合 mongodb vs mysql

node.js - 当我尝试从现有路由获取数据时,为什么会收到 404 错误

python - 使用 mongodb $push 和 $pull 的赞成(喜欢)功能

MongoDB 查找并返回所有的最大值

javascript - socket.on() 未接收数据

javascript - 将 JSHint 与 Express.js/'delete' 一起使用(保留字)

javascript - AngularJS 数组未被 ng-repeat 识别

node.js - 如何在nodejs中取消unirest请求

javascript - Node shell 脚本上没有这样的文件或目录