Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to validate string length with Mongoose?

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?

like image 753
Shamoon Avatar asked Mar 14 '14 13:03

Shamoon


2 Answers

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

like image 70
Pello X Avatar answered Sep 28 '22 02:09

Pello X


The exact string length is like:

...
minlength: 2,
maxlength: 2,
...
like image 22
vaheeds Avatar answered Sep 28 '22 03:09

vaheeds