Vraj
Vraj

Reputation: 95

Having custom validation messages for schema violations in mongodb and nodejs

My schema is following:

var mongoose     = require('mongoose');
var Schema       = mongoose.Schema;

var StudentSchema   = new Schema({
    name: {
        type: String,
        required: [true, 'name must be non empty']
    },
    family: {
        type: String,
        required: [true, 'family must be non empty']
    },
    subjects: {
        type: [String],
        validate: [{
            validator: function(val) {
            return val.length > 0;
            },
            msg: 'Continents must have more than or equal to one elements',
            errorCode: 25
        }
        ]
    },
    created: {
        type: Date,
        default: Date.now
    },
});

But when I post the JSON without name, I see the following error object:

{ [ValidationError: Validation failed]
  message: 'Validation failed',
  name: 'ValidationError',
  errors: 
   { name: 
      { [ValidatorError: Validator "required" failed for path name with value `undefined`]
        message: 'Validator "required" failed for path name with value `undefined`',
        name: 'ValidatorError',
        path: 'name',
        type: 'required',
        value: undefined } } }

So, there are issue with above response:

  1. 'name must be non empty' is not coming anywhere
  2. value is coming as undefined

Is there a way to change message: 'Validator "required" failed for path name with valueundefined'? What is the correct approach?

Upvotes: 3

Views: 951

Answers (1)

Vraj
Vraj

Reputation: 95

The issue was that I was using older version mongoose. After updating it, it is working fine. Updated version to 4.5.3

Upvotes: 1

Related Questions