defined validation error message are not showing in node.js

654 Views Asked by At

I am a MEAN learner.

I have write a Schema and save it in Controller class. In the schema i define validation error message like this way

var userSchema = new Schema( {
      name: {type: String, required : 'please insert name'}
  });
User = mongoose.model('User', userSchema);

module.exports = {
User : User
};

save it in controller class and print err

insertUser.save(function (err,user){
    if(err) {
        console.log(err);
        res.send(err);
    }
    else res.send("inserted user name : " + user.name);
});

But i find error message

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

what change make me achieve to display proper validation message ??

1

There are 1 best solutions below

0
On
var userSchema = new Schema({
   name: { type: String }
});

userSchema.path('name').validate(function (value) {

  return value.length !== 0;

}, 'please insert name');