Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

why not use this simple line in one single method instead of that confusing way to access doc and model! #190

Open
Mahmoud-AbouDeghedy opened this issue Apr 21, 2023 · 4 comments

Comments

@Mahmoud-AbouDeghedy
Copy link

reviewSchema.post(/^findOneAnd/, async function (doc) {
  await this.model.calcAverageRatings(doc.tour);

instead of

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);
@developedbyjay
Copy link

The course is old, that was how it has to be done as at then

@Mahmoud-AbouDeghedy
Copy link
Author

TypeError: Cannot read property 'tour' of null\n at model.Query.

i got that error. Don't know what is wrong

which code u tried?

@developedbyjay
Copy link

developedbyjay commented May 19, 2023 via email

@lorand-horvath
Copy link

lorand-horvath commented Jun 22, 2023

The best way is to simply include both post hooks and access the model via doc.constructor, like so:

reviewSchema.post(['save', /^findOneAnd/], async function(doc) {
    // Review === doc.constructor
    const stats = await doc.constructor.calcRatingsAverage(doc.product);
});

I'm not sure what's up with all the other convoluted methods...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants