Paula Ysabelle Medina
Paula Ysabelle Medina

Reputation: 562

How to access the sub-collection of a queried document in Firestore?

Context: Below is the screenshot of my collection and document in Firebase Firestore. Basically, every transaction document has its own field and a chat collection inside of it.

What I need: My goal is to query the document with a specific handler_id and to access the chat collection inside of it.

What's happening: This query only returns the transaction field

 db.collection("transaction").where("handler_id", "==", 3)

How can I include the chat collection in the queried document? Do you have any suggestion on how I can structure my data more efficiently? enter image description here

Upvotes: 4

Views: 1924

Answers (1)

Renaud Tarnec
Renaud Tarnec

Reputation: 83048

Queries in Firestore are shallow, meaning that when you query for documents via a query you only get the corresponding documents in the collection you are querying and not the documents from their sub-collections.

So you need to first query the parent transaction document (which is an asynchronous process), and when you get it, query the sub-collection (which is also an asynchronous process).

If we make the assumption that there is only one document in the transaction collection with handler_id = 3, you would do something along the following lines:

db.collection("transaction").where("handler_id", "==", 3).get()
.then(querySnapshot => {
   return querySnapshot.docs[0].ref.collection('chat').get();
})
.then(querySnapshot => {
    querySnapshot.forEach(doc => {
        // doc.data() is never undefined for query doc snapshots
        console.log(doc.id, " => ", doc.data());
    });
});

If you want to set up a listener to the chat subcollection, you just have to call the onSnapshot() method instead of the get() one, as follows:

db.collection("transaction").where("handler_id", "==", 3).get()
.then(querySnapshot => {
   querySnapshot.docs[0].ref.collection('chat').onSnapshot(querySnapshot => {
        // Do whatever you want with the querySnapshot
        // E.g. querySnapshot.forEach(doc => {...})
        // or querySnapshot.docChanges().forEach(change => {...})
        // See https://firebase.google.com/docs/firestore/query-data/listen#listen_to_multiple_documents_in_a_collection
    });
}); 

Upvotes: 8

Related Questions