如何转换猫鼬模式错误
问题描述:
我想变换全部猫鼬模式错误。如何转换猫鼬模式错误
比方说,我有一个UserSchema:
const UserSchema = new mongoose.Schema({
email: {
type: String,
unique: true,
required: [true, 'E-Mail is required']
},
password: {
type: String,
required: [true, 'Password is required']
}
}
如果我想尝试保存而不电子邮件和密码的用户,我会得到如下回应:
{
"errors": {
"password": {
"message": "Password is required",
"name": "ValidatorError",
"properties": {
"type": "required",
"message": "Password is required",
"path": "password"
},
"kind": "required",
"path": "password"
},
"email": {
// ...
}
},
"_message": "User validation failed",
"name": "ValidationError"
}
我想改变这个错误响应全球为我的所有模式,例如到
{
errors: [
{ message: "Password is required", path: "password" }
// ...
]
}
有没有办法将全局变换方法应用于所有模式错误? (我想避免手动转换每个响应)
答
var schema = new Schema({
name: {
type: String,
required: true
}
});
var Man= db.model('Man', schema);
// This man has no name :(
var man = new Man();
man.save(function(error) {
assert.equal(error.errors['name'].message,
'Path `name` is required.');
error = man.validateSync();
assert.equal(error.errors['name'].message,
'Path `name` is required.');
});
这并不能解决全局问题**。我想拥有一个拦截器,它可以在一个地方转换所有的错误。 – mbppv