gpt4 book ai didi

node.js - Express.js 项目中在哪里进行验证 – 数据库层验证(re. Mongoose)?

转载 作者:太空宇宙 更新时间:2023-11-03 22:02:52 25 4
gpt4 key购买 nike

我正在用 Express.js 编写一个带有表单的应用程序,首先,我在路由(或 Controller ,如果您愿意的话)中进行所有验证:

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

但是,我很快了解到我的验证应该在模型中进行,与“瘦 Controller ,胖模型”原则保持一致。

型号:

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

路由/ Controller :

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 (密码confirmPassword)。这无法在架构中定义,因为我只在模型中保存 salthash 。因此,我需要在路由/ Controller 中的数据库层之前进行此验证。因此,我将无法一起显示验证消息。

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

最佳答案

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

关于node.js - Express.js 项目中在哪里进行验证 – 数据库层验证(re. Mongoose)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13993669/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com