是否可以自定义mongoose中的错误?

时间:2018-05-06 16:30:52

标签: mongoose

假设我有架构:

const transactionSchema = new mongoose.Schema({
    "ID": {
        type:String,
        required:true,
        maxlength:36,
        minlength:35,
    }
...
}

如果我的客户端尝试保存长度小于34的ID文件,那么mongoose会产生此错误

{
  "errors": {
    "ID": {
      "message": "Path `ID` (`k2131381a2asaddaddsdsw12sa3`) is shorter than the minimum allowed length (35).",
      "name": "ValidatorError",
      "properties": {
        "minlength": 35,
        "type": "minlength",
        "message": "Path `{PATH}` (`{VALUE}`) is shorter than the minimum allowed length (35).",
        "path": "ID",
        "value": "k2131381a2asaddaddsdsw12sa3"
      },
      "kind": "minlength",
      "path": "ID",
      "value": "k2131381a2asaddaddsdsw12sa3",
      "$isValidatorError": true
    }
  },
  "_message": "transaction validation failed",
  "message": "transaction validation failed: ID: Path `ID` (`k2131381a2asaddaddsdsw12sa3`) is shorter than the minimum allowed length (35).",
  "name": "ValidationError"
}

现在为了告诉我的客户错误的确切原因(即ID比预期的短)我必须做很多努力并编写各种if if语句:

if(error && error.ID && error.ID.kind === 'minlength'){
   res.status(400).json({error:45});//error 45 refers to ID length errors. Client knows about it
}

我做错了吗?当ID长度不合适时,是否有一种干净的方式告诉mongoose只给我一个错误代码45?

1 个答案:

答案 0 :(得分:2)

您可以在validate定义中使用Schema对象。

message中的validate对象中,您可以指定您选择的任何消息

const transactionSchema = new mongoose.Schema({
    "ID": {
        type:String,
        required:true,
        validate : {
            validator : (data)=>{
                if(data.length >=35 && data.length <=36 ){
                    return true; //validation success
                }
                else{
                    return false; // validation failure
                }
            },
            message : "Length mismatch. Length must be >=35 and <=36"
        }
    }
...
}

假设您必须在此架构中插入记录,您可以在执行validateSync()操作之前使用insert方法触发架构中指定的验证。

var transaction = new transaction({ID : "myid"});
var validationResult = transaction.validateSync();
if(validationResult == null){
    //validation success
    //proceed with insert operation
}
else{
    //validation failure
    //you can extract all the key fields that failed the validation using errors object in validationResult object

    for (x in validationResult.errors) {
        // print error messages of specific field
        console.log(validationResult.errors[x].message);
    }
}

您可以打印validationResult对象以查看validationResult对象的内容。

对我们来说,最有用的对象是validationResult.errors对象,如上面的代码所示