Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
142 views
in Technique[技术] by (71.8m points)

javascript - 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

question from:https://stackoverflow.com/questions/66062793/iterating-collection-and-trying-to-get-reference-field-inside-documents-get-i

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...