Airlo
Airlo

Reputation: 111

How to get subcollection inside firestore using reactjs?

I tried doing db.collection("posts").collection("comments").get() and db.collection("posts/comments").get() but neither seemed to work.

Upvotes: 0

Views: 1253

Answers (2)

Lasitha Lakmal
Lasitha Lakmal

Reputation: 880

If you are using Web Modular API for like React or Next JS Try this

const querySnapshot = await getDocs(collection(db, "posts", "post_id", "comments"));
querySnapshot.forEach((doc) => {
  // doc.data() is never undefined for query doc snapshots
  console.log(doc.id, " => ", doc.data());
});

Documentation Link : https://firebase.google.com/docs/firestore/query-data/get-data#get_all_documents_in_a_subcollection

Upvotes: 0

Frank van Puffelen
Frank van Puffelen

Reputation: 598668

Subcollections live under a specific document. In order to access the comments subcollection of a specific post, you'll need to specify that post ID in the path:

db.collection("posts").doc("post ID you want").collection("comments").get()

If you want to access documents across all comments collections, you'll want to use a collection group query:

db.collectionGroup("comments").get()

Upvotes: 1

Related Questions