0

So i've been researching about how do i get the subcollection of firebase documents. Basically its .get() but its not working now in 2022 I THINK. I have the code in below...

Let say this one I will create a subcollection path with the collections.

await setDoc(doc(db,list2[i],`${currentUser?.email}-${uid}`,`single_item`,`image`),{
    creator:username,name:name,img:downloadURL,email:currentUser?.email
})

await setDoc(doc(db,list2[i],`${currentUser?.email}-${uid}`,`group_item`,`images`),{
    creator:username,name:name,img:downloadURL,email:currentUser?.email
})

Now i'm getting all the items of firebase documents with these...

export const owneritemsRef = collection(db,'owner_items')
export const singleItemsRef = collection(db,'owner_items/single_item/image')
export const groupItemsRef = collection(db,'owner_items','group_item',`images`)

Now when I tried to read it in my react file...

  useEffect(() => {
    console.log(singleItemsRef)
    const unsubscribe = onSnapshot(singleItemsRef,snapshot => {
      console.log(snapshot)
      setSearchFilter(snapshot.docs.map((doc,idx) => {
        console.log(doc.data())
        return {
          ...doc.data(),
            name:doc.data().name
          }
      }))
      setSearchList(snapshot.docs.map((doc,idx) => {
        console.log(doc)
        return {
          ...doc.data(),
          name:doc.data().name
        }
      }))
    })
    return () => {
      unsubscribe()
    }
  },[])

It doesn't show anything...like it is completely null.. but I can see the pathsegments of singleRef... How do I get those documents please? The diagram is like this

owner-items -> (single/group) -> image/s -> { document items }

Dharmaraj
  • 47,845
  • 8
  • 52
  • 84
Myth Vince
  • 143
  • 9

1 Answers1

1

A collection group consists of all collections with the same ID and the subcollections live under a specific document. To access the subcollection you'll need to specify that particular ID in the path reference.
Using Collection Group Queries might be the easiest way to fetch all documents from collections with the same name which are passed in the collectionGroup() method. You need to use collection() to get a CollectionReference instead of doc() which returns a DocumentReference.

Also check these similar examples for Get Subcollection and fetching subcollection documents.

UPDATE

If you need to get that specific nested subcollection you could try something similar to below

db.collectionGroup("orders").get().then((querySnapshot) => {
  console.log(querySnapshot.docs.map(d => ({id: d.id, ...d.data()})))
})
Vaidehi Jamankar
  • 1,232
  • 1
  • 2
  • 10