node.js - 我有 2 个关于 mongoose 聚合和索引方法的问题
问题描述
我有 2 个问题
第一:
我正在尝试制作评论模式,用户应在每个训练营中添加 1 条评论
代码:
ReviewSchema.index({ bootcamp: 1, user: 1 }, { unique: true });
它不起作用..用户仍然可以添加多个评论
第二期:
我正在尝试计算评论的平均评分,但在获取训练营时它不会被添加到数据库中
代码:
// Static Method to get the avg rating of reviews and save
ReviewSchema.statics.getAverageRating = async function (bootcampId) {
const obj = await this.aggregate([
{
$match: { bootcamp: bootcampId },
},
{
$group: {
_id: '$bootcamp',
averageRating: { $avg: '$rating' },
},
},
]);
try {
await this.model('Bootcamp').findByIdAndUpdate(bootcampId, {
averageRating: obj[0].averageRating,
});
} catch (err) {
console.log(err);
}
//Call averageRating after save
ReviewSchema.post('save', async function () {
await this.constructor.getAverageRating(this.bootcamp);
});
//Call averageRating before remove
ReviewSchema.pre('remove', async function () {
await this.constructor.getAverageRating(this.bootcamp);
});
** 它不起作用,并且平均评分永远不会添加到数据库中(作为训练营的字段)**
解决方案
我做了与教程相同的操作,一开始没有用,但后来我发现缺少分号。
推荐阅读
- python - 如何在 Python 中使用 Excel 定义的名称来获取值?
- python - 如何找到二值图像的最低点?
- javascript - jquery如何提交表单
- android - 我可以将 Button 放在 ScrollView 内的 ConstraintLayout 的底部吗?
- ubuntu-18.04 - Ubuntu添加用户未设置主目录
- swift - 在 Swift 中将字符串更新/附加到文件末尾的问题
- java - 读取大量数据
- python - 葡萄牙语的 Hunspell 将正确拼写的单词显示为拼写错误
- javascript - 在 Trimble 地图中获取经纬度停靠点
- asp.net-core - 修复了 JSON 引用循环错误而不是我得到太多数据