Handling Mongoose validation errors – where and how?

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

    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)
    

提交回复
热议问题