Search code examples
javascriptmongodbmongoosemongodb-querymongoose-schema

Mongoose validate length of array in schema


I want to create a schema, with arrays for names of participants at an event, I make the list of participants by doing so:

  quizPart:[{
    type:String,
  }]

How can I validate that the length of this array is either zero (no participants at this event) or 2, and not 1 (it is a two people per team event). I want to return an error message that I can handle with ValidationError

I am adding data to this schema like so:

var school = new School();
school.quizPart=req.body.quiz;

where req.body.quiz = ["name1","name2"] or ['','']

and then, if only 1 field has a string value, I want to parse an error to the repsonse body like so:

    function handleValidationError(err, body) {
      for (field in err.errors) {
        switch (err.errors[field].path) {
          case "quizPart":
            body["quizPartError"] = err.errors[field].message;
            break; 
}}}

Solution

  • Made the field:

      quizPart:[{
        type:String,
      }],
    

    And then verified the field by:

    schoolSchema.path('quizPart').validate((list)=>{
      alNumRegex= /^[a-z0-9]+$/i
      return list[0]!=="" && list[1]!=="" || alNumRegex.test(list[0]) && alNumRegex.test(list[1]);
    },'Please Register atleast two participants for quiz.');