mongoose/快递:平均子文件

我有以下型号:

产品:

var ProductSchema = new Schema({ name: String, comments: [{ type: Schema.Types.ObjectId, ref: 'Comment'}], _user: { type: Schema.Types.ObjectId, ref: 'User'} }); 

评论:

 var CommentSchema = new Schema({ text: String, rating: Number, _product: { type: Schema.Types.ObjectId, ref: 'Product'} }); 

我目前所做的是检索所有产品以及他们的用户:

 router.get('/', function(req, res, next) { Product.find().populate('_user').exec(function (err, products) { if (err) return next(err); res.json(products); }); }); 

我想添加到结果“平均”字段,其中包含每个产品的所有评论的平均值,所以结果如下所示:

 [{name: "Product 1", _user: {name: "Bob"}, average: 7.65},...] 

这是唯一的查询可能吗? 每次添加新评论时,是否需要在产品文档中计算并存储平均值?

谢谢 !

也许你应该尝试计算“跑步平均”。 你只需要知道有多less收视率,他们的平均值是多less。 在MongoDB中为每个文档保存相同的平均值应该是不好的做法,我希望这会帮助你。 所以你可以像这样创build模式:

 var AverageProductRatingSchema = new Schema({ productId: {type: Schema.Types.ObjectId, ref: 'Product'}, averageRating: {type: Number}, numberOfRatings: {type: Number} }); 

然后,只需实现addRating()函数就像这样:

 function addRating(newRating, productId) { /* Find document that holds average rating of wanted product */ AverageProductRating.findOneAsync({productId: productId}) .then(function (avgProdRating) { /* Calculate new average using the Running Average method. http://www.bennadel.com/blog/1627-create-a-running-average-without-storing-individual-values.htm */ var newAverageRating = (avgProdRating.averageRating * avgProdRating.numberOfRatings + newRating) / (avgProdRating.numberOfRatings + 1); var newNumberOfRatings = avgProdRating.numberOfRatings + 1; AverageProductRating.update( { productId: productId }, { $set: { averageRating: newAverageRating, numberOfRatings: newNumberOfRatings } }); }); } 

这是描述类似问题的链接: http : //www.bennadel.com/blog/1627-create-a-running-average-without-storing-individual-values.htm