说我们有这个模式
{
"rating": 0,
"reviews": [
{"name": "bob", rating: 5},
{"name": "ann", rating: 3}
]
}
当评论数组更新时,我们如何计算评分字段?
编辑:使用Node和猫鼬
谢谢。
答案 0 :(得分:0)
您可以在架构上设置pre save hook,以在每次保存时自动更新评级:
schema.pre('save', function (next) {
let totalRatings = this.reviews.reduce((total, review) => total + review.rating);
this.rating = totalRatings / this.reviews.length;
next();
})
答案 1 :(得分:0)
我最终要做的是添加2个功能。
一个用于添加评论的功能,我们可以在该功能内调用在该架构上定义的方法
productSchema.statics.addReview = async function (_id, review) {
const doc = await this.findById(_id);
doc.reviews.unshift(review);
doc.calculateRating(); <-- now we can call calculateRating() only when addReview function gets called
return new Promise(resolve => resolve(doc.save()));
};
// methods on the schema lets us call the function on the doc itself
// note that es6 arrow functions wont work in this case because
// arrow functions explicitly prevent binding this
productSchema.methods.calculateRating = function () {
const total = this.reviews.reduce((sum, reviewObj) => sum + reviewObj.rating, 0);
this.rating = (total / this.reviews.length).toFixed(2);
};