我是Node.JS和MongoDB的初学者。我想做注册过程。现在我正在检查演示代码而不使用express.js我的任务是如果用户在db中我应该显示“你是存在用户转到登录页面“,如果用户是db新手,我应该在db中插入数据。我应该显示“欢迎你是新用户”在这段代码中所有内容都完美执行但是邮件不打印atlast是问题。任何人都可以解决这个问题吗?在此先感谢..
var mongodb=require("mongodb");
var mongoclient=mongodb.MongoClient;
var url="mongodb://localhost:27017/check";
var username="V.V vinayak";
var userpass="655vhwhww";
var usergmail="vvvinayak123@gmail.com";
var message="";
mongoclient.connect(url,function(err,db)
{
if(err)
{
console.log("check db is not connected");
console.log(err);
}
else
{
console.log("check db is connected");
var collection=db.collection("achocho");
collection.findOne({"name":username},function(err,result)
{
if(err)
{
console.log(err);
}
else if(result)
{
message="You are exist user go to login Page";
}
else
{
collection.insertOne({"name":username,"gmail":usergmail,"password":userpass},function(err,result)
{
if(err)
{
console.log(err);
}
else
{
console.log("Data inserted successfully"); //This message is also displayed correctly for me...
message="welcome you are new user";
}
});
}
});
}
console.log(message); // This message is not printed that is the problem.I should display the message here
});
答案 0 :(得分:0)
节点js本质上是异步的,因此您需要仔细编写下一个执行步骤 请在下面找到更新的代码:
var mongodb=require("mongodb");
var mongoclient=mongodb.MongoClient;
var url="mongodb://localhost:27017/check";
var username="V.V vinayak";
var userpass="655vhwhww";
var usergmail="vvvinayak123@gmail.com";
var message="";
mongoclient.connect(url,function(err,db)
{
if(err)
{
console.log("check db is not connected");
console.log(err);
}
else
{
console.log("check db is connected");
var collection=db.collection("achocho");
collection.findOne({"name":username},function(err,result)
{
if(err)
{
console.log(err);
}
else if(result)
{
message="You are exist user go to login Page";
printMsg(message);
}
else
{
collection.insertOne({"name":username,"gmail":usergmail,"password":userpass},function(err,result)
{
if(err)
{
console.log(err);
}
else
{
console.log("Data inserted successfully"); //This message is also displayed correctly for me...
message="welcome you are new user";
printMsg(message);
}
});
}
});
}
});
printMsg(message) {
console.log(message);
}