ios - Firestore 查询在创建新文档时未收到更新
问题描述
我有一个 Firestore 查询,我需要它来收听新文档的创建,我尝试了很多可能性但无法使其工作,每次创建文档时都不会触发监听器。这是我的监听器代码:
firestore
.collection("users")
.document("123")
.collection("images")
.whereField("postId", isEqualTo: "123")
.order(by: "createdAt", descending: true)
.limit(to: 1)
.addSnapshotListener { [weak self] snapshot, error in
guard let imageDocument = snapshot?.documents.first else {
return
}
// this print statement is only being called once (not being called when creating a new doc)
print(imageDocument)
}
...
这是我创建文档的查询:
firestore
.collection("users")
.document("123")
.collection("images")
.document()
.setData([
"postId": "123",
"imageUrl": "....",
"createdAt": Timestamp()
]) { error in
guard let error = error else { return }
print(error)
}
我的目标是当我在 Firestore 中创建新文档时触发此侦听器。
此外,如果我从侦听器查询中删除限制,代码可以工作,但我会花费大量不必要的读取。
解决方案
问题不在于您将数据添加到 Firestore 的方式,而在于您如何阅读它。也没有与“limit(to: 1)”调用相关的内容。当您执行以下查询时:
firestore
.collection("users")
.document("123")
.collection("images")
.whereField("postId", isEqualTo: "123")
.order(by: "createdAt", descending: true)
.limit(to: 1)
这意味着您要从“images”子集合中获取所有文档,其中“postId”字段的值为“123”,然后根据“createdAt”字段的降序和限制对结果进行排序结果为“1”。
为了能够使这样的查询工作,你必须为它创建一个索引,否则它不会返回任何结果。您可以在Firebase 控制台中手动创建所需的索引:
或者您会在 IDE 中找到如下所示的消息:
FAILED_PRECONDITION: The query requires an index. You can create it here: ...
您只需单击该链接或将 URL 复制并粘贴到 Web 浏览器中,系统就会自动为您创建索引。
代码应保持不变。
推荐阅读
- interop - 有什么东西阻碍了现代语言和 COBOL 之间的互操作性吗?
- microsoft-teams - 团队 - 图形 API - 无法使用已定义的组织者/指定频道创建活动
- javascript - 如何在 time-phaser3 创建一枚硬币
- vba - 如果字段和记录号已知,则获取值?
- python - 如何对我的 Dataframe 执行特定操作?
- spring-boot - 无法访问在 MacO 上的容器内运行的 springboot 应用程序
- vba - 带有事件的 VBA 文本框数组
- perl - 为什么 perl 脚本从 YouTube 服务器获得“429 Too many requests”,而 Web 浏览器可以正常加载网页
- php - PHP/OCI - 无法从临时表中的 Oracle 过程中获取结果
- sql-server - 如何从我有没有父母的孩子的表格贸易代码中删除?