jonasschmedtmann / complete-node-bootcamp

Starter files, final projects and FAQ for my Complete Node.js Bootcamp
https://www.udemy.com/nodejs-express-mongodb-bootcamp/?couponCode=GITHUB515
3.13k stars 3.63k forks source link

Query was already executed #126

Open harshmalviya opened 3 years ago

harshmalviya commented 3 years ago

When using pre and post middlewares in review model to add ratings after editing a review, I am getting this error from the post findOneAnd middleware. This is happening because the query is already executed and we can't add anything in the document.

hoangtd21 commented 3 years ago

You can use (for mongose v6.0.11):
this.r = await this.findOne().clone();

Read details here: https://mongoosejs.com/docs/migrating_to_6.html

ErfanCE commented 2 years ago

in mongoose v6 you don't need that pre hook any more in post hook use doc.

reviewSchema.post(/^findOneAnd/, async function (document) {
  await document.constructor.calcAverageRatings(document.tour);
});