-1

I'm trying to retrieve a firestore firebase subcollection.

With this code below everything is ok:

  await firestore()
    .collection('VILLES')
    .doc('9HNkAv99pd1rm9Q3vdwd')
    .collection('restaurents')
    .get()
    .then(querySnapshot => {
      querySnapshot.forEach(doc => {
        const {image, address, description, title, ratings, contact} =
          doc.data();

        list.push({
          id: doc.id,
          image: image,
          address: address,
          description: description,
          title: title,
          ratings: ratings,
          contact: contact,
        });
      });
    });
  setrestaurents(list);
  if (loading) {
    setloading(false);
  }
  console.log('restaurents:', restaurents);
} catch (e) {
  console.log(e);
}

But the problem is I have many documents which have a personal collection how can I write a code so that every document will retrieve his own subcollection, and I know the problem is around the document Id

I tried this

  await firestore()
    .collection('VILLES')
    .doc(VILLESId)
    .collection('restaurents')
    .get()

but I'm getting this error

Possible Unhandled Promise Rejection (id: 0):
TypeError: undefined is not an object (evaluating '_ref2.VILLESId')

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459

1 Answers1

0

If you want to retrieve all documents from all restaurents subcollections, you can use a collection group query like this:

  firestore()
    .collectionGroup('restaurents')
    .get()
    .then(querySnapshot => {
      querySnapshot.forEach(doc => {
        ...

This will take all documents from all restaurents collections.


If you need to know the VILLE document ID for a specific restaurent document in the above, you can get it with:

doc.ref.parent().parent().id
Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
  • IT IS NOT WHAT IM LOOKING FOR I HAVE A COLLECTION NAME TOWN AND THIS COLLECTION HAVE DOCCUMENTS LETS SAY WE HAVE 5 DOCUMENTS AND EVERY DOCUMENT HAVE A SUBCOLLECTION THE PROBLEM IS THAT WHEN I SELECT A SPECIFIC DOCUMENT I WILL LIKE TO RETREAVE THE SUBCOLLECTION BELONG TO THIS DOCUMENT IF I CAME BACK AND SELECT ANOTHER DOUMENT I WILL LIKE TO RETREAVE HIS OWN SUBCOLLECTION .TO TEST MY CODE I COPY ONE DOCUMENT ID AND PASS IT IT WORK FINE BUT IF I USE THIS CODE I CANT GET THE REST DOCUMENT OF THE FIRST COLLECTION THANKS FOR ANY HELP – Groupe Akoua May 25 '21 at 17:38
  • 1
    Please don't type in all-caps, as that reduces readability and is commonly perceived as yelling. – Frank van Puffelen May 25 '21 at 18:40
  • i'm very sorry i didn't know that.excuse me – Groupe Akoua May 25 '21 at 19:18
  • @GroupeAkoua please see [another thread](https://stackoverflow.com/questions/58456701/how-to-read-a-sub-collections-document-fields-from-firestore-in-react-native) where this question was answered. – Farid Shumbar May 26 '21 at 11:24