使用mongoose进行自定义验证错误

时间:2017-04-13 23:41:21

标签: node.js mongodb express mongoose

我想知道当我尝试更新文档时是否可以在mongoose中自定义验证错误。

我收到此验证错误:

{
  "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"
  }
}

我想回复像这样的错误

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

我的模型定义:

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);

如果我在其他字段中收到更多错误,则响应必须为:

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

提前致谢

更新

我遵循安德烈的建议,我收到相同的错误消息

const express = require('express')
Batch = require('./../../database/controllers/production/batches');

function mongooseErrorHandler (err, req, res, next) {
    if (err.errors) {
      console.log(err);
        const error = {};
        const keys = Object.keys(err.errors);

        keys.forEach((key) => {
            let message = err.errors[key].message;

            if (err.errors[key].properties && err.errors[key].properties.message) {
                message = err.errors[key].properties.message.replace('`{PATH}`', key);
            }

            message = message.replace('Path ', '').replace(key,'').trim();
            error[key] = message;
        });
        return res.status(500).json(error);
        //return next(error);
    }

    next();
};

module.exports = function(app){
  app.put('/api/batches/:_id',mongooseErrorHandler,(req, res, err) => {
      var id = req.params._id;
      var batch = req.body;
      Batch.update(id, batch,{}, (err, batch) => {
          res.status(200).json(batch);
      });
  });
}

1 个答案:

答案 0 :(得分:1)

您应该创建一个中间件来处理猫鼬错误:

function mongooseErrorHandler (err, req, res, next) {
    if (err.errors) {
        const error = {};
        const keys = Object.keys(err.errors);

        keys.forEach((key) => {
            let message = err.errors[key].message;

            if (err.errors[key].properties && err.errors[key].properties.message) {
                message = err.errors[key].properties.message.replace('`{PATH}`', key);
            }

            message = message.replace('Path ', '').replace(key,'').trim();
            error[key] = message;
        });

        return res.status(500).json(error); // or return next(error);
    }

    next();
};

并将其添加到您的路线中。例如:

router.get('/batch', mongooseErrorHandler, (req, res, err) =>{
    ...
});

或者如果您在中间件中使用next(err)

router.get('/batch', mongooseErrorHandler, (req, res, err) =>{
    if (err) res.status(500).json(err);
    ...
});