node.js - 查询已执行
问题描述
我想averageRating
从我的评论集合中计算。因此,首先我创建了一个聚合管道,通过与项目 ID 匹配来查找avgRating
和ratingQuantity
。然后我制作了一个post
中间件(文档中间件),当任何人创建新评论时, averageRating
and ratingQuantity
字段会被更新,但问题是这仅适用save
于update
or delete
。因此,我制作了一个查询中间件,然后为了获取文档,我执行了查询,但得到了错误查询已执行,请帮助!!!
我的 reviewModel.js 代码
const mongoose = require('mongoose');
const movieModel = require('./movieModel');
const reviewSchema =new mongoose.Schema({
review:{
type:String,
required:[true,"review can't be blank"],
maxlength:100,
minlength:10
},
rating:{
type:Number,
required:[true,"review must have a rating"],
max:10,
min:1
},
movie:{
type:mongoose.Schema.ObjectId,
ref:'movies',
required:[true,'review must belong to a movie']
},
user:{
type:mongoose.Schema.ObjectId,
ref:'users',
required:[true,'review must belong to a user']
}
},
{
toJSON:{virtuals:true},
toObject:{virtuals:true}
});
reviewSchema.pre(/^find/,function(next){
this.populate({
path:'movie',
select:'name'
}).populate({
path:'user',
select:'name'
});
next();
})
reviewSchema.index({movie:1,user:1},{unique:true});
reviewSchema.statics.calcAvgRating = async function(movieId){
console.log(movieId);
const stats = await this.aggregate([
{
$match:{movie:movieId}
},
{
$group:{
_id:'$movie',
nRating:{$sum:1},
avgRating:{$avg:'$rating'}
}
}
])
console.log(stats);
const movie = await movieModel.findByIdAndUpdate(movieId,{
ratingsQuantity:stats[0].nRating,
avgRating:stats[0].avgRating
});
}
reviewSchema.post('save',function(){
this.constructor.calcAvgRating(this.movie);
})
reviewSchema.pre(/^findOneAnd/,async function(next){
const r = await this.findOne();
console.log(r);
next();
})
const reviewModel = mongoose.model('reviews',reviewSchema);
module.exports = reviewModel;
我的 updateOne 控制器
exports.updateOne = Model=> catchAsync(async(req,res,next)=>{
console.log("handler");
const doc = await Model.findByIdAndUpdate(req.params.id,req.body,{
new:true,
runValidators:true
});
if(!doc)
return next(new appError('Ooops! doc not found',404));
sendResponse(res,200,'success',doc);
})
解决方案
尝试这个
reviewSchema.post(/^findOneAnd/,async function(doc){
const model=doc.constructor;
})
这doc
实际上是当前执行的文档,通过这样做doc.constructor
你得到了它的模型。在该模型上,您可以使用calcAvgRating
推荐阅读
- apache-spark-sql - 如何从键值映射中提取值,火花数据框
- amp-html - 实现 amp 多页滑块
- sql - MSAccess 2013:联合 3 个表中的任何 2 个工作,联合所有 3 个崩溃
- c++ - map 在运行时选择 `std::greater` 或 `std::less`
- ruby-on-rails - Mongoid 和扩展 JSON
- docker - 在安装卷的 Kubernetes 中启动 RStudio
- android - 将 7 textview 的内容转移到适配器的另一个活动
- elasticsearch - 从同一网络中的另一台机器访问 Elastic Search
- jekyll - 3Jekyll .1.6 不在 Ubuntu 上服务:未定义的方法 `bash_on_windows?' 对于 Jekyll:: Utils:: Platforms: 模块
- powershell - 删除条件中的匹配字符串,PowerShell