首页 > 解决方案 > 当firestore查询中不存在数据时无限搜索循环

问题描述

我正在使用 Node.js(express) + firestore 实现登录控件。我尝试使用搜索查询来检查id& 密码(pw)。

如果用户输入数据(来自 HTML <form>)在 firestore DB 中,客户端页面将重定向到/main. else将重定向回来。

当数据在firestore DB中时它可以工作,但是redirect当数据不在firestore DB中时,它不适用于无限循环并且没有。

我检查了数据(idpw)并进行了测试。但是当数据不在firestore DB中时,它总是会无限循环。

查看代码是这样的。

    <form action="" method="post">
      <input placeholder="ID" name="id" id="id" type="text">
      <input placeholder="PASSWORD" name="pw" id="password" type="password">
      <button type="submit">SIGN-IN</button>
    </form>
    <button onclick="location.href='/signup'">SIGN-UP</button>

服务器中的代码是这样的

var users_info = db.collection('users')
    .where('id', '==', req.body.id).where('pw', '==', sha256(req.body.pw))
    .get().then(snapshot => {
      snapshot.forEach(doc => {
        if (doc.exists) {
          req.session.user = {
            'id': doc.data().id,
            'name': doc.data().name,
            'auth': doc.data().auth,
            'is_guest': doc.data().is_guest
          }
          res.redirect('/main');
        } else {
          res.redirect('back');
        }
      });
    })
    .catch(err => {
      console.log(err);
      res.redirect('back');
    });

标签: node.jsgoogle-cloud-firestore

解决方案


我自己通过使用找到了解决方案snapshot.empty

var users_info = db.collection('users')
    .where('id', '==', req.body.id).where('pw', '==', sha256(req.body.pw))
    .get().then(snapshot => {
      if(snapshot.empty) {
        res.redirect('/');
      }
      else{
        snapshot.forEach(doc => {
          if (doc.exists) {
            req.session.user = {
              'id': doc.data().id,
              'name': doc.data().name,
              'auth': doc.data().auth,
              'is_guest': doc.data().is_guest
            }
            res.redirect('/main');
          } else {
            res.redirect('/');
          }
        });
      }

    })
    .catch(err => {
      console.log(err);
      res.redirect('/');
    });

推荐阅读