Sequelize 创建方法忽略验证规则

Sequelize create method is ignoring validation rules

我正在构建一个带有节点、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 错误。哈尔普!

根据文档,您正在使用的 .catch() 函数似乎在 'Database synchronization' 中使用。由于您的 'then' 函数中已经有 err 参数和回调,因此请将您的控制台日志语句放在那里。像这样:

/* ... */
create: function(req, reply) {
    models.User.create(req.payload)
      .then(function(err, user) {
        if (err){
          console.log(err);
        }
      })
    reply('test');
  },
/* ... */

'then' 函数已经 'catching' 验证错误(如果有的话)。

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

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

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