firebase - Firebase Firestore 中的嵌套查询
问题描述
我有一个这样的 Firestore 数据库结构:(文章是一个集合,里面的一切都是数组)
Articles:
[
{
"id": 1,
"reports": [
{
"locations": [
{
"location": "Sydney",
"country": "Australia"
},
{
"location": "Perth",
"country": "Australia"
}
],
},
{
"locations": [
{
"location": "King County, Washington",
"country": "USA"
}
],
}
]
},
{
"id": 2,
"reports": [
{
"locations": [
{
"location": "Brisbane",
"country": "Australia"
}
]
}
]
}
]
我想创建一个查询以返回所有提及特定国家的文章。我最好重组我的数据库吗?
解决方案
虽然 Firestore 的array-contains
查询可以让您接近这一点,但您不能在当前数据模型中使用它们,因为您正在嵌套数组。
为了允许用例,您至少需要将其中一个数组取消嵌套到每篇文章的子集合中,因此:
Articles (collection)
$article
reports (collection)
$report (document with a locations array)
此时您可以使用集合组查询来搜索所有reports
集合,然后array-contains
找到相关的报告文档:
var ref = firebase.firestore().collectionGroup("reports");
ref.where("locations", "array-contains", { location: "Sydney", country: "Australia" })
别介意下面的答案,假设你只有一层数组......
据我所知,使用运算符应该可以进行这种类型的查询array-contains
。请记住,您需要指定整个数组项。
所以像:
collectionRef.where("reports.locations", "array-contains",
{ location: "Sydney", country: "Australia" })
推荐阅读
- html - 如何以角度更改列表框中第一个元素的颜色?
- c# - 为什么在 xaml 中绑定 ItemsSource 时 ui 更新但在代码中分配它时不更新?
- facebook - facebook 服务器发送实时视频评论事件,仅提供视频所有者评论
- java - ConstraintValidation 不适用于 Rest Api 请求
- javascript - 在回发时我不想改变表单的视觉效果?
- ios - 为 Pushkit 分配 PKPushRegistryDelegate 时如何消除类型错误?
- php - 如何更改php代码以在每个输入框下显示错误
- javascript - 在 JEST 测试中隐藏控制台日志
- angularjs - 如何在 twilio-video 中添加额外的轨道?
- angular - Angular 中状态为 302 时读取响应头