Thursday 13 April 2017

Custom validation error with mongoose

I want to know if is possible to customize the validation errors in mongoose when I try to update a document.

I get this validation error:

{
  "err": {
    "errors": {
      "batch_number": {
        "message": "Path `batch_number` is required.",
        "name": "ValidatorError",
        "properties": {
          "type": "required",
          "message": "Path `{PATH}` is required.",
          "path": "batch_number",
          "value": ""
        },
        "kind": "required",
        "path": "batch_number",
        "value": ""
      }
    },
    "message": "Validation failed",
    "name": "ValidationError"
  }
}

I want to response an error like this

{
    "errors": {
      "batch_number": "Cannot be null or empty"
      }
}

My model definition:

const mongoose = require('mongoose');
const Schema =  mongoose.Schema;

const batchSchema = Schema({
  batch_number:{type: String, required: true},
  work_order_id:{ type: Schema.Types.ObjectId, ref: 'work_orders' ,required: true},
  start_date_time:{type: Date, required: true},
  end_date_time:{type: Date},
  status:{type: String},
},
{
  timestamps: true
});

const Batch = module.exports = mongoose.model('batches',batchSchema);

If I get more errors in other field the response must be:

{
    "errors": {
      "batch_number": "Cannot be null or empty",
      "start_date_time": "must be a date"
      }
}

Thanks in advance



via joselegit

No comments:

Post a Comment