我有一个 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”。
为了能够进行这样的查询,您必须创建一个 index对于它,否则,它不会返回任何结果。您可以在 Firebase Console 中手动创建所需的索引:
或者您会在 IDE 中找到如下所示的消息:
FAILED_PRECONDITION: The query requires an index. You can create it here: ...
您只需单击该链接或将 URL 复制并粘贴到网络浏览器中,系统就会自动为您创建索引。
代码应该保持不变。
关于ios - Firestore 查询在创建新文档时未收到更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69308228/