7

想象一下,我已经定义了以下自定义验证器函数:

isUnique: function () { // This works as expected
  throw new Error({error:[{message:'Email address already in use!'}]});
}

但是,当我尝试查询数据库时,我遇到了问题:

isUnique: function (email) { // This doesn't work
  var User = seqeulize.import('/path/to/user/model');

  User.find({where:{email: email}})
    .success(function () { // This gets called
      throw new Error({error:[{message:'Email address already in use!'}]});  // But this isn't triggering a validation error.
    });
}

如何在自定义验证器中查询 ORM 并根据 ORM 的响应触发验证错误?

4

5 回答 5

27

您可以像这样验证电子邮件是否已经存在:

email: {
  type: Sequelize.STRING,
  allowNull: false,
  validate: {
    isEmail:true
  },
  unique: {
      args: true,
      msg: 'Email address already in use!'
  }
}
于 2017-01-19T14:43:39.800 回答
15

这是一个功能isUnique验证回调的简化示例(从 SequelizeJS v2.0.0 开始工作)。我添加了注释来解释重要的部分:

var UserModel = sequelize.define('User', {

    id: {
        type: Sequelize.INTEGER(11).UNSIGNED,
        autoIncrement: true,
        primaryKey: true
    },
    email: {
        type: Sequelize.STRING,
        validate: {
            isUnique: function(value, next) {

                UserModel.find({
                    where: {email: value},
                    attributes: ['id']
                })
                    .done(function(error, user) {

                        if (error)
                            // Some unexpected error occured with the find method.
                            return next(error);

                        if (user)
                            // We found a user with this email address.
                            // Pass the error to the next method.
                            return next('Email address already in use!');

                        // If we got this far, the email address hasn't been used yet.
                        // Call next with no arguments when validation is successful.
                        next();

                    });

            }
        }
    }

});

module.exports = UserModel;
于 2013-10-10T21:47:38.973 回答
11

使用 Sequelize 2.0,您需要捕获验证错误。

首先,使用自定义验证器定义用户模型:

var User = sequelize.define('User',
    {
        email: {
            type: Sequelize.STRING,
            allowNull: false,
            unique: true,
            validate: {
                isUnique: function (value, next) {
                    var self = this;
                    User.find({where: {email: value}})
                        .then(function (user) {
                            // reject if a different user wants to use the same email
                            if (user && self.id !== user.id) {
                                return next('Email already in use!');
                            }
                            return next();
                        })
                        .catch(function (err) {
                            return next(err);
                        });
                }
            }
        },
        other_field: Sequelize.STRING
    });

module.exports = User;

然后,在控制器中,捕获任何验证错误:

var Sequelize = require('sequelize'),
    _ = require('lodash'),
    User = require('./path/to/User.model');

exports.create = function (req, res) {
    var allowedKeys = ['email', 'other_field'];
    var attributes = _.pick(req.body, allowedKeys);
    User.create(attributes)
        .then(function (user) {
            res.json(user);
        })
        .catch(Sequelize.ValidationError, function (err) {
            // respond with validation errors
            return res.status(422).send(err.errors);
        })
        .catch(function (err) {
            // every other error
            return res.status(400).send({
                message: err.message
            });
        });
于 2014-11-28T10:17:39.727 回答
4

即使没有找到用户,也会调用成功回调。您必须检查函数是否将用户作为参数传递:

isUnique: function (email) {
  var User = seqeulize.import('/path/to/user/model');

  User.find({where:{email: email}})
    .success(function (u) { // This gets called
      if(u){
        throw new Error({error:[{message:'Email address already in use!'}]});  // But this isn't triggering a validation error.
      }
    });
}
于 2013-09-19T20:46:35.937 回答
0

使用自定义验证器定义用户模型:

const { DataTypes } = require('sequelize');
const sequelize = require('../config/db');

const UserModel = sequelize.define('user', {
  id: {
    type: DataTypes.INTEGER(11).UNSIGNED,
    autoIncrement: true,
    primaryKey: true,
  },
  name: {
    type: DataTypes.STRING,
    allowNull: false,
  },
  email: {
    type: DataTypes.STRING,
    allowNull: false,
    validate: {
      isUnique: (value, next) => {
        UserModel.findAll({
          where: { email: value },
          attributes: ['id'],
        })
          .then((user) => {
            if (user.length != 0)
              next(new Error('Email address already in use!'));
            next();
          })
          .catch((onError) => console.log(onError));
      },
    },
  },
  password: {
    type: DataTypes.STRING,
    allowNull: false,
  },
  createdAt: {
    type: DataTypes.DATE,
    allowNull: false,
  },
  updatedAt: {
    type: DataTypes.DATE,
    allowNull: false,
  },
});

module.exports = UserModel;
于 2021-05-22T12:00:26.840 回答