chelly
chelly

Reputation: 33

Get Nested Docs in Firestore

Here is my data:

enter image description here

I want to iterate through each event_prod in event_prods and go to the eventGroups subcollection. Once in that sub-collection, I want to loop through each eventGroup in eventGroups and get doc data.

Here's my code thus far:

async function getAllEventGroups() {
  let eventGroups = []

  try {
    let eventProducerRef = await db.collection('event_prods')
    let allEventProducers = eventProducerRef.get().then(
      producer => {
        producer.forEach(doc => console.log(doc.collection('eventGroups'))
      }
    )
  } catch (error) {
    console.log(`get(): there be an error ${error}`)
    return []
  }
  return eventGroups
}

Obviously, it doesn't do what I want, but I can't figure out how to get access to the eventGroups subcollection. Calling 'collection()' on 'doc' is undefined. Can someone please help fix this? By the way, I don't care if this requires two (or more) queries as long as I don't have to bring in data I will never use.

Edit: this is not a duplicated because I know the name of my subcollection

Upvotes: 2

Views: 4262

Answers (2)

Raphael Jenni
Raphael Jenni

Reputation: 318

You call the .collection on the QueryDocumentSnapshot. This methods doesn't exist there. But as the QueryDocumentSnapshot extends DocumentSnapshot you can call ref on it to get the reference to the requested document.

```

let allEventProducers = eventProducerRef.get().then(
      producer => {
        producer.forEach(doc => console.log(doc.ref.collection('eventGroups')) // not the ref here
      }
    )

Upvotes: 1

Doug Stevenson
Doug Stevenson

Reputation: 317437

eventProducerRef is a CollectionReference. The get() method on that yields a QuerySnapshot, which you are storing in producer. When you iterate it with forEach(), you are getting a series of QueryDocumentSnapshot objects, which you're storing in doc. QueryDocumentSnapshot doesn't have a method called collection(), as you are trying to use right now.

If you want to reach into a subcollection of a document, build a DocumentReference to the document, then call its collection() method. You'll need to use the id of each document for this. Since a QueryDocumentSnapshot subclasses DocumentSnapshot, you can use its id property for this:

let eventProducerRef = await db.collection('event_prods')
let allEventProducers = eventProducerRef.get().then(
  producer => {
    producer.forEach(snapshot => {
      const docRef = eventProducerRef.doc(snapshot.id)
      const subcollection = docRef.collection('eventGroups')
    })
  }
)

Upvotes: 0

Related Questions