我有以下型号: 产品: 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: St
产品:
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},...]
这可能是一个独特的查询吗?每次添加新评论时,是否需要在“产品”文档中计算和存储平均值?
谢谢 !
也许你应该尝试计算“跑步平均值”.您只需知道有多少评分,以及它们的平均值.为MongoDB中的每个文档保存相同的平均值应该是不好的做法,我希望这对您有所帮助.
所以你可以创建这样的架构:
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
