Mongoose: How to track fields changes at update?

Created on 15 Dec 2016  路  2Comments  路  Source: Automattic/mongoose

I have a User schema with a path email. I want track changes over this field, so, when the user changes his email, a job is executed. Which is the way to do it with mongoose, since the update hooks pass a Query instead a Document (can't use isModified(path))?

Most helpful comment

You can access getUpdate() in a pre update hook to check whether email is getting updated or not:

mySchema.pre('update', function() {
  if (this.getUpdate().email) {
    // Run job
  }
});

You can't use isModified(), but email won't change unless email is in the update

All 2 comments

Actually, instead of use Model.update, I follow this pattern:

  • Fetch the model to update via ID
  • Assign manually the new values (user.email = data.email || user.email)
  • Use save method.

So, with this way I'm able to get the document inside the pre save hook and I can check if the path was changed via doc.isModified('email').

Would be great if docs are availabe on update and remove hooks too. It is possible?

You can access getUpdate() in a pre update hook to check whether email is getting updated or not:

mySchema.pre('update', function() {
  if (this.getUpdate().email) {
    // Run job
  }
});

You can't use isModified(), but email won't change unless email is in the update

Was this page helpful?
0 / 5 - 0 ratings