【问题标题】:Where to validate in Express.js project – Validation at the database layer (re. Mongoose)?Express.js 项目中在哪里进行验证——在数据库层进行验证(re. Mongoose)?
【发布时间】: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 samepasswordconfirmPassword)。这不能在模式中定义,因为我只在模型中保存 salthash。因此,我需要在路由/控制器中的数据库层之前进行此验证。因此,我将无法同时显示验证消息。

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

【问题讨论】:

    标签: node.js validation model-view-controller express mongoose


    【解决方案1】:

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

    【讨论】:

    • 您的意思是考虑将验证保留在模型中吗?
    • 是的。很抱歉造成混乱。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-21
    • 1970-01-01
    • 1970-01-01
    • 2013-04-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多