Home > OS >  Firebase v9 - Get a Referentiated Document Content
Firebase v9 - Get a Referentiated Document Content

Time:11-28

I don't understand why I'm not finding this documentation anywhere.

But I have a collection called users in my Firebase Firestore project. Inside users there are three collections: companies, policies and stores.

In the collection policies I have one store field and one company field that are references to one of that user's store or company.

Ok so as far as now is fine. But now, I'm performing the next query:

const subcollectionSnapshot = await getDocs(collection(db, 'users', 'S3casIyXxdddEAaa1YJL6UjBXLy2', 'policies'));

And the response is the next one: enter image description here

But now... how can I get the company and store nested documents? How can I "populate" them in order to see their information and access their fields?

Thanks.

CodePudding user response:

It looks like the company and store fields are of type DocumentReference.

In that case you can get a DocumentSnapshot of each of them by calling getDoc() with the DocumentReference:

subcollectionSnapshot.docs.forEach((policyDoc) => {
  const companyRef = policyDoc.data()["company"];
  const companyDoc = await getDoc(companyRef);
  const storeRef = policyDoc.data()["store"];
  const storeDoc = await getDoc(storeRef);
  ...
})

If you have multiple policy documents, you will need to do this for each of them. There is no concept of a server-side join in Firestore (nor in most other NoSQL databases).

  • Related