我正在構建我的node.js api,並希望僅傳遞有關錯誤的回調消息。現在,我需要有一個處理這樣如何僅將錯誤消息從模型傳遞給控制器(Mongoose)?
{
"success": false,
"msg": {
"errors": {
"email": {
"message": "[email protected] is not a valid email!",
"name": "ValidatorError",
"properties": {
"type": "user defined",
"message": "{VALUE} is not a valid email!",
"path": "email",
"value": "[email protected]"
},
"kind": "user defined",
"path": "email",
"value": "[email protected]"
},
"username": {
"message": "The Username is not long enough",
"name": "ValidatorError",
"properties": {
"type": "user defined",
"message": "The Username is not long enough",
"path": "username",
"value": "te"
},
"kind": "user defined",
"path": "username",
"value": "te"
}
},
"_message": "Users validation failed",
"name": "ValidationError"
}
}
這裏對象是我的代碼 userModel.js
/* Custom Validation */
const validator = (v)=> {
return v.length > 5;
};
/* END of Custom Validation */
const UserSchema = new Schema({
username: {
type: String,
validate: [
validator,
'The Username is not long enough'
],
required: [true, 'The Username is required'],
unique: true,
lowercase: true
},
password: {
type: String,
required: [true, 'The Password is required']
},
email: {
type: String,
validate: [
(v)=> { return /^(([^<>()\[\]\.,;:\[email protected]\"]+(\.[^<>()\[\]\.,;:\[email protected]\"]+)*)|(\".+\"))@(([^<>()[\]\.,;:\[email protected]\"]+\.)+[^<>()[\]\.,;:\[email protected]\"]{2,})$/i.test(v)},
'{VALUE} is not a valid email!'
],
lowercase: true,
required: true
},
role: {
type: [{
type: String,
enum: ['user', 'manager', 'admin']
}],
default: ['user']
},
team: {
type: [{
type: String,
enum: ['IHLO', 'ADULT&SH', 'IPJ', 'ISD', '']
}],
default: ['']
},
created_date: {
type: Date,
default: Date.now
},
});
UserSchema.pre('save', ...
UserSchema.methods.comparePassword = ...
module.exports = mongoose.model('Users', UserSchema);
**userController.js**
/Register new user
exports.signup = (req, res)=> {
let new_user = new User(req.body);
new_user.save((err, new_user)=> {
if (err)
return res.json({success: false, msg: err});
res.json({success: true, msg: `Successful created new user ${new_user.username}.`});
});
};
我當然可以上搜索「消息的前端功能'鍵,但對於一些記錄,它可能超過100個錯誤。無論如何,我是如何做到這一點的,而且不會傳遞冗餘數據?
感謝您的答覆,但我試圖避免解析對象。在這種情況下, – user3315525
看起來是最好的解決方案 – user3315525