Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to define array of Strings in mongoose?

I want to define a document as

numbers : ["99995", "44444", "666664".....]

The numbers shouldn't start with 0 and length should be 5. Also there should be minimum 1 element

The mongoose schema that I defined in something of this type

numbers: {
  type: [String],
  length : 5,
  validator : (num) => {
      return /[1-9]{1}\d{4}.test(num);
    },
    message: props => `${props.value} is not a valid number!` 
  }    
}

But how should I put a check on the numbers length ie minimum one is required ?

like image 396
Ankuj Avatar asked Sep 03 '25 08:09

Ankuj


1 Answers

"when you create a custom validator you can do any thing in your function to validate your data. You must only return true when the vlidation is passed and false if it fails."

validator: (num) => {
    if(num.length == 5) {
         return /[1-9]{1}\d{4}/.test(num); // You forgot to add / at the end of the RegEx
    }
    return false;
}

or you can use the match to validate string with regex instead of creating you own function

numbers: {
     type: [String], match: /^[^0]\d{4}$/
}
like image 152
Yves Kipondo Avatar answered Sep 05 '25 01:09

Yves Kipondo