繁体   English   中英

Node.js ORM2检查字段是否已存在

[英]Node.js ORM2 check if field already exists

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

这是我的模型:

// 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错误。

谢谢Radu

看起来像添加一个钩子并使用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();
                            });
                        }
                    });
                }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM