Skip to content

Instantly share code, notes, and snippets.

@deepal
Created March 24, 2019 18:11
Show Gist options
  • Select an option

  • Save deepal/f313396230cf3afb32e2b3c6ccd7ee82 to your computer and use it in GitHub Desktop.

Select an option

Save deepal/f313396230cf3afb32e2b3c6ccd7ee82 to your computer and use it in GitHub Desktop.
schema.pre('findOneAndUpdate', function (next) {
const MongooseValidationError = mongoose.Error.ValidationError,
model = this.model(),
immutableFields = ['email', 'password'],
update = this.getUpdate();
immutableFields.forEach((field) => {
if (update.hasOwnProperty(field)) {
model.invalidate(field, `${field} cannot be modified`, update[field], 'immutable');
}
});
if (model.errors) {
const validationError = new MongooseValidationError(null);
validationError.errors = model.errors;
return next(validationError);
}
return next();
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment