Reputation: 43491
My validation is:
LocationSchema.path('code').validate(function(code) {
return code.length === 2;
}, 'Location code must be 2 characters');
as I want to enforce that the code
is always 2 characters.
In my schema, I have:
var LocationSchema = new Schema({
code: {
type: String,
trim: true,
uppercase: true,
required: true,
},
I'm getting an error: Uncaught TypeError: Cannot read property 'length' of undefined
however when my code runs. Any thoughts?
Upvotes: 14
Views: 24179
Reputation: 2913
The exact string length is like:
...
minlength: 2,
maxlength: 2,
...
Upvotes: 3
Reputation: 481
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
Upvotes: 42
Reputation: 6805
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');
Upvotes: 10