javascript - 如何在 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);
})
})
但是,当任一条件为真时,这将导致不显示任何数据。这段代码有什么问题?
解决方案
借助 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)进行重复数据删除,该怎么做。(免责声明,我是文章的作者)
推荐阅读
- python - Kivy 标签文本不更新
- django - 无法从 Django 中的选择表单中获取值
- reactjs - 为什么表单数据不在 req.body 中?
- php - 为什么在没有任何条款的情况下尝试访问 taxonomy.php 页面时出现 404 错误,(Wordpress 看不到分类页面)
- regex - 使用正则表达式匹配子字符串
- youtube-data-api - 超出配额 - 从我的应用上传 YouTube 链接 - 在仪表板上看不到超出配额
- windows - 从长路径启动 win32 应用程序
- javascript - 在 mongoose 文档中检索对象的所有键
- r - 有没有办法根据一组字符串是否显示为较长字符串的一部分来过滤它们?
- reactjs - 如何使用 react-native-testing-library getByRole