MongoDB,AngularJS:返回多条错误消息
假设我们有两个必需的属性MongoDB,AngularJS:返回多条错误消息,angularjs,node.js,mongodb,mongoose,Angularjs,Node.js,Mongodb,Mongoose,假设我们有两个必需的属性title和content var ArticleSchema = new Schema({ created: { type: Date, default: Date.now }, title: { type: String, default: '', trim: true, required: 'Title cannot be blank' }, content: { type: String,
title
和content
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函数时,服务器在第一个错误后停止,并返回一个带有“Title不能为空”的字符串。有没有办法让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对象的屏幕截图:这是一种迂回的方式,因为mongoose不能为您这样做
// 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);
}
};
errorResponse.errors输出什么?你能用console.dir吗?一般来说,这样做有意义吗?比如说,我需要标题和内容长度>标题长度。如果标题为空,您将如何根据内容进行验证(如果我传入字符串)?我添加了errorResponse对象的屏幕截图。它不包含错误属性。ABOS,是的,这是有意义的,你可以在标题为空时添加一个if条件