const stats = await this.aggregate([
{
$match: { tour: tourId },
},
{
$group: {
_id: '$tour',
nRating: { $sum: 1 },
avgRating: { $avg: '$rating' },
},
},
]);
console.log(stats);
await Tour.findByIdAndUpdate(tourId, {
ratingsQuantity: stats[0].nRating,
ratingsAverage: stats[0].avgRating,
});
};
reviewSchema.post('save', function () {
this.constructor.calcAverageRatings(this.tour);
});
reviewSchema.pre(/^findOneAnd/, async function (next) {
this.r = await this.findOne();
// console.log(this.r);
next();
});
reviewSchema.post(/^findOneAnd/, async function () {
// await this.findOne(); does NOT work here, query has already executed
await this.r.constructor.calcAverageRatings(this.r.tour);
});
this.r的值为null。因此,分配给this.r的查询返回null,但为reviewSchema的查询中间件预定义了构造函数。