MK01111000
MK01111000

Reputation: 822

How to retrieve documents from subcollections in Firestore

enter image description here

I am trying to retrieve all documents ("Spanish", ...) within sub-collection group for all groups and all cards for each group The following returns all documents for group "Spanish" But How to retrieve the documents if the name of the group is not known and when there are more than one

db.collection('usersx').doc(this.user.email).collection('group').doc('Spanish').collection('card').get()
  .then(querySnapshot => {
    querySnapshot.forEach(doc => {
      console.log(doc.id, ' => ', doc.data())
    })
  });

The desired outcome would be something like this:

[
  {
    "id":"[email protected]",
    "group":[
      {
        "Spanish":{
          "cards":[
            {
              "front":"huis",
              "back":"house"
            },
            {
              "front":"auto",
              "back":"car"
            }
          ]
        }
      },
      {
        "English":{
          "cards":[
            {
              "front":"test",
              "back":"test"
            },
            {
              "front":"bla",
              "back":"blabla"
            }
          ]
        }
      }
    ]
  }
]

Upvotes: 1

Views: 825

Answers (1)

LeadDreamer
LeadDreamer

Reputation: 3499

You need to fetch on the collectionGroup 'cards' - collection groups are across all structures, and there is no way to qualify the collection on a "parent".

What you can do is add the parent name as a field in your cards document, such as 'languageField:' (a safe operation because it will be static), then use that as part of a query:

// to fetch ALL cards
db.collectionGroup('card').get()
  .then(querySnapshot => {
    querySnapshot.forEach(doc => {
      console.log(doc.id, ' => ', doc.data())
    })
  });

//to fetch SOME cards
db.collectionGroup('card').where(fieldRef:'languageField', opstr: '==', value: 'Spanish').get()
  .then(querySnapshot => {
    querySnapshot.forEach(doc => {
      console.log(doc.id, ' => ', doc.data())
    })
  });

Incidentally, the doc.ref contains a field refPath, which is the fully qualified path FROM THE ROOT, which you can parse to find the specific language collection the card was part of. I use a HIGHLY structured database, and use this approach all the time, including finding the parent(s) via the refPath.

Upvotes: 1

Related Questions