Modify data in mongoose pre-validate hook

Viewed 521

I would like to modify a document field's data prior to it being validated by mongoose, like so:

mySchema.pre("validate", function (next) {
  this.myField = "yay a new value prior to validation" // doesn't work for me

  next();
});

Unfortunately, that doesn't work for me. The example above is simplified, in my project I'm trying to prevent an ObjectParameterError from crashing my server, and assigning values in my pre-validate hook doesn't work for me.

1 Answers

Try using .set() method of mongoose Document to access value. Your code should be changed this way

mySchema.pre("validate", function (next) {
  this.set("myField", "yay a new value prior to validation")
  next();
});
Related