Search code examples
firebasegoogle-cloud-firestore

Firestore realtime listener detect the type of change for a single doc only


I saw on the Firestore documentation for realtime listener that we can view changes between snapshots and see whether each document is added, removed or modified.

I am wondering if it is possible to see the type of changes if I am only attaching onSnapshot to a single document?

I tried to run the docChanges() method on the single doc listener:

    db.collection("matching").doc("user1").onSnapshot(async doc => {
        doc.docChanges().forEach(function(change) {
            if (change.type === "added") {
                console.log("added: " + change.doc.data());
            }
        })
    })

But it produced an error of :

Uncaught (in promise) TypeError: doc.docChanges is not a function

I think I simply cannot run docChanges() on a single doc listener. In that case, how to view changes for a single firestore doc realtime listener then?


Solution

  • No, the API will not indicate to you what data or fields changes between snapshots. You just get a callback every time something changed anywhere in the document. You have to compare the previous and current snapshot to figure that out for yourself.