Node.js(express,mongodb)注册过程

你好,Stackoverflow社区,我是新的Node.js /快递,我需要你的帮助,因为我卡住了一些问题。

我试图做一个注册过程中,后input保存到一个mongodb。 之前我想validation,如果用户的电子邮件地址已经存在于数据库中。

如果我尝试在db.users.find()语句中定义一个var应用程序将无法正常工作。

app.post("/sign-up", function(req, res){ var validate; db.users.find({email : req.body.email}, function(err, users) { if( err || !users){ validate = true; }else{ validate = false; } }); console.log(validate); if(validate == true){ db.users.save({ title: req.body.title, firstname: req.body.firstname, surname: req.body.surname, country : req.body.country, email: req.body.email, password: bcrypt.hashSync(req.body.password, 10) }, function(err, saved) { if( err || !saved ) console.log("User not saved"); else console.log("User saved"); res.location("sign-up-success"); // And forward to success page res.redirect("sign-up-success"); }); } }); 

如何db.users.find()函数需要看起来像我可以做/如果请求db.users.save()函数。

       

网上收集的解决方案 "Node.js(express,mongodb)注册过程"

问题是db.users.find是一个asynchronous函数。 我会build议如下:

 app.post("/sign-up", function(req, res){ var validateUser = function(callback) { db.users.find({email : req.body.email}, function(err, users) { if( err || !users){ callback(true); } else { callback(false); } }); } validateUser(function(isValid) { if(isValid == true){ db.users.save({ title: req.body.title, firstname: req.body.firstname, surname: req.body.surname, country : req.body.country, email: req.body.email, password: bcrypt.hashSync(req.body.password, 10) }, function(err, saved) { if( err || !saved ) console.log("User not saved"); else console.log("User saved"); res.location("sign-up-success"); // And forward to success page res.redirect("sign-up-success"); }); } }) }); 

这是asynchronous的问题,你可以移动一些代码到你的查找callback像这样:

  app.post("/sign-up", function(req, res){ var validate; db.users.find({email : req.body.email}, function(err, users) { if( err || !users){ validate = true; }else{ validate = false; } // your code should be here: console.log(validate); if(validate == true){ .... } }); // This code will print undefined, so you must move to the callback // console.log(validate) // because the callback was not call yet