首页 > 解决方案 > 在firebase查询后没有运行else语句

问题描述

我有一个一直在使用 firebase 的网络应用程序,但最近遇到了障碍。我正在尝试查询集合的内容,然后根据查询是否成功命中进一步运行一些代码。

这是我当前的代码:

            store
            .collection("users")
            .where("email", "==", email)
            .get()
            .then((docs) => {
                docs.forEach((doc) => {
                    if (doc.exists) {
                        console.log("it exists");
                    } else {
                        console.log("it doesnt exist");
                    }
                });
            })
            .catch((err) => {
                console.log(err.message);
            });

我遇到的问题是:当集合中存在带有电子邮件的文档时,它将适当的字符串记录到控制台。但是,当它不存在时,它会完全跳过那里的 else 语句,并且根本不会记录任何内容。

我知道这可能只是我忽略的一个错误。有没有更好的方法来使用firebase执行这样的检查?

提前致谢。

标签: javascriptfirebasegoogle-cloud-firestore

解决方案


您将永远不会到达 else 块,因为您正在检查集合循环中的现有文档,该文档只有有效文档。您应该检查返回集合的大小是否大于 0。

最终的代码将是这样的:

store
        .collection("users")
        .where("email", "==", email)
        .get()
        .then((docs) => {
          if (docs.size > 0) {
            docs.forEach((doc) => {
                // doc.exists is not necessary
                console.log("it exists");
            });
          } else {
            console.log("it doesnt exist");
          }
        })
        .catch((err) => {
            console.log(err.message);
        });

推荐阅读