当我尝试更新数据库中的记录时,我的模型验证不会执行。该函数更新信息但不验证它。这是更新功能
exports.update = (req, res) => {
const id = req.params.id;
const updateUser = {
firstName: req.body.firstName,
lastName: req.body.lastName,
password: req.body.password,
confirm: req.body.confirm,
email: req.body.email,
}
User.update(updateUser, { where: { id: id } })
.then(user => {
delete updateUser.password; delete updateUser.confirm;
res.status(200).json({ msg: "Updated!", user: updateUser })
})
.catch(err => {
if (err instanceof ValidationError) {
let msgs = err.errors.map(error => error.message)
res.status(422).json(msgs)
}
})
.catch(err => res.status(400).json('Ups...' + err));
}
const { Model } = require('sequelize');
module.exports = (sequelize, DataTypes) => {
class User extends Model {
static associate(models) {}
};
User.init({
firstName: {
type: DataTypes.STRING,
allowNull: false,
validate: {
notNull: {
msg: "Not Null"
},
isAlpha: {
args: true,
msg: "Alpha"
},
notEmpty: {
args: true,
msg: "Not Empty"
},
len: {
args: [3, 255],
msg: "Length error"
},
}
},
}, {
sequelize,
modelName: 'User',
hooks: {
afterCreate(record) {
delete record.dataValues.id;
delete record.dataValues.password;
delete record.dataValues.confirm;
},
}
});
return User;
};
sequelize 手册:模型验证器允许您为模型的每个属性指定格式/内容/继承验证。创建、更新和保存时会自动运行验证
请问这个问题解决了吗?