首页 > 解决方案 > Angular Firestore - 从嵌套的引用数组映射数据

问题描述

我有一个集合 A,这些文档有一个对集合 B 中文档的引用数组。

在此处输入图像描述

在我的服务中,我得到了所有的 A,但有一系列不可用的对象。但我也想查看它们。

  getAs() {
      this.aService.getAs().subscribe((data) => {
        this.aArray = data.map((e) => {
          return {
            id: e.payload.doc.id,
            ...(e.payload.doc.data() as {}),
          } as A;
        });
      //TODO some magic to get a nice array of B's inside every A
      });
   }

在此处输入图像描述

重要的是获取 A 对象数组,其中包含 B 对象数组,而不是 A 和 B 的两个单独数组。

我希望我已经在某种程度上清楚地表达了自己。提前致谢

标签: arraysangulartypescriptgoogle-cloud-firestore

解决方案


正如 Firestore 文档中所述,Firestore Reference文档引用是指 Firestore 中的文档位置,可用于读取、写入或收听所述文档。这意味着引用类型不存储文档数据,因此您必须查询它。

您需要做的是遍历每个引用array_of_bs并使用其路径来查询相应的文档。然后,将文档数据添加到一个临时数组中,并将其与 map() 函数返回的数组结合起来,如下所示:

async getAs() {
   this.aService.getAs().subscribe(async (data) => {
     const promises = await data.map(async (e) => {

       // temp array to hold b document data
       let array_of_bs = [];

       // loop over each reference in array_of_bs
       for (const path of (e.payload.doc.data() as any).array_of_bs) {
         const bObj = await this.afs.doc(path).get().toPromise();
         array_of_bs.push(bObj.data());
       }

       return {
         id: e.payload.doc.id,
         ...(e.payload.doc.data() as {}),
         array_of_bs: array_of_bs // this will overwrite the array_of_bs returned in the above line with the document data
       } as A;
     });

     const docValues = await Promise.all(promises);

     console.log(docValues);
   });
 }

推荐阅读