在Express.js项目中validation的地方 – 在数据库层validation(re。Mongoose)?

我正在用Express.js写一个表单的应用程序,首先,我在路由器(或控制器,如果你喜欢的话)中进行所有的validation:

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 } }); 

但是,我很快就了解到,我的validation应该在模型中进行,与“瘦控制器,胖模式”原则保持一致。

模型:

 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 } }); }); 

这很好。 但是,我需要在数据库层之前进行validation。 例如,我需要检查两个密码是否相同 ( passwordconfirmPassword )。 这不能在模式中定义,因为我只在模型中保存salthash 。 因此,我需要在数据库层之前在路由/控制器中进行此validation。 因此,我将无法一起显示validation消息。

这是做事情的最好方式 – 在数据库层以及控制器中的模型中进行validation? 像以前一样在控制器中进行所有的validation会更好吗? 但是,我会重复代码,我再次保存到模型中。 或者我应该使用另一种模式,如果是的话,是什么?

我会考虑将validation逻辑移到模型上,但不要再把模型作为数据库。 该模型比数据库更大。 模型执行validation,如果validation通过,则将数据保存到数据库,如果validation失败,则返回正确的消息,以便路由器可以呈现正确的错误消息。