如何使用JavaScript中的OR运算符从Firestore检索数据?

问题描述 投票:0回答:2

我正在尝试使用以下代码从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);
    })
})

但是,当任一条件为真时,则不会显示任何数据。此代码有什么不对?

javascript firebase google-cloud-firestore
2个回答
1
投票

使用Cloud Firestore,我们可以组合多个where()方法来创建逻辑AND查询。这些查询在文档中称为compound queries

但是,如文档所述(“ Query Limitations”部分:]:

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

  • 逻辑或查询。在这种情况下,您应该为每个OR条件创建一个单独的查询,并将查询结果合并到您的应用中。

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

  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 {..}
  }

article中将详细解释此方法,特别是如果需要对两个数组(usersArray1和usersArray2)进行重复数据删除,该如何做。 (免责声明,我是本文的作者)


0
投票

您可以如下使用

db.collection('MediCorePatientUsers')。where(“ GPID ==” + user.email +“ || InsuranceCompany ==” + user.email +“”)

© www.soinside.com 2019 - 2024. All rights reserved.