【发布时间】:2012-12-09 05:48:40
【问题描述】:
我正在用 Express.js 中的表单编写一个应用程序,首先,我在路由(或控制器,如果你愿意)中进行所有验证:
app.post('/register', function (req, res, next) {
// Generic validation
req.assert('name', 'Name is empty').notEmpty();
req.assert('username', 'Username is empty').notEmpty();
var errors = req.validationErrors(true);
if (errors) {
// If there are errors, show them
} else {
// If there are no errors, use the model to save to the database
}
});
但是,我很快了解到我的验证应该在模型中进行,并符合“瘦控制器,胖模型”的原则。
型号:
var userSchema = new Schema({
name: {
type: String
, required: true
, validate: [validators.notEmpty, 'Name is empty']
}
, username: {
type: String
, required: true
, validate: [validators.notEmpty, 'Username is empty']
}
, salt: String
, hash: String
});
路线/控制器:
app.post('/register', function (req, res, next) {
var newUser = new User(req.body);
// Tell the model to try to save the data to the database
newUser.save(function (err) {
if (err) {
// There were validation errors
} else {
// No errors
}
});
});
这很好用。但是,我需要在数据库层之前进行验证。例如,我需要check if two passwords are the same(password 和confirmPassword)。这不能在模式中定义,因为我只在模型中保存 salt 和 hash。因此,我需要在路由/控制器中的数据库层之前进行此验证。因此,我将无法同时显示验证消息。
这是做事的最佳方式吗?在数据库层的模型以及控制器中进行验证?像以前一样在控制器中进行所有验证会更好吗?但随后我将重复代码,再次保存到模型中。或者我应该使用另一种模式,如果是的话,是什么?
【问题讨论】:
标签: node.js validation model-view-controller express mongoose