Yasya El Hakim
Yasya El Hakim

Reputation: 69

Best way to get Firestore sub-collections

I want to access and show the entire sub-collection data and successfully use nested foreach.

Here is the path I want to access: users/${id}/posts

Here is the code I use:

const collections = onSnapshot(query(colRef, orderBy('userLastSigned')), (coll) => {
    coll.docs.forEach((colls) => {
        const subsPostListsAlls = onSnapshot(query(collection(db, `users/${colls.id}/posts`), orderBy('createdAt', 'desc')), (query) => {
            query.docs.forEach((queries) => {
                ...

Is there a better way than the one I'm using?

Upvotes: 2

Views: 31

Answers (1)

BeEmil
BeEmil

Reputation: 61

This is how I use

replace: collection(db, users/${colls.id}/posts)

with: collectionGroup(db, 'posts')

You can read more about it here: https://firebase.google.com/docs/firestore/query-data/queries#collection-group-query

Upvotes: 2

Related Questions