Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Firestore listener for sub collections

I have my Firestore setup in the following way:

Channels [collection] ----> channelID ---> Messages [collection] ---> messageID

How would I add snapshotListener to sub collection 'Messages' ?

  Firestore.firestore().collection("Channels").document().collection("Messages").addSnapshotListener { (querySnapshot, error) in
        guard let snapshot = querySnapshot else {
            print("Error listening for channel updates: \(error?.localizedDescription ?? "No error")")
            return
        }

        snapshot.documentChanges.forEach { change in 
           print(change)
        }
    }

This didn't work for me

like image 215
OuSS Avatar asked Nov 09 '18 14:11

OuSS


People also ask

What is sub collection firestore?

A subcollection is a collection associated with a specific document. Note: You can query across subcollections with the same collection ID by using Collection Group Queries.

How do you query collections in firestore under a certain path?

There is no way to get documents from different collections or sub-collections in a single query. Firestore doesn't support queries across different collections in one go unless we are using a collection group query.

What is snapshot listener?

Listeners and Snapshots In our case, whenever changes in that node's data occur, the listener automatically provides the application updated data, called a snapshot. The application can then use information from the snapshot to update the UI.

How do I update sub collection in firestore?

You just need to get a reference to the subcollection, which you get from the DocumentReference . And on that you simply use the regular method for writing data again: firebase.google.com/docs/firestore/manage-data/add-data. If you're having a hard time making this work, update your question to show what you've tried.


1 Answers

You can't have a single listener receive updates from an unknown number of subcollection. There are no "wildcard" operators for listeners on collections. You have to choose a specific collection or query and attach a listener to that.

like image 167
Doug Stevenson Avatar answered Nov 03 '22 01:11

Doug Stevenson