node.js sequelize.js 自定义验证器,检查唯一的用户名/密码

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16356856/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 14:24:18  来源:igfitidea点击:

sequelize.js custom validator, check for unique username / password

javascriptnode.jsormsequelize.js

提问by Matt Richards

Imagine I have defined the following custom validator function:

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

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

However, when I attempt to query the DB I run into problems:

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

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.
    });
}

How can I query the ORM in a custom validator and trigger a validation error based on the response from the ORM?

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

回答by alvaropaco

You can verify if the email already exists like that:

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

email: {
  type: Sequelize.STRING,
  allowNull: false,
  validate: {
    isEmail:true
  },
  unique: {
      args: true,
      msg: 'Email address already in use!'
  }
}

回答by c.hill

Here's a simplified sample of a functioning isUniquevalidation callback (works as of SequelizeJS v2.0.0). I added comments to explain the important bits:

这是一个功能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;

回答by Jon Saw

With Sequelize 2.0, you need to catch Validation Errors.

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

First, define the User Model with a custom validator:

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

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;

Then, in the controller, catch any Validation Errors:

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

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
            });
        });

回答by Alejo Dev

Success callback is called even if no user is found. You have to check if the function passes a user as an argument:

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

isUnique: function (email) { // This doesn't work
  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.
      }
    });
}