我的模型看起来像这样:
user.js的
var AuthorSchema = Schema({
first_name: {type: String, required: true, minlength: 5, maxlength: 20},
last_name: {type: String, minlength: 5, maxlength: 20},
username: {type: String, required: true, match: /([0-9A-Za-z]){5,20}/},
password: String,
email: {type: String, required: true,
validate: function(email) {
return /^[a-zA-Z0-9.!#$%&’*+\/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/.test(email)
}
},
createdOn: {type: Date, default: Date.now },
updatedOn: {type: Date, default: Date.now }
});
app.js
a = new my_models.Author({
first_name: 'err', ## invalid
username: 'tim001@', # invalid
password: 'pass',
email: 'aaa', # invalid
});
a.save(function (err) {
if(err) { console.log(err) return; }
console.log("Author saved")
});
如何通过mongoose返回错误对象来进行iternate?
答案 0 :(得分:0)
您可以在保存数据之前检查验证。试试这样的事情
const a = new my_models.Author({ first_name: 'err', username: 'tim001@', password: 'pass', email: 'aaa', });
const validateResult = a.validateSync();
const {message} = validateResult.errors.name;
console.log(message);