Sequelize create方法忽略了验证规则

时间:2015-04-24 04:39:06

标签: javascript node.js validation model sequelize.js

我正在使用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错误。 HALP!

2 个答案:

答案 0 :(得分:1)

只有在为字段设置了值时才会进行验证。因此,如果密码字段为空,则验证将不会运行。

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

allowNull

答案 1 :(得分:-1)

您正在使用的.catch()函数似乎用于'数据库同步'根据文件。由于您已经拥有了错误的参数和回调,因此'函数,将控制台日志语句放在那里。像这样:

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

'然后'功能已经“抓住”了验证错误,如果有的话。