gpt4 book ai didi

node.js - Mongoose / express : average of subdocuments

转载 作者:可可西里 更新时间:2023-11-01 09:15:13 26 4
gpt4 key购买 nike

我有以下型号:

产品:

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

关于node.js - Mongoose / express : average of subdocuments,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29322497/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com