0

由于某种原因,我无法在 node.js 中的 Web 请求期间多次查询 MongoDB。VERIFY BY USERNAME 和 VERIFY BY EMAIL 都可以单独工作,但不能连续工作。如果我注释掉任一代码部分,该函数将按需要工作。如果我将这两个部分都保留在其中,则在我的 Openshift 服务器上尝试运行请求时会收到 502 代理错误。当我将多个 Mongo 查询放入一个请求中时(不仅仅是在验证时),我实际上总是得到 502。有什么办法可以解决这个问题吗?我应该使用某种异步调用吗?

router.post('/login', function(req, res) {
  var db = req.db;
  userVerify(req, res);
  //VERIFY BY USERNAME
  db.collection('userlist').findOne({'username': req.body.username}, function (err, item){
      if(item.username == req.body.username)
      {
        if(passwordGen.verify(req.body.password, item.password)==true)
        {
          //res.render('logged_in.html', {});
          res.send( {msg: 'success'} )
        }
      }
    });
  //VERIFY BY EMAIL    
  db.collection('userlist').findOne({'email': req.body.username}, function (err, item){
    if(item.email == req.body.username)
    {
      if(passwordGen.verify(req.body.password, item.password)==true)
      {
        res.send( {msg: 'success'} );
      }
    }
  });
  //Return an error if the both failed.
  res.send( {msg: 'ERROR'} );
});
4

1 回答 1

0

我认为您的问题很重要,因为它展示了在 Node.js 下使用 MongoDB 的一个非常基本的方面。

您已经得到了@Neil 评论的答案。这些操作中的每一个都是异步的,不应并行运行它们。您当前的代码显示查询数据库的两个线程之间的竞争,第一个返回,第一个调用 res.send() 并完成响应。

所以你必须做的就是将它们嵌套在另一个中:等待数据库响应以验证密码,然后开始验证电子邮件,完成后 - 响应调用者

高温高压

于 2015-03-09T03:10:52.880 回答