MongoDB,AngularJS:返回多个错误消息

时间:2015-04-20 15:43:49

标签: angularjs node.js mongodb mongoose

假设我们有 2个必需的属性titlecontent

var ArticleSchema = new Schema({
  created: {
    type: Date,
    default: Date.now
},
  title: {
    type: String,
    default: '',
    trim: true,
    required: 'Title cannot be blank'
},
  content: {
    type: String,
    default: '',
    trim: true,
    required: 'Content cannot be blank'
},
  user: {
    type: Schema.ObjectId,
    ref: 'User'
}
});

此时,当我调用$ save函数时,服务器在第一个错误后停止,并返回一个字符串,其中'标题不能为空白'。有没有办法让mongoose返回所有失败验证的JSON对象?

    // Create new Article
    $scope.create = function() {
        // Create new Article object
        var article = new Articles({
            title: this.title,
            content: this.content
        });

        // Redirect after save
        article.$save(function(response) {
            //success
        }, function(errorResponse) {
            $scope.error = errorResponse.data.message;
            //Desired output
            // errors :{
            //   "Title" : "Title cannot be blank",
            //   "Content" : "Content cannot be blank"}
        });
    };

是服务器端的问题(我应该调整Mongoose模型吗?)还是客户端问题(我应该调整Angular $ save函数' errorResponse?)?

编辑:errorResponse对象的屏幕截图:console.dir(errorResponse)

1 个答案:

答案 0 :(得分:0)

这是一种迂回的方式,因为猫鼬不能为你做这件事。

// Create new Article
    $scope.create = function() {
        // Create new Article object
        var article = new Articles({
            title: this.title,
            content: this.content
        });

    for (i=0; i=number_of_validations;i++){

            // Redirect after save
            article.$save(function(response) {
                //success
        break;
            }, function(errorResponse) {
                $scope.error = errorResponse.data.message;
            if (error == 'Title cannot be...'){
            article.title = "Will be deleted";
            }
            else if (error == 'Content cannot...'){
            article.content = "Will be deleted"
            }
           else // other checks {
            }
            errors.push(error);
             //Desired output
            // errors :{
            //   "Title" : "Title cannot be blank",
            //   "Content" : "Content cannot be blank"}
            });
    }
    if (errors.length != 0){
        article.$remove....//remove article from DB
        console.log(errors);
    }
    };