Password field validation

To add validation constraints on the actual password string selected by the end user, we will need to add custom validation logic and associate it with the hashed_password field in the schema.

mern-skeleton/server/models/user.model.js:

UserSchema.path('hashed_password').validate(function(v) {
if (this._password && this._password.length < 6) {
this.invalidate('password', 'Password must be at least 6 characters.')
}
if (this.isNew && !this._password) {
this.invalidate('password', 'Password is required')
}
}, null)

To ensure that a password value is indeed provided, and has a length of at least six characters when a new user is created or existing password is updated, custom validation is added to check the password value before Mongoose attempts to store the hashed_password value. If validation fails, the logic will return the relevant error message.

Once the UserSchema is defined, and all the password related business logic is added as discussed previously, we can finally export the schema at the bottom of the user.model.js file, in order to use it in other parts of the backend code.

mern-skeleton/server/models/user.model.js:

export default mongoose.model('User', UserSchema)