我的应用中有两个schemas
。这些是:
培训师单一评分模式:
trainerID: String,
userID: String,
rating: Number,
review: String,
addedOn: String,
};
const TrainerSingleRating = mongoose.model(
"TrainerSingleRating",
trainerSingleRating
);```
培训师评分架构:
trainerID: String,
averageRating: Number,
ratings: [trainerSingleRating],
};
const TrainerRatings = mongoose.model("TrainerRatings", trainerRatings);```
我正在使用一个函数来更新和创建数据库中的文档。 下面是我的函数的代码:
function saveTrainerRatings(trainerID, userID, ratings, review) {
const date = moment().format("DD MMM YYYY");
const trainerSingleRating = new TrainerSingleRating({
trainerID: trainerID,
userID: userID,
rating: ratings,
review: review,
addedOn: date,
});
TrainerRatings.findOne({ trainerID: trainerID }, function (
err,
foundRatingList
) {
const oldAverageRating = foundRatingList.averageRating;
const newAverageRating = (oldAverageRating + parseInt(ratings)) / 2;
const trainerRatings = new TrainerRatings({
trainerID: trainerID,
averageRating: ratings,
ratings: [trainerSingleRating],
});
if (err) {
console.log(err);
} else {
if (!foundRatingList) {
trainerRatings.save();
} else {
const oldAverageRating = foundRatingList.averageRating;
foundRatingList.ratings.push(trainerSingleRating);
foundRatingList.averageRating.update(newAverageRating);
foundRatingList.save();
}
}
});
trainerSingleRating.save();
}
因此,每次用户对培训师进行评分时,都会创建并保存新文档,并将新文档推入Trainer Rating
模式中的评分数组中。
我需要根据所有评分来计算平均评分。目前,我正在尝试通过每次创建新文档时更新平均评分来解决此问题。但是问题是我在说foundRatingList.averageRating.update is not a function
时出错。
如何解决此错误?还是有任何解决方法将新文档推送到rating array
并同时更新averageRatings
?
感谢前进