Handling Mongoose validation errors – where and how?

后端 未结 9 1720
孤城傲影
孤城傲影 2020-12-23 19:45

I\'m trying to decide how I want to handle validation errors in Mongoose.

Custom error messages using node-validator

I have defined my own validation rules

9条回答
  •  青春惊慌失措
    2020-12-23 20:04

    See the hmv package, which helps you customize the mongoose error message templates, including unique index errors :

    template : {PATH_NAME} must be at least {MIN_LENGTH} characters long
    schema   : { fullname : { type : String, min : 3, $name : 'Full name' } }
    message  : Full name must be at least 3 characters long
    
    template : {PATH_NAME} {VALUE} have been used, please choose another
    schema   : { username : { type : String, unique : true } }
    message  : username MrBean have been used, please choose another
    

    And specifically supports localization, ex in Vietnamese :

    template : {PATH_NAME} dài ít nhất {MIN_LENGTH} kí tự
    schema   : { fullname : { type : String, min : 3, $name : 'tên tài khoản' } }
    message  : Tên tài khoản dài ít nhất 5 kí tự
    

    Good point is that you only need to customize the message template once, instead of customizing every field of every schema in the previous approach.

提交回复
热议问题