【问题标题】:Firestore wont retrieve my data when I use where当我使用 where 时,Firestore 不会检索我的数据
【发布时间】:2020-06-01 23:03:55
【问题描述】:

我正在尝试使用 where 从我的数据库中检索数据。用户输入他们想要邀请的电子邮件,然后发送邀请。但是没有文件被退回。这是我用来检索的代码:

await props.firestore
    .collection("users")
    .where("email", "==", state.inviteEmail)
    .get()
    .then((doc) => {
      if (!doc.exists) {
        props.showMsg(
          "No user with that email exists. Make sure you've entered it correctly"
        );
      } else {
        // This is where it goes if it works
        alert("It works");
      }
    });

我尝试将 where 替换为 .doc(any id) 并且它可以正常工作,因此我知道数据库已正确连接。这是数据库的视图:

我使用的是 Reactjs,而数据库使用的是 Firebase

编辑:对于其他有同样问题的人,这是我所做的更改:

await props.firestore
    .collection("users")
    .where("email", "==", state.inviteEmail)
    .get()
    .then((doc) => {
      if (doc.empty) {
        props.showMsg(
          "No user with that email exists. Make sure you've entered it correctly"
        );
      } else {
        alert("This emails username: "+doc.docs[0].data().username);
      }
    });

数据以 QuerySnapshot 的形式返回,类似于数组,因此它需要是 doc.docs[0].data 而不是 doc.Data()。因为我只有一个保证返回的文档,所以我只抓取了第一个元素,但如果我有多个元素,我将不得不使用 foreach。

【问题讨论】:

  • 我只在标题中添加了“解决”这个词,因为我在其他问题上看到了它。我还包括了我的问题的解决方案,因为我觉得解释为什么我首先遇到这个问题很有帮助。每当我在这个网站上遇到问题时,不得不通过多个链接来弄清楚他们如何解决他们的问题可能会令人沮丧,所以我觉得如果我把解决方案放到我的网站上,它可能会在未来更有效地帮助其他人。我不知道堆栈溢出有这样的规则
  • 没关系。这就是为什么我解释了什么和为什么。有关此主题的一些讨论,您可能会发现更可信:meta.stackexchange.com/questions/31809/…
  • 哦,我明白了,我明白你的意思。 Tbh 我没有意识到我可以就自己的问题发布答案

标签: node.js reactjs firebase google-cloud-firestore


【解决方案1】:

当您添加where 子句时,您实际上得到的是QuerySnapshot 对象而不是DocumentSnapshot。所以你的代码中的问题是QuerySnapshot 对象没有exists 字段作为DocumentSnapshot 对象。因此,在这种情况下,doc.exists 将始终等于 undefined,并且 if 语句的计算结果始终为 true。

您可以将 if 条件转换为查找 empty 属性,因此代码将如下所示:

firestore
.collection("users")
.where("email", "==", state.inviteEmail)
.get()
.then((snap) => {
  if (snap.empty) {
    props.showMsg(
      "No user with that email exists. Make sure you've entered it correctly"
    );
  } else {
    // This is where it goes if it works
    alert("It works");
  }
});

【讨论】:

  • 我之前尝试过,但我不断收到“doc.data 不是函数”,这意味着它无法抓取任何东西。我已经替换了警告说它与 props.showMsg("Email's username: " + doc.data().username);
  • @Lonstu 这是因为QuerySnapshot 对象没有data 函数。正如我之前提到的,您将 QuerySnapshotDocumentSnapshot 对象混淆了。尝试将QuerySnapshot 视为DocumentSnapshot 与其他一些属性和方法的集合,例如用于迭代的forEach 和保存返回文档数量的size。为了更好地理解,请在QuerySnapshot上通过firestore的official documentation
  • 谢谢。我没有意识到返回的是 QuerySnapshot 并且它被视为一个数组。我使用了 doc.docs[0].data().username 并且它有效。再次感谢您!
猜你喜欢
  • 2018-09-22
  • 1970-01-01
  • 1970-01-01
  • 2020-05-16
  • 1970-01-01
  • 2020-08-27
  • 1970-01-01
  • 2021-11-19
  • 2021-09-15
相关资源
最近更新 更多