15

I am trying to get the documents inside an subcollection which is part of an document found with the .where function

Example:

  • RootColl/
  • Doc A/
    • SubColl 1
      • Doc 1
      • Doc 2
      • Doc 3
    • SubColl 2
      • Docs
  • Doc A/
    • SubColl 1
      • Doc 1
      • Doc 2
      • Doc 3
    • SubColl 2
      • Docs

I want to get all the documents under SubColl 1 from the doc with the field level == 1

I am trying to do it like:

db.collection("RootColl").where("field", "==", "1").collection("SubColl 1").get()

But by doing that I get the error

Uncaught TypeError: db.collection(...).where(...).collection is not a function

EDIT 1: By following Frank van Puffelen suggestion, i get the same error, "collection" is not a function

Nimantha
  • 6,405
  • 6
  • 28
  • 69
dragon blade
  • 155
  • 1
  • 1
  • 7

2 Answers2

35

A sub-collection lives under a specific document. A query as you've shared now points to a number of documents. You'll need to execute the query to determine what documents it points to, then loop over the results, and get the sub-collection for each document.

In code:

var query = db.collection("RootColl").where("field", "==", "1");
query.get().then((querySnapshot) => {
  querySnapshot.forEach((document) => {
    document.ref.collection("SubColl 1").get().then((querySnapshot) => {
      ...
    });
  });
});
Ali Abbas
  • 4,247
  • 1
  • 22
  • 40
Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
  • 3
    i get the same error: `document.collection is not a function` – dragon blade Dec 04 '17 at 15:12
  • 1
    same `document.collection is not a function` – alexndm Jan 23 '18 at 04:45
  • 1
    Thanks for catching that mistake. you'll need to get the `ref` from the `document` to get at the subcollection. I fixed the code in my answer. – Frank van Puffelen Jan 23 '18 at 05:08
  • 12
    Thanks @FrankvanPuffelen, are there any plans to write a guide or documentation how to work with subcollections on the web? The current documentation just states "subcollections are not supported on the web". – alexndm Jan 23 '18 at 19:33
1

If you have multiple document in main collection and then sub collection, then use this code:

Data structure: users(collection)-->>user1(doc)-->group(collection)-->data(doc) users(collection)-->>user2(doc)-->group(collection)-->data(doc)

const mainRef = collection(db, "users"); //users is my main collection, containing all the users 
const users = await getDocs(mainRef); //Getting all the users
users.forEach(async (user) => { // loop through each user so that we got id for each document(user) to get sub collection data
  let userCollectionRef = collection(db, `users/${user.id}/groups`); //groups is my sub-collection name
  const GroupDoc = await getDocs(userCollectionRef); //getting all docs for particular user in sub-collection(groups)
  GroupDoc.forEach((item) => console.log(item.data())); // loop through each document in group for each user so that we got nested data 
});