Home > database >  Accessing the collection inside a document of a parent collection in firestore
Accessing the collection inside a document of a parent collection in firestore

Time:11-29

I am looking to fetch the data of collection named users which has documents with an id of logged-in users' uid. Further, these documents contain some data and a subCollection called posts. which looks like -

database structure

So now, I need to fetch all four(4) of these documents along with the posts collection data together so that I can display it.

My approach - ( here I fetched the document ids - middle section of image IDs)

// Fetching Firestore Users Document IDs

const [userDocs, setUserDocs] = React.useState([]);

  React.useEffect(() => {
    try {
      const data = firestore.collection('users')
        .onSnapshot(snap => {
          let docIDs = [];
          snap.forEach(doc => {
            docIDs.push({id: doc.id});
          });
          setUserDocs(docIDs);
        })
    }
    catch(err) {
        console.log(err);
    }
  }, [])

Now, I have tried to fetch the entire data using the following way (which isn't working)

// Fetching Firestore Posts Data

const [postData, setPostData] = useState([]);
  React.useEffect(() => {
      try {
        userDocs.map(data => {
          const data = firestore.collection('users/' currentUser.uid '/posts')
          .onSnapshot(snap => {
            let documents = [];
            snap.forEach(doc => {
              documents.push({...doc.data(), id: doc.id});
            });
            setPostData(documents);
          })
        })
      }  
      catch(err) {
          console.log(err);
      }
    }, [])

Finally, I should end up with postData array which I can map on my card component to render all posted images and captions to the UI.

I am not sure if this is the right way to achieve what I am doing here, please help me correct this error and if there's a more subtle and easy way to do it please let me know. Thank You.

CodePudding user response:

I have tried to fetch the entire data

Looking at the code you wrote for fetching "the entire data" (i.e. the second snippet) it seems that you don't need to link a post document to the parent user document when fetching the post documents. In other words, I understand that you want to fetch all the posts collection independently of the user documents.

Therefore you could use a Collection Group query.


If you need, for each post document returned by the Collection Group query, to get the parent user doc (for example to display the author name) you can do as explained in this SO answer, i.e. using the parent properties.

  • Related