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
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.
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.
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.
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.
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.
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