2

我正在用 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
    }
  });
});

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

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

4

1 回答 1

2

我会考虑将验证逻辑移至模型,但不要将模型视为数据库。模型大于数据库。模型执行验证,如果验证通过,则将数据保存到数据库中,如果验证失败,则返回正确的消息,以便路由器可以呈现正确的错误消息。

于 2012-12-21T19:40:38.917 回答