davidbaguetta
davidbaguetta

Reputation: 532

Mongoose field validation not working correctly

I'm using the library validator to validate the Dates in my Mongoose Schemas.

I have the following code:

var validator = require('validator');

var TesteSchema = new Schema({
  testeData: { type: Date, required: true, validate: validator.isISO8601}

Since Mongoose saves Dates in the ISO8601 format, I'm validating it accordingly. But the problem is the validation is returning false, even when I provide it with a valid ISO Date.

Upvotes: 0

Views: 1035

Answers (1)

Jason Cust
Jason Cust

Reputation: 10899

Expanding on my comment: "The validator function expects a string but Mongoose has already cast the value to a date by the time the validator is executed."

See the following code below to see this happening:

const mongoose = require('mongoose');

const TesteSchema = new mongoose.Schema({
  testeData: {
    type: Date,
    required: true,
    validate: (v) => v instanceof Date
  }
});
const Teste = mongoose.model('Teste', TesteSchema);

const teste = new Teste({
  testeData: '11/11/2018'
});

teste.validate(); // true

Update

One approach to validate the string input is to store the value as a string and if necessary to also have a date version then a setter can be used to store this value to another property to be stored.

const mongoose = require('mongoose');
const validator = require('validator');

const TesteSchema = new mongoose.Schema({
  testeData: {
    type: String,
    required: true,
    validate: validator.isISO8601,
    set: function (d) { return this._testeData = d; }
  },
  _testeData: {
    type: Date,
    required: true
  }
});
const Teste = mongoose.model('Teste', TesteSchema);

const testeBad = new Teste({
  testeData: '11/11/2018'
});
console.log(testeBad);
/*
{
  _id: ObjectId('5aeb55c58e374e7034c8a1bb'),
  _testeData: IsoDate('Sun Nov 11 2018 00:00:00 GMT-0500 (EST)'),
  testeData: '11/11/2018'
}
*/
testeBad.validate(); // Teste validation failed: testeData: Validator failed for path `testeData` with value `11/11/2018`

const testeGood = new Teste({
  testeData: '2018-11-11T00:00:00'
});
console.log(testeGood);
/*
{
  _id: ObjectId('5aeb55c58e374e7034c8a1bc'),
  _testeData: IsoDate('Sun Nov 11 2018 00:00:00 GMT-0500 (EST)'),
  testeData: '2018-11-11T00:00:00'
}
*/
testeGood.validate(); // true

Upvotes: 1

Related Questions