M.El Yaakoubi
M.El Yaakoubi

Reputation: 181

Fetching documents of sub-collections in firestore

I'm trying to fetch sub-collection documents from my firestore database.

Collection Imgs: enter image description here enter image description here enter image description here

My current code:

const fetchHighlight =async()=>{
      
    const Highlight = []
    const HighlightDbId = await 
 db.collection('highlights').doc('2SCS2S0JnzngWEiYkHNk').collection('4C4kd2QnaQhcp9knexkW').get()
       console.log(HighlightDbId)
    }
    React.useEffect(()=>
    {
      fetchHighlight ()
     
    }, [])

Upvotes: 1

Views: 2436

Answers (2)

Alan Kersaudy
Alan Kersaudy

Reputation: 891

You forgot to fetch your query at the end of your chain, and the subcollection 4C4kd2QnaQhcp9knexkW does not exist, it's the id of a document in the subcollection you're trying to access. The right subcollection ID was hBYWvZ3KN3NLLrucTpryETQZnz2.
To sum up, you could go this way:

const yourDocument = (await db.collection('highlights').doc('2SCS2S0JnzngWEiYkHNk')
  .collection('hBYWvZ3KN3NLLrucTpryETQZnz2').doc('YOUR_DOC_ID').get()).data()

or this way:

const yourDocument = (await db.collection('highlights/2SCS2S0JnzngWEiYkHNk/hBYWvZ3KN3NLLrucTpryETQZnz2')
  .doc('YOUR_DOC_ID').get()).data()

Edit If you want to fetch only the first document of the subcollection you can go this way:


const yourDocument = (await db.collection('highlights').doc('2SCS2S0JnzngWEiYkHNk')
  .collection('hBYWvZ3KN3NLLrucTpryETQZnz2') // subcollection ref
  .orderBy("createdAt", "asc") // index
  .limit(1) // limit the size of your response
  .get()) // send the request and wait for it (you could also use '.then()' here)
  .docs[0] // get the first doc of the array
  .data() // retrieve the doc's data use `.id` instead if you want its id

And if you want to get the first subcollection of a doc you should go this way with the listCollections method:

const subcollectionId = (await db
  .doc('highlights/2SCS2S0JnzngWEiYkHNk')
  .listCollections())[0] // retrieve the first subcollection `.id`

Note that this only works with the node.js library, if you're attempting to do your query fore the front-end, it will fail. Then you should simply put a reference of your subcollection inside your parent doc by an update when creating your subcollection in the first place:

// const HighlightDbId = creating you subcollection
db.collection('highlights').doc('2SCS2S0JnzngWEiYkHNk').update({
  subcollection: HighlightDbId
});

And simply retrieve the field subcollection when you need to fetch data from its subcollection.

Upvotes: 3

M.El Yaakoubi
M.El Yaakoubi

Reputation: 181

I fixed this problem by adding the last doc :

 db.collection('highlights').doc('2SCS2S0JnzngWEiYkHNk').collection('4C4kd2QnaQhcp9knexkW').doc('XXXXXXXX').get()

Upvotes: -1

Related Questions