你在使用Express和Mongoose处理表单验证时是如何操作的?你使用自定义方法、某些插件还是默认的错误数组?
虽然在某些非常简单的验证情况下,你可以考虑使用默认的错误数组,但是这种方法在嵌套模型的情况下可能会出现问题。
虽然在某些非常简单的验证情况下,你可以考虑使用默认的错误数组,但是这种方法在嵌套模型的情况下可能会出现问题。
Mongoose有验证中间件。您可以为模式项单独定义验证函数。嵌套项目也可以进行验证。此外,您可以定义异步验证。要了解更多信息,请查看mongoose页面。
var mongoose = require('mongoose'),
schema = mongoose.Schema,
accountSchema = new schema({
accountID: { type: Number, validate: [
function(v){
return (v !== null);
}, 'accountID must be entered!'
]}
}),
personSchema = new schema({
name: { type: String, validate: [
function(v){
return v.length < 20;
}, 'name must be max 20 characters!']
},
age: Number,
account: [accountSchema]
}),
connection = mongoose.createConnection('mongodb://127.0.0.1/test');
personModel = connection.model('person', personSchema),
accountModel = connection.model('account', accountSchema);
...
var person = new personModel({
name: req.body.person.name,
age: req.body.person.age,
account: new accountModel({ accountID: req.body.person.account })
});
person.save(function(err){
if(err) {
console.log(err);
req.flash('error', err);
res.render('view');
}
...
});