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

Using Mongoose pre hook to get document before findOneAndUpdate() #7497

Closed
darrenbrett opened this issue Feb 7, 2019 · 1 comment
Closed

Comments

@darrenbrett
Copy link

I am running "mongoose": "5.4.9".

I am trying to use Mongoose pre and post hooks in my MongoDB backend in order to compare the document in its pre and post-saved states, in order to trigger some other events depending on what's changed. So far however I'm having trouble getting the document via the Mongoose pre hook.

According to the docs "pre hooks work for both doc.save() and doc.update(). In both cases this refers to the document itself... ". So I here's what I tried. First in my model/schema I have the following code:

let Schema = mongoose
  .Schema(CustomerSchema, {
    timestamps: true
  })
  .pre("findOneAndUpdate", function(next) {
    trigger.preSave(next);
  })
  // other hooks
}

... And then in my triggers file I have the following code:

exports.preSave = function(next) {
  console.log("this: ", this);
  }
};

But this is what logs to the console:

this: { preSave: [Function], postSave: [AsyncFunction] }

So clearly this didn't work. This didn't log out the document as I was hoping for. Why is this not the document itself here, as the docs themselves appear to indicate? And is there a way I can get a hold of the document with a pre hook?

@vkarpov15
Copy link
Collaborator

Read up on query middleware vs document middleware: https://mongoosejs.com/docs/middleware.html#types-of-middleware

@Automattic Automattic locked as resolved and limited conversation to collaborators Feb 9, 2019
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants