Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Firestore onSnapshot - how to tell which individual fields changed?

I’m modeling data and have a question about the onSnapshot (web) listener. As pointed out in a couple posts on SO and in the docs, after the initial invocation, the listener only fetches the changed data. I am interested to know what the changed data is. If listening on a document, is it just the field or the entire document that is fetched?

In a scenario where we have a listener on a Document, and the value of a field on that document changes (or a field is added, or removed), is only that field is fetched? In other words, is this similar to placing a child_changed/added/removed listener on a node in the RTDB?

The intent is to determine if I should keep frequently changing Documents, which clients must listen to, in RTDB or Firestore. I prefer not to resend the entire document to the client due to only a field change, if possible.

Example. We have the following document:

rando_id:
  field1
  field2
  field3

If field2's value changes, will only field2 be the transmitted data from Firestore DB to the client? The same would apply to adding a field4 or removing field1. Would just those fields be sent to the client?

like image 921
skwny Avatar asked May 31 '18 16:05

skwny


People also ask

What is snapshotChanges?

snapshotChanges() Metadata provides you the underyling DocumentReference , document id, and array index of the single document. Having the document's id around makes it easier to use data manipulation methods.

How do I get most recent documents on firestore?

Is there any way to get the last created document in Firebase Firestore collection? Yes, there is! The simplest way to achieve this is to add a date property to each object in your collection, then simply query it according to this new property descending and call limit(1) function. That's it!


1 Answers

The unit of storage in Firestore is the document. There are no more granular ways to transmit data. There is no API to tell what exactly has changed in a document - you would have to determine that yourself using a prior snapshot, if available. You also can't target document fields in security rules. With documents in Firestore, it's either all or nothing.

like image 86
Doug Stevenson Avatar answered Sep 30 '22 04:09

Doug Stevenson