当我使用sequelize编辑对象时,如何验证唯一字段

时间:2014-07-15 18:34:57

标签: validation sequelize.js

我在创建用户对象时使用以下代码来验证用户伪的唯一性。问题是,当我编辑用户对象时,我需要检索当前的user.id.我怎么能这样做?

pseudo:   {
  type: DataTypes.STRING(150), 
  allowNull: false, 
  validate: {
    len: {args: [3, 150], msg: "Pseudo shall contains at least 3 characters"},
    isUnique: function(value, next) {
      User.find({
          where: {pseudo: value},
          attributes: ['id']
      }).done(function(error, user) {
        if (error)
            return next(error);

        if (user)
            return next('Pseudo already in use!');

        next();
      });
    }
  }

1 个答案:

答案 0 :(得分:1)

我是这样做的:

pseudo:   {
  type: DataTypes.STRING(150), 
  allowNull: false, 
  validate: {
    len: {args: [3, 150], msg: "Pseudo shall contains at least 3 characters"},
    isUnique: function(value, next) {
      var id = this.getDataValue('id');

      User.find({
          where: {pseudo: value},
          attributes: ['id']
      }).done(function(error, user) {
        if (error)
            return next(error);

        if (user && user.id !== id)
            return next('Pseudo already in use!');

        next();
      });
    }
  }
},