Skip to content
Advertisement

Iterating collection and trying to get reference field inside documents .get() is not working

I am trying to get a collection then iterating over its documents. inside every document there’s a reference field for another collection document. Normally if i query for it then there is no problem but iterating creates a problem

Following the field i want to get while iterating over organization-members

enter image description here

 const result = await firestore.collection("organization-members").get();
      result.docs.forEach((doc) => {  // or result.forEach
        const data = doc.data();
        const organization = data.organization;
     
        const orgData = await organization.get() // But this says that organization.get() is not a function
      });

However if i hard query then it works okay

const snap = await firestore
      .doc("organization-members/BOcSNLR4bt8i0Ay4aAr7")
      .get();
    const orgSnap = await snap.data().organization.get();
    console.log(orgSnap.data());

There objects are different as well

upper log is from when i hard query for it and the lower one when i loop through the collection documents

enter image description here

What am i doing wrong

Advertisement

Answer

For anyone else having similar problem this answer might help you

So first of all there was a mistake inside my code but that gave me another answer

Mistake is is that i forgot to add async in forEach function

This should be like this

 const result = await firestore.collection("organization-members").get();
  result.docs.forEach(async (doc) => {  // or result.forEach
    const data = doc.data();
    const organization = data.organization;
 
    const orgData = await organization.get() // But this says that organization.get() is not a function
  });

But this is not the correct way

Apparently async/await does not work properly inside forEach loop i don’t know the reason behind this i did contact the firebase team and there representative said the same thing so the best way should be to use for loop

e.g

for(doc of result.docs)

This will always work fine

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement