0
我想知道是否可以在我嘗試更新文檔時自定義貓鼬中的驗證錯誤。用貓鼬定製驗證錯誤
我得到這個驗證錯誤:
{
"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"
}
}
在此先感謝
UPDATE:
我跟安德烈的建議,我也得到了同樣的錯誤消息
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);
});
});
}
我按照你的建議,我也得到了相同的結果。我想我嘗試實施您的解決方案時出錯。請參閱更新 – joselegit
感謝它的工作我犯了一個錯誤,當我修復它時,中間件功能正常工作 – joselegit
很高興幫助:) –