如何迭代Mongoose返回的错误?

时间:2017-07-02 14:27:10

标签: node.js mongoose mongoose-schema

我的模型看起来像这样:

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?

1 个答案:

答案 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);