Handling Mongoose validation errors – where and how?

后端 未结 9 1670
孤城傲影
孤城傲影 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:07

    From Mongoose: https://github.com/leepowellcouk/mongoose-validator

    Error Messages Custom error messages are now back in 0.2.1 and can be set through the options object:

    validate({message: "String should be between 3 and 50 characters"}, 'len', 3, 50)


    How I implemented this:

    var emailValidator = [validate({message: "Email Address should be between 5 and 64 characters"},'len', 5, 64), validate({message: "Email Address is not correct"},'isEmail')];
    
    var XXXX = new Schema({
    email : {type: String, required: true, validate: emailValidator} }); 
    

    My front end deals with required, so I don't ever expect the mongoose "required" error to make it to the user, more of a back end safe guard.

    0 讨论(0)
  • 2020-12-23 20:07

    The question you need to ask yourself is who is responsible for causing the error in the first place?

    If this happens in your system, that you are in control over, just let the errors hit you like you normally would, and weed the bugs out as you go along, but I suspect you are doing an application which is facing real world users and you want to sanitize their inputs.

    I would recommend that client side you check that the input is correct before you send it to your server, and you show nice helper messages like "Your username must be between x and y characters".

    Then on the server side you expect that in 99% of the cases the input will come directly from your sanitizing client, and so you still validate it using the techniques you already suggested, but if there is an error you simply return a general error message to the user interface - since you trust that your user interface would have shown helper messages so the validation error must be caused by a bug or a hacking attempt.

    Remember to log all server side validation errors as they could be severe bugs or someone looking for exploits.

    0 讨论(0)
  • 2020-12-23 20:07

    As of mongoose 4.5.0 Document#invalidate returns a ValidationError. See this https://github.com/Automattic/mongoose/issues/3964

    Also, when trying to invalidate on a findOneAndUpdate query hook, you can do:

    // pass null because there is no document instance
    let err = new ValidationError(null)
    err.errors[path] = new ValidatorError({
        path: 'postalCode',
        message: 'postalCode not supported on zones',
        type: 'notvalid',
        value,
    })
    throw(err)
    
    0 讨论(0)
提交回复
热议问题