gpt4 book ai didi

javascript - Sequelize create 方法忽略验证规则

转载 作者:行者123 更新时间:2023-12-03 22:42:40 25 4
gpt4 key购买 nike

我正在构建一个带有 node、hapi 和 sequelize 的小型 REST API。尝试在没有所需数据的情况下创建新用户时,我预计会出现验证错误。相反,我收到数据库错误。

该模型:

'use strict';
module.exports = function(sequelize, DataTypes) {
var User = sequelize.define('User',
{
email: {
type: DataTypes.STRING,
validate: {notEmpty: true, isEmail: true}
},
password: {
type: DataTypes.STRING,
validate: {notEmpty: true, min: 6}
},
name: {
type: DataTypes.STRING,
validate: {notEmpty: true}
},
is_active: {
type: DataTypes.BOOLEAN
},
api_key: {
type: DataTypes.STRING,
validate: {notEmpty: true}
}
},
{
classMethods: {
associate: function(models) {
// associations can be defined here
User.hasMany(models.Keeper);
}
},
timestamps: true,
createdAt: 'created',
updatedAt: 'modified',
deletedAt: false
}
);
return User;
};

编码:
exports.users = {
/* ... */
create: function(req, reply) {
models.User.create(req.payload)
.then(function(err, user) {
/* ... */
})
.catch(function(err) {
console.log(err);
});
reply('test');
},
/* ... */
};

错误:
{ [SequelizeDatabaseError: ER_NO_DEFAULT_FOR_FIELD: Field 'password' doesn't have a default value]
name: 'SequelizeDatabaseError',
message: 'ER_NO_DEFAULT_FOR_FIELD: Field \'password\' doesn\'t have a default value',
parent:
{ [Error: ER_NO_DEFAULT_FOR_FIELD: Field 'password' doesn't have a default value]
code: 'ER_NO_DEFAULT_FOR_FIELD',
errno: 1364,
sqlState: 'HY000',
index: 0,
sql: 'INSERT INTO `Users` (`id`,`email`,`modified`,`created`) VALUES (DEFAULT,\'email@email.com\',\'2015-04-24 04:35:49\',\'2015-04-24 04:35:49\');' },
original:
{ [Error: ER_NO_DEFAULT_FOR_FIELD: Field 'password' doesn't have a default value]
code: 'ER_NO_DEFAULT_FOR_FIELD',
errno: 1364,
sqlState: 'HY000',
index: 0,
sql: 'INSERT INTO `Users` (`id`,`email`,`modified`,`created`) VALUES (DEFAULT,\'email@email.com\',\'2015-04-24 04:35:49\',\'2015-04-24 04:35:49\');' },
sql: 'INSERT INTO `Users` (`id`,`email`,`modified`,`created`) VALUES (DEFAULT,\'email@email.com\',\'2015-04-24 04:35:49\',\'2015-04-24 04:35:49\');' }

我期待未传递密码的验证错误,而是收到 SQL 错误。呸!

最佳答案

仅当已经为该字段设置了值时才会进行验证。因此,如果密码字段为空,则验证将不会运行。

要解决此问题,请在列上设置 allowNull:

  password: {
type: DataTypes.STRING,
allowNull: false,
validate: {notEmpty: true, min: 6}
},

关于javascript - Sequelize create 方法忽略验证规则,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29838829/

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