更新索引值时,Firestore addSnapshotListener无法监听文档上的更新

时间:2020-04-14 20:53:11

标签: ios swift firebase google-cloud-firestore

我不确定在Swift的Firebase中是否正确执行了此操作。 假设我将一些日期存储在一个名为“ temp”的集合中,并且我正在尝试听文档上的任何更新。每个文档都有几个字段。例如,一个字段是userId,另一个字段是updateTs。为了查询最新文档,我的监听器就是这样

messageListener = Firestore.firestore().collection("temp")
                .whereField("userId", isEqualTo: "\(userId)")
                .whereField("updateTs", isLessThan: lastUpdateTs)
                .order(by: "updateTs", descending: true)
                .limit(to: 20)
                .addSnapshotListener { querySnapshot, error in
                    guard let snapshot = querySnapshot else {
                        return
                    }
                    for i in 0..<snapshot.documentChanges.count {
                        var change = snapshot.documentChanges[i]
                        // do things herer
                        if (change.type == .added) { print("added") }
                        if (change.type == .removed) { print("removed") }
                        if (change.type == .modified) { print("modified") }
                    }
                }

由于我同时使用whereField和order进行查询,因此我必须创建一个复合索引(userId + updateTs)。

一切都很好,但是在我使用userp字段未更改的情况下尝试更新updateTs字段上的值时,

let messageData: [String: Any] = ["userId": userId, "updateTs": updateTs]
Firestore.firestore().collection("temp").document(thisDocument).updateData(messageData)

上述侦听器将上述更改标识为removed而不是modified,并且在侦听器第一次观察到更改后,将不再能够观察到更改(可能是由于被标识为removed

我的假设是这是因为我正在更新索引的值,从而导致了此问题。在这种情况下,有什么解决方法吗?感谢您的帮助

1 个答案:

答案 0 :(得分:1)

您在文档上设置的updateTs的值是什么?

我的猜测是您将updateTs设置为大于lastUpdateTs的va值。在这种情况下,更新后的文档将不再与您的查询匹配,并且会从查询结果中被删除。因此,这意味着change.type.removed,因为该文档已从查询结果中删除。