2017-06-06 64 views
1

我正在構建我的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個錯誤。無論如何,我是如何做到這一點的,而且不會傳遞冗餘數據?

回答

1

你可以只需在將錯誤對象發送到前端之前解析它即可。

下面是如何使用循環做到這一點。

if (err){ 
    let messages = []; 
    for(let i in err){ 
     messages.push({ 
      field: i, 
      message: err[i].message 
     }); 
    } 

    return res.json({success: false, msg: messages}); 
} 

你也可以使用像lodash這樣的庫,使它更清潔。

if (err){ 
    let messages = _.flatMap(err, (value, key) => { field: key, message: value.message }); 
    return res.json({success: false, msg: messages}); 
} 
+0

感謝您的答覆,但我試圖避免解析對象。在這種情況下, – user3315525

+0

看起來是最好的解決方案 – user3315525

0

預測

User.find({}, {messages: 1})

User.find({},'messages')

第二個參數是投影mongoose api

我想你也可以做User.find({},'messages -_id')離開了_id,但如果你正在使用的對象,你可以做{_id : 0}

如果你想與錯誤信息過濾掉對象:

你可以使用.lean()做一個真正的JS對象

這樣做

User.find({}).lean() 
.then(users =>{ 
    user.filter(e => e.name == "ValidationError") 
}) 

沒有測試

+0

你真的可以使用投影與保存返回的錯誤嗎? – user3220633

+0

我對後端文檔進行了過濾編輯 –

+0

@jackblank感謝您的回覆。你的意思是做這樣的事情嗎?//註冊新用戶 exports.signup =(req,res)=> {let} new_user = new User(req.body); new_user.save((ERR,new_user)=> { 如果(ERR){ User.find({})。瘦() 。然後(new_user => { new_user.filter(E =>電子.name ==「ValidationError」) }); return res.json({success:false,msg:err}); } else res.json({success:true,msg:'Successful created new user $ {new_user.username}。'}); }); };'不能使它的工作到目前爲止 – user3315525

相關問題