Is it possible to only retrieve the newest document with a QuerySnapshot in Firestore?

时间:2019-03-17 22:56:04

标签: firebase flutter google-cloud-firestore snapshot

I have a question regarding QuerySnapshot. For example, lets say I have a chat app. To keep the discussion updated I use a StreamBuilder connected to Firestore. I use a querySnapshot to retrieve all the documents in the collection "messages" and every time I add a message a new Query Snapshot is triggered with the new message and all the previous documents. So here is my question, If my collection "messages" contain 10 documents, the first time I have to get all document so I read 10 documents. Next I add a messag, I now have 11 documents in my collection and the querySnapshot will then return the 11 documents even if I only need the new one. So in the end, will it count as 11 documents read (10 + the new one ) or 21 (10 +11 ) ? If it is the lattest, is there a way to only get the new document instead of all the documents ?

Thanks in advance.

2 个答案:

答案 0 :(得分:1)

这取决于您是否设置了侦听器.addSnapshotListener还是刚刚使用了.getdocument。如果您设置了侦听器,它将仅从Firestore中读取新文档或更改过的文档,然后将其与本地缓存的数据合并。然后,它将再次向您的应用显示完整的11个文档。从本地缓存10,新加载1。您确实可以选择仅获取更改,请参见下文。如果您未设置侦听器,则可以使用.addSnapshotListener更改.getdocument,其余代码应相同。但是,当不再需要侦听器时,请不要忘记分离它。

db.collection("cities").whereField("state", isEqualTo: "CA")
.addSnapshotListener { querySnapshot, error in
    guard let snapshot = querySnapshot else {
        print("Error fetching snapshots: \(error!)")
        return
    }
    snapshot.documentChanges.forEach { diff in
        if (diff.type == .added) {
            print("New city: \(diff.document.data())")
        }
        if (diff.type == .modified) {
            print("Modified city: \(diff.document.data())")
        }
        if (diff.type == .removed) {
            print("Removed city: \(diff.document.data())")
        }
    }
}

答案 1 :(得分:0)

只要将侦听器附加到查询,只要文档不变,就不会从服务器重新读取任何文档。每次更改都会将侦听器传递给整个集合,但是如果不更改,则将从内存中传递它们。每次回调只获得更改,甚至每次check to see exactly what changed都可以。