I\'ve noticed, when I try to use a realtime listener on a Collection in firestore, each time a new Document is added to the collection, the logic will be rerun, and I will d
You can get the new document that caused this callback
for change in changes:
if change.type.name == 'ADDED':
print(f'New document: {change.document.id}')
It seems that the onSnapshot
is only for listening an entire document,which means it would return all of the fields in a document that you're listening. So you are not able to only retrieve the changed field.
But you can do different things according to different types of change:
xxxx.onSnapshot(function(querySnapshot){
querySnapshot.docChanges.forEach(function(change){
if(change.type=="added"){//first time it will be triggered
}else if(change.type == "modified"){//modified
}else if(change.type == "removed"){//removed
}
})
})
Hope this helps
When you use onSnapshot() on a collection, you're not actually downloading the entire collection on each invocation. The documents are cached and will be reused when the collection changes again.
For each change that causes your callback to be invoked, you can find out which documents are new seen since the first invocation by checking the changes within the snapshot. An example of how to do this is in the documentation. With a query snapshot in hand, you can use this logic to determine which documents are new:
snapshot.docChanges.forEach(function(change) {
if (change.type === "added") {
// change.doc here is new a new document
}
});
The documents are cached and hence they are not completly downloaded. But if the complete data is bigger than cache size, it might be ree downloaded. The best strategy is to enable cache storage to disk and then using limitToLast(1).
firebase.firestore().collection("Tweets")
.orderBy("key1")
.limitToLast(1)
.onSnapshot(function(querySnapshot) {
querySnapshot.forEach(function(doc) {
console.log("snapshot added ", doc)
});
});
in this key1 could be the tweet id.
This will leverage automatic single property index and will only fetch the last record. if persistence is enabled, this fetch will be from the cache.
Multiple answers above have talked about how to figure about if this data is new or stale.