How to validate string length with Mongoose?
Much simpler with this:
var LocationSchema = new Schema({
code: {
type: String,
trim: true,
uppercase: true,
required: true,
maxlength: 2
},
https://mongoosejs.com/docs/schematypes.html#string-validators
The field "code" is validated even if it is undefined so you must check if it has a value:
LocationSchema.path('code').validate(function(code) {
return code && code.length === 2;
}, 'Location code must be 2 characters');
The exact string length is like:
...
minlength: 2,
maxlength: 2,
...