TypeError:无法调用未定义的方法'toLowerCase'

时间:2013-12-04 09:33:29

标签: javascript node.js

我遇到了一个错误,我不知道为什么。我尝试在插入数据库之前将所有字符转换为小写并用于比较。 在第一个函数this.addUser我调用toLower变换它变成小写它没有问题但是在第二个函数this.checkPublicUsername我调用它,它在我的终端显示错误表示TypeError: Cannot call method 'toLowerCase' of undefined

function toLower (text) {
    return text.toLowerCase();
}

this.addUser = function(data,callback) {
    "use strict";
    // Generate password hash
    var salt = bcrypt.genSaltSync();
    var password_hash = bcrypt.hashSync(data.password, salt);
    // transform all character into lowercase
    var real = toLower(data.publicUsername);
    // Create user document
    var user = {
        '_id': data.email,
        'email':data.email,
        'password': password_hash,
        'name':{
            'firstName': data.firstName,
            'lastName': data.lastName
        },
        'penName': data.penName,
        'publicUsername':{
            'display':data.publicUsername,
            'real':real
        }
    };
    users.insert(user, function (err, result) {
        "use strict";

        if (!err) {
            console.log("Inserted new user");
            return callback(null, result[0]);
        }
        if (err) console.log(err)

        return callback(err, null);
    });
}

this.checkPublicUsername = function(data,callback) {
    "use strict";
    var real = toLower(data);
    var publicUsername = {
        "publicUsername.real":real
    }
    users.find(publicUsername).count(function(err, result) {
        callback(null,result);
    })

}

调用checkPublicUsername

 users.checkPublicUsername(data.publicUsername, function(err, result){
     if(result){
     callback(new Error('"'+data.publicUsername+'" has been taken. Please choose another.'), null);
             }
        });

2 个答案:

答案 0 :(得分:5)

您收到此错误是因为data.publicUsername未定义,请检查您传递给此函数的值。

答案 1 :(得分:2)

我收到此错误的原因是因为我尝试执行此功能时data.publicUsername未定义

this.checkPublicUsername = function(data,callback) {
    "use strict";
    var real = toLower(data);
    var publicUsername = {
        "publicUsername.real":real
    }
    users.find(publicUsername).count(function(err, result) {
        callback(null,result);
    })

}

real未定义导致错误,如果你想避免这个问题只是简单地写一个if else所以如果真的是未定义的那么就不要执行这个功能

 users.find(publicUsername).count(function(err, result) {
            callback(null,result);
        })

if else可能是这样的

 if(data != undefined){
            var real = toLower(data);
        }
希望这有帮助!