Home > OS >  How to get reference data inside map of parent data in Firebase
How to get reference data inside map of parent data in Firebase

Time:04-29

I can't get this to work. Code is as follows and problem is res.data() doesn't show in de docs object.

getProjects = async () => {
    const colRef = db.collection('parentCollection').orderBy('createdAt', 'desc');
    const snapshots = await colRef.get();
    const docs = snapshots.docs.map((doc) => ({
      docId: doc.id,
      ...doc.data(),
      ...doc
        .data()
        .childId.get()
        .then((res) => res.data()),
    }));
    this.setState({
      list: docs,
    });
  };

CodePudding user response:

This answer from here worked!

db.collection('parentCollection').get()
    .then(res => {
      vm.mainListItems = [];
      res.forEach(doc => {
        let newItem = doc.data();
        newItem.id = doc.id;
        if (newItem. childId) {
          newItem. childId.get()
          .then(res => { 
            newItem.userData = res.data() 
            vm.mainListItems.push(newItem);
          })
          .catch(err => console.error(err));
        } else {
          vm.mainListItems.push(newItem);  
        }

      });
    })
    .catch(err => { console.error(err) });

CodePudding user response:

I understand from the comment that the childId field is of type Reference. The following code, using Promise.all(), should do the trick (untested):

const colRef = db.collection('parentCollection').orderBy('createdAt', 'desc');
const snapshots = await colRef.get();

const promises = [];
snapshots.forEach(snapshot => {
    promises.push(db.doc(snapshot.data().childId).get())
})

const childrenSnapshots = await Promise.all(promises); // Returns an Array of Document Snaphots, in the same order than the parents

const docs = [];
snapshots.forEach((snapshot, index) => {
    docs.push({
        docId: snapshot.id,
        ...snapshot.data(),
        ...childrenSnapshots[index].data()
    });
}); 
  • Related