Cha*_*nce 14 validation mongoose node.js express
你是如何使用Express和Mongoose处理表单验证的?您使用的是自定义方法,某些插件还是默认错误数组?
虽然我可能会看到使用默认错误数组进行一些非常简单的验证,但这种方法似乎在嵌套模型的情况下会爆炸.
Nic*_*can 18
我个人使用node-validator检查用户的所有输入字段是否正确,然后再将它呈现给Mongoose.
节点验证器也非常适合创建可以呈现给用户的所有错误的列表.
Erh*_*han 14
Mongoose有验证中间件.您可以单独为模式项定义验证函数.嵌套项也可以验证.此外,您可以定义asyn验证.有关更多信息,请查看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');
}
...
});
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
9686 次 |
最近记录: |