0

I have document ids in a collection say idsCollection. I have another collection where documents are actually stored say path-to-documents/docId. I want an array say results to return all documents. I'm trying to achieve this as follows:

function getAllDocuments(database: any) {
  return new Promise((resolve, reject) => {
          const idsCollection = "path/idsCollection"
          const docPath = "path-to-documents/documents"
          const dataSource = database
          const dataRef = dataSource.collection(idsCollection);

          const results = {};
          dataRef.get()
              .then(snapshot => {
                  snapshot.forEach(doc => {
                      let id = doc.data().docId
                      console.log("docId: " + id)

                      dataSource.doc(docPath+id).get()
                      .then(d => {
                        results[d.id] = d.data()
                      })
                  })

                  //return results[documentId]: {document}
                  if (Object.keys(results).length > 0) {
                      resolve(results);
                  } else {
                      resolve('No such document');
                  }
              }).catch(err => {
                  reject(false);
                  console.log('Error getting documents', err);
              });
        })
}

Disclaimer: I'm new to NodeJs and Promise.

bianca
  • 7,004
  • 12
  • 43
  • 58

1 Answers1

0

The creation of a new promise is unnecessary. .get() will return a promise. firestore also has a getAll you can take advantage of, Check this post.

As an example

return dataRef.get().then(snapshot => {
  docRefs = []
  snapshot.forEach(doc => {
    docRefs.push(firestore.collection(docPath).doc(doc.data().docId)
  })
  return dataSource.getAll(...docRefs)
})
ACzChef
  • 31
  • 3
  • ```dataSource.getAll(...docRefs)``` returns big blob of document, which is nice. However, I want to return only few fields as array/list : `results[doc.id]=doc.data().member1`. How can I transform data in this format ? – bianca Apr 18 '19 at 19:00
  • You can use array.map(). There's no way to retrieve specific fields. `members = results.map(doc => doc.data().member1)` – ACzChef Apr 18 '19 at 21:29
  • if you want a mapping of document ids to member1, you would use reduce instead – ACzChef Apr 18 '19 at 21:33
  • Looks like [this](https://cloud.google.com/nodejs/docs/reference/firestore/1.2.x/global#ReadOptions) could also help. – ACzChef Apr 20 '19 at 13:49