首页 > 解决方案 > 如何在 JavaScript 中使用 OR 运算符从 Firestore 检索数据?

问题描述

我正在尝试使用以下代码从 Firestore 集合中读取数据:

auth.onAuthStateChanged(user => {
if(user) {
  console.log('User logged in:', user)

db.collection('MediCorePatientUsers').where("GPID", "==", user.email)
.get().then((snapshot) => {
    snapshot.docs.forEach(doc => {
        renderPatientList(doc);
        })
    })

document.getElementById("nameOfUser").innerHTML = user.email;

} else {
  console.log('User logged out');
}
});

这可以按预期工作并向我的网页显示正确的数据。但是,我想在代码中添加另一个条件,使用“或”运算符来显示字段“InsuranceCompany”也等于当前用户电子邮件的数据。

db.collection('MediCorePatientUsers').where("GPID", "==", user.email || "InsuranceCompany", "==", user.email)
.get().then((snapshot) => {
snapshot.docs.forEach(doc => {
    renderPatientList(doc);
    })
})

但是,当任一条件为真时,这将导致不显示任何数据。这段代码有什么问题?

标签: javascriptfirebasegoogle-cloud-firestore

解决方案


借助 Cloud Firestore,我们可以组合多种where()方法来创建逻辑AND查询。这些查询在文档中称为复合查询。

但是,如文档中所述(“<a href="https://firebase.google.com/docs/firestore/query-data/queries#query_limitations" rel="noreferrer">查询限制”部分):

Cloud Firestore 不支持以下类型的查询:

  • …</li>
  • 逻辑或查询。在这种情况下,您应该为每个 OR 条件创建一个单独的查询,并在您的应用程序中合并查询结果。
  • …</li>

为了实施文档中提出的解决方案,您可以执行以下操作:

  const usersRef = db.collection('MediCorePatientUsers');

  async function getMediCorePatientUsers(email) {
    const q1 = usersRef.where("GPID", "==", email).get();
    const q2 = usersRef.where("InsuranceCompany", "==", email).get();

    const [querySnapshot1, querySnapshot2] = await Promise.all([q1, q2]);

    const usersArray1 = querySnapshot1.docs;
    const usersArray2 = querySnapshot2.docs;

    return usersArray1.concat(usersArray2);
  }


  //You can then call the asynchronous getMediCorePatientUsers() function as follows
  auth.onAuthStateChanged(user => {
    if(user) {
       getMediCorePatientUsers(user.email).then(result => {
            result.forEach(docSnapshot => {
                renderPatientList(docSnapshot);
            });
       });
    } else {..}
  }

这种方法在下面的文章中有更详细的解释,特别是如果您需要对两个数组(usersArray1 和 usersArray2)进行重复数据删除,该怎么做。(免责声明,我是文章的作者)


推荐阅读