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 download everything already in the collection
right now:
firebase.firestore().collection("Tweets").onSnapshot(function(querySnapshot) {
querySnapshot.forEach(function(doc) {
console.log("snapshot added ", doc)
});
});
Is there a way to track only ADDITIONS to the collection? I guess I could do that device side, but theres no need to transfer all the additional data I have already queryed for..
Output of that log would print out every single "tweet" in the collection, regardless of only one being added
EX: Initial Query
-Tweet 1
-Tweet 2
-Tweet 3
New Tweet, Tweet 4 is added
Output:
Tweet 1
Tweet 2
Tweet 3
Tweet 4
If that makes sense
There are two ways to retrieve data stored in Cloud Firestore. Either of these methods can be used with documents, collections of documents, or the results of queries: Call a method to get the data. Set a listener to receive data-change events.
The best way to prevent duplicate nodes in firebase realtime database or duplicate documents in firebase firestore database is to keep a check in the app itself to verify that the record to be inserted doesn't already exist in the database by querying for data using key field in where clause.
Set the event handler Functions let you handle Realtime Database events at two levels of specificity; you can listen for specifically for only creation, update, or deletion events, or you can listen for any change of any kind to a path.
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
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With