【问题标题】:Node.js ORM2 check if field already existsNode.js ORM2 检查字段是否已存在
【发布时间】:2014-01-18 17:10:44
【问题描述】:

检查字段值是否已存在的最佳方法是什么。

这是我的模型:

// Set global
var moment = require('moment');
var _  = require('lodash');

// Create model
module.exports = function (orm, db) {

    var Profile = db.define('profile', 
        // Field Properties
        {
            username: {type: 'text', required: true, unique: true},
            name: {type: 'text', required: true},
            email: {type: 'text', required: true},
            password: {type: 'text', required: true},
            birthday: {type: 'date', required: true},
            gender: {type: 'enum', values: ["male", "female"], required: true},
            join_date: {type: 'date'}
        },
        {
            // Model hooks. Manual: https://github.com/dresende/node-orm2/wiki/Model-Hooks
            hooks: {

                beforeValidation: function() {

                    // Set join date to current date
                    this.join_date = new Date();
                }
            },

            // Model Validations. Manual: https://github.com/dresende/node-orm2/wiki/Model-Validations
            validations: {
                username: [orm.enforce.security.username({length: 4}, 'Invalid username')],
                email: [orm.enforce.patterns.email('Please enter a valid email')],
                password: [orm.enforce.security.password('6', 'Invalid password')],
                birthday: [orm.enforce.patterns.match(/\d{2}-\d{2}-\d{4}/, null, 'Invalid birthday')]
            },

            // Model methods. Extra functions and stuff
            methods: {

            }
    });
};

这是我的注册控制器:

module.exports = function (req, res, next) {

    // Get post params
    var params = _.pick(req.body, 'formAction', 'username', 'password', 'email', 'confirm_password',
                            'birthday', 'gender', 'terms');

    // If we try to register
    if (params['formAction'] == 'register') {

        // Manual validations
        // Check if we agreed with the terms
        if (params['terms'] != 1) {

            res.send({error: 'You must agree to the terms of service'});
            return false;   
        }

        // Check if password was confirmed
        if (params['password'] && params['password'] != params['confirm_password']) {

            res.send({error: 'Please confirm your password'});
            return false;
        }

        // Check if username already exists


        // Try to register
        req.models.profile.create({username: params['username'], 
                                   password: params['password'],
                                   email: params['email'],
                                   birthday: params['birthday'], 
                                   gender: params['gender'],
                                   name: params['username']}, function (err, items) {

                                       // Check to see if we have error
                                       error = helpers.getError(err);

                                       // Return error
                                       if (error)
                                           res.send({error: error});
                                   });
    }
    // Show login form
    else
        res.sendfile(settings.path + '/public/register.html');
};

如何检查数据库中是否已经存在用户名?现在,如果我尝试创建,我会从数据库中得到 DUP_KEY 错误。

谢谢, 拉度

【问题讨论】:

    标签: javascript node.js orm express


    【解决方案1】:

    看起来像添加一个钩子并使用 next() 解决了

    beforeCreate: function (next) {
    
                        obj = this;
                        Profile.exists({email: this.email}, function (err, exists) {
                            if (exists) {
                                return next(new Error("Email already exists"));
                            }
                            else
                            {
                                Profile.exists({username: obj.username}, function (err, exists) {
                                    console.log(exists);
                                    if (exists) {
                                        return next(new Error("Username already exists"));
                                    }
                                    else
                                        return next();
                                });
                            }
                        });
                    }
    

    【讨论】:

      猜你喜欢
      • 2018-12-09
      • 1970-01-01
      • 1970-01-01
      • 2017-11-22
      • 1970-01-01
      • 2010-11-24
      • 2019-03-04
      相关资源
      最近更新 更多