Reputation: 311
I want to validate a field before setting it, but my current code runs the validator after setting it. Is there a way to do it the other way around?
password: {
type: String,
required: true,
validate: {
validator: function(password) {
return password.length > 9;
}
},
set: v => encryptPassword(v)
This code checks the encrypted password's length but I want to check the unencrypted password's length.
Upvotes: 1
Views: 198
Reputation:
Use pre middleware:
schema.pre('save', function(next) {
this.password = /*encrypted password algorithm*/;
next();
});
The validator will run before the pre middleware, so you encrypt the password after having validated the password. We use a regular function
because we need access to this
, and I'm not sure what kind of password encryption you're using.
Upvotes: 1