【问题标题】:How to delete a collection with all its sub-collections and documents from Cloud Firestore如何从 Cloud Firestore 中删除集合及其所有子集合和文档
【发布时间】:2021-01-08 04:47:13
【问题描述】:

我在 Cloud Firestore 中有一个集合,其中包含数百万个文档和子集合。我想删除这个集合及其所有文档和子集合。我们可以从 Firebase 控制台执行此操作,但删除此集合需要很长时间。

是否有任何firebase cli命令或node.js代码sn-p使用我可以删除这个集合?

【问题讨论】:

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


    【解决方案1】:

    您可以通过删除集合的所有文档来删除集合。您可以在official docs 中阅读更多内容。示例代码:

    async function deleteCollection(db, collectionPath, batchSize) {
      const collectionRef = db.collection(collectionPath);
      const query = collectionRef.orderBy('__name__').limit(batchSize);
    
      return new Promise((resolve, reject) => {
        deleteQueryBatch(db, query, resolve).catch(reject);
      });
    }
    
    async function deleteQueryBatch(db, query, resolve) {
      const snapshot = await query.get();
    
      const batchSize = snapshot.size;
      if (batchSize === 0) {
        // When there are no documents left, we are done
        resolve();
        return;
      }
    
      // Delete documents in a batch
      const batch = db.batch();
      snapshot.docs.forEach((doc) => {
        batch.delete(doc.ref);
      });
      await batch.commit();
    
      // Recurse on the next process tick, to avoid
      // exploding the stack.
      process.nextTick(() => {
        deleteQueryBatch(db, query, resolve);
      });
    }
    

    如果上面的答案不起作用,您可以使用 Cloud Functions,如 here

    【讨论】:

    • 我应该在哪里运行上面的代码?我应该把它放在javascript文件中并运行它吗?你能给我一点想法吗?
    • 你可以在 node.js 服务器上运行它。如果您不想这样做,那么使用我上面提供的链接中的 CLI 方法是您的最佳选择
    【解决方案2】:

    Firebase CLI 有一个 firestore:delete 命令也可以递归删除内容。请参阅其文档here

    请注意,API 和 CLI 都不可能比控制台快得多。由于没有用于批量删除数据的 API,因此它们基本上都采用相同的方法。

    【讨论】:

      猜你喜欢
      • 2020-04-16
      • 2018-10-19
      • 2021-08-12
      • 2018-11-01
      • 2018-03-22
      • 2018-08-23
      相关资源
      最近更新 更多