Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get sub-collections with Firebase firestore? [duplicate]

I am tying to get all the collections withing the withing the document, I don't know how to do it I am new to firestore.

Firebase.firestore()
      .collection("reservations")
      .doc(tripUid)
      .get()
      .then(doc => {
        console.log(doc.doc.data());
      }).catch(error => {
        console.log("Error getting document:", error);
      });

My Firebase firestore data

like image 563
Anes Abismail Avatar asked Apr 10 '19 20:04

Anes Abismail


2 Answers

So sub collections still follow the whole path idea of Firestore. So to give an example let's say you have a collection called 'Orders' with a sub collection called 'Products.' To get all the product documents of a specific Order you would write something like Firebase.firestore().collection("Orders/orderid123/Products").get() where orderid123 is the ID of the order you want the products for.

Looking at your data model, you have actually named the sub collection what appears to be a generated ID. So in the above example instead of using 'Products' you would instead be using 'ymuIjdv...'. You may want to revisit how you are naming this sub collection to give it a more human readable name. It looks like you are generating the ID for the sub collection document and using it as the name of the sub collection as well.

In your exact set up, what you are asking can be achieved by doing Firebase.firestore().collection("reservations/" + tripUid + "/ymuIjdvwWnOr20XWVp6gwRKtmgD2").get(). This will get all the sub collection documents under the reservation with an held within tripUid variable and within the collection 'ymuIjdvwWnOr20XWVp6gwRKtmgD2'.

like image 90
CuriousGeorge Avatar answered Jan 02 '23 09:01

CuriousGeorge


This is implementation for Firebase Admin SDK

Hope this will help

firestore()
    .collection("reservations")
    .doc(tripUid)
    .listCollections()
    .then((subCollections) => {
        subCollections.forEach((subCollection) => {
            subCollection
                .get()
                .then((array) => {
                    array.docs.forEach((doc) => {
                        console.log(doc.data());
                    });
                });
        });
    });
like image 35
Arpit Bhalla Avatar answered Jan 02 '23 11:01

Arpit Bhalla