首页 > 解决方案 > 查询已执行

问题描述

我想averageRating从我的评论集合中计算。因此,首先我创建了一个聚合管道,通过与项目 ID 匹配来查找avgRatingratingQuantity。然后我制作了一个post中间件(文档中间件),当任何人创建新评论时, averageRatingand ratingQuantity字段会被更新,但问题是这仅适用saveupdateor 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);
    
})

标签: node.jsmongodbexpressmongoose

解决方案


尝试这个

reviewSchema.post(/^findOneAnd/,async function(doc){

    const model=doc.constructor;

})

doc实际上是当前执行的文档,通过这样做doc.constructor你得到了它的模型。在该模型上,您可以使用calcAvgRating


推荐阅读