When to use validate and when to use a validator with mongoose?

tdd

#1

Question

When to use validate and when to use a validator with mongoose?

Answer
It is mainly related to the scope of what we need to check for, most times using a validator will be a perfect solution since, even though limited, mongoose has a variety of validators that span towards most common cases, for example, if the data inputted is a date, we can use min and max to create a margin just like with numbers:

ie, with our dinosaur schema:

const date = new Date();

const DinosaurSchema = new Schema(
  {
    name: {type: String, required: true},
    count: {
      type: Number,
      max: [10, 'Cannot hold more than 10 dinosaurs.']
    },
    year: {
      type: Date,
      min: [date.getFullYear() - 60, 'Cannot be older than 1958'] // I am certainly unsure about what kind of dinosaur I would be referring to...
    },
    risk: {type: String}
  }
);

But a moment we might need to use validate if for example if we wanted dinosaurs whose year is only an even number (using our good friend modulus %):

const date = new Date();

const validator = function(val){
  return val % 2;
}

const DinosaurSchema = new Schema(
  {
    name: {type: String, required: true},
    count: {
      type: Number,
      max: [10, 'Cannot hold more than 10 dinosaurs.']
    },
    year: {
      type: Date,
      validate: validator//let's thing we are talking about people in a disrespectful way
    },
    risk: {type: String}
  }
);