【问题标题】:How to recursively fetch collection with all subcollections?如何递归地获取所有子集合的集合?
【发布时间】:2019-06-18 10:04:15
【问题描述】:

我在 firestore 中有一个名为“steps”的集合,并且在步骤集合中我在每个 step 文档中有很多文档和子集合,称为“substeps”。我需要创建一个数组,其中包含我可以使用这个component 的所有步骤和子步骤,所以数组应该看起来像这样

let steps = [
  {
    step: 1,
    id: '1'
    substeps: [
      {
        step: '1.1'
        substeps: [
          {
            step: '1.1.2'
          }
        ]
      }
    ]
  }
]

现在我想创建递归函数,如果它们存在,将获取所有子步骤

我尝试创建应该获取所有子集合的函数,但我不知道如何完成它,所以下面是我尝试过的示例,但请注意函数未完成,这只是第一步 这里是documentation

fetchAllStepsDeep (request) {
    //this.steps = array of objects with step data
    let result = []
    let requestLocal = this.$firebaseFirestore.collection('steps_for_classes')

    for (let i in this.steps) {
        result.push(this.steps[i])
        requestLocal.doc(this.steps[i].id).get().then((doc) => {
            if (doc.exists) {
                console.log('Document data:', doc.data())
            } else {
                // doc.data() will be undefined in this case
                console.log('No such document!')
            }
        }).catch((error) => {
            console.log('Error getting document:', error)
        })
    }
}

有人可以帮我检索集合中的所有子集合并与其他子对象数组创建一个大数组吗?我使用 vue 框架,所以也许这会有所帮助

谢谢

【问题讨论】:

  • 您必须知道所有子集合的所有名称和路径,并单独查询它们。 Firestore 中没有“递归获取”操作。

标签: javascript firebase vue.js google-cloud-firestore


【解决方案1】:

如果子集合总是被调用substeps,你可以创建一个辅助函数来处理递归

function getSubstepsOf(docRef, path, result) {
  docRef.collection("substeps").get((querySnapshot) => {
    querySnapshot.forEach((doc) => {
      result.push({ path, doc });
      getSubstepsOf(doc.ref, `${path}/substeps/${doc.id}`, result);
    });
  });
}

然后从您现有的代码中调用它:

getSubstepsOf(doc.ref, doc.id, result);

【讨论】:

  • 是的,这就是我想要获取数据的方式,但我不知道如何在所有子数组和对象所在的位置创建这个大数组。我需要在这个结果数组中指定路径,不知道如何
  • 我在答案中添加了如何跟踪递归调用中的路径。任何时候你需要递归地做某事,把它作为参数传递给函数,并在你递归的时候构建它。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-02-13
  • 2021-06-29
  • 2010-12-01
相关资源
最近更新 更多