【问题标题】:Google Cloud Function to delete sub-collections on "missing documents谷歌云功能删除“丢失文档”的子集合
【发布时间】:2021-06-17 21:17:21
【问题描述】:

我有一个名为 Posts 的 Firestore 集合,Posts 中的每个文档都可以有一个名为 Post-Likes 和/或 Post-Comments 的子集合。当我删除 Posts 文档时,它不会删除子集合,因此我留下了对 Firestore 中缺失文档的引用,如下所示:

我在我的 Google Cloud 函数中使用以下代码在 Post 集合中查找缺少数据的引用,然后对于缺少引用的每个文档,我想删除子集合 Post-Likes 和 Post-Comments。目前,我只是尝试列出子集合文档,以便删除它们,但出现错误。

function deleteOrphanPostSubCollections() {

    let collectionRef = db.collection('Posts');

    return collectionRef.listDocuments().then(documentRefs => {
       return db.getAll(...documentRefs);
    }).then(documentSnapshots => {
       for (let documentSnapshot of documentSnapshots) {
          if (documentSnapshot.exists) {
            console.log(`Found document with data: ${documentSnapshot.id}`);
          } else {
            console.log(`Found missing document: ${documentSnapshot.id}`);
            return documentSnapshot.getCollections().then(collections => {
              return collections.forEach(collection => {
                console.log('Found subcollection with id:', collection.id);
              });
            });
          }
       }
       return
    });
}

但是,我收到以下错误。请帮我解决这个问题。

【问题讨论】:

    标签: javascript node.js google-cloud-firestore google-cloud-functions firebase-admin


    【解决方案1】:

    这是因为DocumentSnapshot 没有getCollections() 方法。

    如果要列出DocumentSnapshot对应的Document的所有集合,需要使用listCollections()方法,如下:

    documentSnapshot.ref.listCollections()
      .then(collections => {
        for (let collection of collections) {
          console.log(`Found subcollection with id: ${collection.id}`);
        }
      });
    

    另外,请注意,如果您在循环中调用异步方法,建议使用Promise.all(),以便在所有“输入”Promise 都解析时返回一个解析的 Promise。

    【讨论】:

    • 嘿@ramluro,你有时间看看建议的解决方案吗?
    猜你喜欢
    • 2013-04-24
    • 1970-01-01
    • 2022-09-27
    • 2013-08-29
    • 1970-01-01
    • 2021-03-06
    • 2022-09-23
    • 2019-01-30
    • 2020-05-21
    相关资源
    最近更新 更多