【问题标题】:How to display mongoose error to backbone views如何向主干视图显示猫鼬错误
【发布时间】:2014-02-22 23:14:01
【问题描述】:

所以,我有一个主干视图,我试图在其中保存用户

 this.model.save(user_details, { // this is backbone model
                error: function (model, errors) {

                },
                success: function (model, response) {
                }
            });

Backbone Model urlRoot 指向一个后端函数

// here user is a Mongoose schema
user.save(function (err) {
    if (err) {
        res.send(err.errors);

    }
});

我正在 Mongoose 模式中运行一些验证。

如果验证失败,我如何在我的主干视图上显示这些“err.errors”。 如果我控制台记录错误但无法将它们发送回视图,我可以在终端看到。

【问题讨论】:

    标签: validation backbone.js express mongoose schema


    【解决方案1】:

    查看“错误”对象后找到解决方案

    All errors are returned in "errors.resposeText" which has format like
    {
      "key name": {
       "message": "",
       "name": "",
       "path": "",
       "type": "",
       "value": ""
     }
    }
    
    this.model.save(user_details, { // this is backbone model
                error: function (model, errors) {
                    var err = JSON.parse(errors.responseText);
                    $.each(errors, function (name, err) {
                       // do something with error
                       console.log(name + err.message);
                    }
    
    
                },
                success: function (model, response) {
                }
            });
    

    注意:来自 mongodb 的错误(如唯一、dup 键)不会以这种格式附加。所以我们可以将它们更改为 json 并将其包装在 res.errors 中。

    In case of error in unique keys user.save(function (err) {
    
        if (err) {
           if(err.code!='undefined' && err.code=='11000')
               err.errors = {'email':{'message':'This unique value is already in db'}};
           res.send(500, err.errors);
        } 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-08-10
      • 1970-01-01
      • 2020-03-10
      • 2011-03-21
      • 1970-01-01
      • 1970-01-01
      • 2017-05-03
      • 2017-10-27
      相关资源
      最近更新 更多