Mahar
Mahar

Reputation: 51

Firebase Get document from subcollection using its ID only

Is it possible to fetch a document from a subcollection without parent document ids?

We have a structure like:

RootCollection1
 -- SubCollection1
    -- SubCollection2
       - Document1
    -- SubCollection3
       -- Document2
          -- SubCollection2
             -- Document3 [different fields with Document1]

App User will only have the Document1 ID.

I tried implementing a collection group query. Notice that SubCollection2 name appears twice and they have different fields/values. I only want to get the document from one SubCollection2.

Is it possible to fetch the data from document1 without the parent doc id from SubCollection1 and RootCollection1.

Upvotes: 4

Views: 2097

Answers (2)

Nam
Nam

Reputation: 1

This is all you need:

firestore.collection("Task").doc(taskId).collection("SubTask").doc(subTaskId).get();

Upvotes: 0

Doug Stevenson
Doug Stevenson

Reputation: 317412

If you can't locate a document using its full path (knowing the names of all documents and collections in the path), and you can't use a collection group query, then what you're trying to do isn't possible. You can't focus a collection group query to a specific path - they always consider all documents in all collections with the same name.

You have two viable workarounds:

  1. Change the name of the subcollection so that it's unique and does not overlap with subcollections that should not be queried in a collection group query.

  2. Add a field to the document so you can use it in a filter on a collection group query. You will have to be able to identify which documents you are interested in without considering all documents in all subcollections with the same name. For example, if you have a field called "scope", you can narrow the scope of your collection group query like this:

    firestore.collectionGroup('coll').where('scope', '==', 'x')
    

    Or you can store the ID of the document as a field in it, and filter for it:

    firestore.collectionGroup('coll').where('id', '==', 'id')
    

Upvotes: 1

Related Questions