ok, after a deep dive I think I got what's happening here (haven't used mongoose in almost a year! so I had to refresh)
First:
getQuery()
is deprecated and the new equivalent is getFilter()
.
mongoose docs say:
You should use getFilter() instead of getQuery() where possible. getQuery() will likely be deprecated in a future release.
Second:
you want to get the updated document to calculate the review right? then what you have to do is only accepting the updated document in the post
hook since it's one of the accepted parameters:
reviewSchema.post(/^findOneAnd/, async function(updatedReviewdDoc){
await updatedReviewdDoc.constructor.calculateAvgRatings(updatedReviewdDoc.tour);
});
your post
hook didn't work because you must have thought that the this
keyword is shared or inherited between both the pre
and the post
right? but that is not the case.
let's break it down, you're using one of the Query middleware/hook so this
keyword is referring to the query itself not to the document, that's why your post
is not working as you might think it would. you can't call constructor.calculateAvgRatings
on a query instance! constructor
property belongs to a Mongoose document.
yes you fetched the document here:
reviewSchema.pre(/^findOneAnd/, async function (next) {
this.r = await this.model.findOne(this.getQuery());
next();
});
but as I mentioned this
is not shared or inherited.
Finally, you can safely remove the pre
hook you don't need it since the post
can get the updated doc without any help from it.
I hope my answer makes all the sense and helped you