Mongoose-How to restrict date to be bigger than today´s date?

Viewed 709

For this model I want to prevent that an user sets a Date previous to today´s Date. How can I do it?

var requestSchema = new Schema({
  paciente: {
    type: mongoose.Schema.Types.ObjectId,
    ref: "User",
  },
  encaminhado: {
    type: Boolean,
    required: [true, "encaminhado is a required field"],
  }, //vem do body
  pessoaRisco: {
    type: Boolean,
    required: [true, "pessoaRisco is a required field"],
  }, //vem do body
  trabalhoRisco: {
    type: Boolean,
    required: [true, "trabalhoRisco is a required field"],
  }, //vem do body
  estadoPedido: {
    type: String,
    enum: ["Pendente", "Agendado", "Concluído", "Aguarda Resultado"],
  },
  resultado: { type: String, enum: ["Positivo", "Negativo"] },
  dataExame: { type: Date }, //data tem de ser superior a data atual
});
1 Answers

You can use a validation function, something like:

dataExame: { 
    type: Date,
    validate: function(input) {
        /* return true only if the input is a valid date, AND is 
        greater than or equal to the current date/time */
        return typeof new Date(input) === 'date' && new Date(input) >= new Date();
    },
    message: input => `${input} must be greater than or equal to the current date!`
}, //data tem de ser superior a data atual
Related