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

huangapple go评论73阅读模式
英文:

How do I retrieve data from Firestore using an OR Operator in JavaScript?

问题

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

然而,当其中任何一个条件为真时,这导致数据都不显示。这段代码有什么问题?

英文:

I am attempting to read data from a Firestore collection using the following code:

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');
}
});

This works as intended and displays the correct data to my webpage. However, I would like to add another condition to the code, using an 'or' operator to display data where the field "InsuranceCompany" is also equal to the current user email.

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

However this is resulting in none of the data displaying when either of the conditions is true. What is incorrect with this code?

答案1

得分: 7

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

然而,正如文档中所示(第“查询限制”部分):

> Cloud Firestore不支持以下类型的查询:
>
> - …
> - 逻辑OR查询。在这种情况下,您应该为每个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);
}

//然后可以如下调用异步的getMediCorePatientUsers()函数
auth.onAuthStateChanged(user => {
  if (user) {
    getMediCorePatientUsers(user.email).then(result => {
      result.forEach(docSnapshot => {
        renderPatientList(docSnapshot);
      });
    });
  } else {...}
});

有关此方法的更多详细信息,请参阅以下文章,特别是如何处理如果需要去重两个数组(usersArray1和usersArray2)。 (免责声明,我是文章的作者)

英文:

With Cloud Firestore, we can combine multiple where() methods to create logical AND queries. These queries are called compound queries in the documentation.

However, as indicated in the documentation (Section “Query Limitations”):

> Cloud Firestore does not support the following types of queries:
>
> - …
> - Logical OR queries. In this case, you should create a separate query for each OR condition and merge the query results in your app.
> - …


In order to implement the solution proposed in the documentation, you can do as follows:

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

This approach is explained in more detail in the following article, in particular how to do if you need to de-duplicate the two arrays (usersArray1 and usersArray2). (disclaimer, I'm the author of the article)

答案2

得分: -3

你可以使用如下方式:

db.collection('MediCorePatientUsers').where("GPID == " + user.email + " || InsuranceCompany == " + user.email + "")

英文:

You can use as follows

> db.collection('MediCorePatientUsers').where("GPID == " + user.email +
> " || InsuranceCompany == " + user.email + "")

huangapple
  • 本文由 发表于 2020年1月6日 20:11:44
  • 转载请务必保留本文链接:https://go.coder-hub.com/59611888.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定