I have created a simple app using flutter and firebase firestore database. There are 'users' collections and each user has 'posts' collections. Each post may have one or more posts added by different users. I am trying to get all the posts regardless of users. However, my current function was written for reading records only shows the posts relevant for login user, not all the posts.
Stream<QuerySnapshot> readItems({required String collectionName}) {
CollectionReference detailCollection = _firestore
.collection(mainCollectionName!)
.doc(userUid)
.collection(collectionName);
return detailCollection.snapshots();
}
Here, I pass 'users','login user's uid' and 'posts' as mainCollectionName, userUid and collectionName respectively. Can anybody guide me how do I get all the posts regardless of users?
CodePudding user response:
It is possible to get all sub collections data from all the documents in a collection. Try this way
_firestore
.collection(`${mainCollectionName}/*/${collectionName}`)
.get()
Refer to this page for more details about querying collections and sub collections - https://firebase.googleblog.com/2019/06/understanding-collection-group-queries.html
CodePudding user response:
After searching I found a solution here. The following method gives the desired output.
Stream<QuerySnapshot> readItems({required String collectionName}) {
Query<Map<String, dynamic>> detailCollection = _firestore.collectionGroup(collectionName);
return detailCollection.snapshots();
}