首页 > 解决方案 > 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 中创建新文档时触发此侦听器。

此外,如果我从侦听器查询中删除限制,代码可以工作,但我会花费大量不必要的读取。

标签: iosswiftfirebasegoogle-cloud-platformgoogle-cloud-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 浏览器中,系统就会自动为您创建索引。

代码应保持不变。


推荐阅读