我会尽快尝试一下。我是初学者,并在node.js(express)中编写了这段代码。我只是想使用mongodb创建一个基本的'服务器'来存储用户名,密码和其他一些东西,以及node.js.我用猫鼬连接它。
我为大多数步骤添加了console.log(),以明确我的问题。结果是以下=> 1 2 3 4 5返回使用中的用户名r1:true 6 7 8 9 10 11 12
由于奇怪的模式,比较只是不起作用,因为它甚至在从数据库获取数据之前总是返回true。顺便说一句,回来的数据和比较完美,因为我已经通过重新安排代码测试了它。只是我要么无法添加新帐户,因为一切都是真的,或者我可以无限地添加相同的用户名,这不应该发生。
如果我不将它们放在单独的checkUsername()和checkEmail()函数中,它们就可以正常工作。我只是想让代码重用并且更容易阅读,但是我不明白的是阻止我。这种模式有这样的原因吗?它与Express或mongodb或mongoose有关吗?
有人可以向我解释一下代码的流程是什么吗?
var result = checkForDuplication(regUserName, regEmail);
//then it should come here as the 11th step
if(result == 0){ //ok code
var newUser = {"username": regUserName, "password": regPassword, "email": regEmail, "valid": false, "admin": false, "creation": dateOfCreation};
User.create(newUser, function(err, createUser){
if(err){
console.log(err);
}else{
res.redirect("back");
}
});
}else if(result == 1){
console.log("7 - should be 12");//depending on the outcome of the comparing, of course.
//used username
logOut(res);
}else if(result == 2){
console.log("7 - should be 12");
logOut(res);
//used email
}
function checkForDuplication(regUserName, regEmail){
var result1 = checkUsername(regUserName),
result2 = checkEmail(regEmail);
if(result1 == true){
console.log("returns username in use r1: " + result1);
console.log("6 - should be 10"); //and now that I have the booleans, it should come here to check and these should be 10th steps
return 1;
}else if(result2 == true){
console.log("returns email in use r2: " + result2);
console.log("6 - should be 10");
return 2;
}else{
console.log("returns ok r1: "+ result1 + " r2: "+ result2);
console.log("6 - should be 10");
return 0;
}
}
function checkUsername(regUserName){
console.log("2");
User.findOne({username: regUserName}, function(err, account){
console.log("8 - should be 3");
if(err)
console.log(err);
else{
if(account == undefined){
console.log("9 - should be 4");
return false;//this should be returned, but nothing of the sort happens, as if this was ignored because of the weird shifts...
}
return true;
}
});
console.log("3 - should be 5, though I shouldn't get here, actually, see return true above... ");
return true;
}
function checkEmail(regEmail){
console.log("4 - should be 5 after finisihing things in checkUsername()");
User.findOne({email: regEmail}, function(err, account){
console.log("10 - should be 6");
if(err)
console.log(err);
else{
console.log("11 - should be 7");
if(account == undefined){
console.log("12 - should be 8");
return false; //same as above
}
return true;//should return this if email already in the database
}
console.log("13 - this is left out, basically...");//it's okay because there are returns, but strangely enough, the compiler doesn't even warn me about it, even though I knew it wouldn't get here
});
console.log("5 - should be 9"); //only if for some strange reason return doesn't work... like it shouldn't even come here in the first place
return true;//should return this if email already in the database
}