从Firestore中删除所有文档和集合

时间:2018-05-09 13:09:14

标签: firebase google-cloud-firestore firebase-cli

我正在尝试清除Firestore数据库,该数据库中包含大量文档和子集合以供测试。 Firebase CLI(firebase-tools@3.18.4)建议从Cloud Firestore删除数据的可能性如下:

用法: firestore:delete [options] [path]

选项:

-r, --recursive    Recursive. Delete all documents and subcollections. Any action which would result in the deletion of child documents will fail if this argument is not passed. May not be passed along with --shallow.
--shallow          Shallow. Delete only parent documents and ignore documents in subcollections. Any action which would orphan documents will fail if this argument is not passed. May not be passed along with -r.
--all-collections  Delete all. Deletes the entire Firestore database, including all collections and documents. Any other flags or arguments will be ignored.
-y, --yes          No confirmation. Otherwise, a confirmation prompt will appear.

问题在于它对我来说并不适用。

执行firebase firestore:delete --all-collections会产生以下输出:

You are about to delete YOUR ENTIRE DATABASE. Are you sure? Yes
Deleting the following collections: 13OPlWrRit5PoaAbM0Rk, 17lHmJpTKVn1MBBbC169, 18LvlhhaCA1tygJYqIDt, 1DgDspzJwSEZrYxeM5G6, 1GQE7ySki4MhXxAeAzpx, 1MhoDe5JZY8Lz3yd7rVl, 1NOZ7OJeqSKl38dyh5Sw, 1Rxkjpgmr3gKvYhBJX29, 1S3mAhzQMd137Eli7qAp, 1S8FZxuefpIWBGx0hJW2, 1a7viEplYa79eNNus5xC, 1cgzMxAayzSkZv2iZf6e, 1dGjESrw6j12hEOqMpky, 1dbfgFD5teTXvQ6Ym897, 1eeYQgv2BJIS0aFWPksD, 1ehWNAZ0uKwg7mPXt3go, 1fDTkbwrXmGwZlFUl3zi, 1k5bk4aiMCuPw2KvCoAl, 1pxUSDh1YqkQAcuUH9Ie, 1rMSZ5Ru0cAfdcjY0Ljy
Deleted 92 docs (652 docs/s)

即使多次执行该功能,仍然会在Firestore数据库中保留大量文档和子集合。执行该命令时,只删除约70-150个文档,而不是删除ENTIRE DATABASE

如何删除整个数据库?

2 个答案:

答案 0 :(得分:0)

我已将其报告为错误,并收到以下答案:

  

当前,这是预期的行为。如我们的documentation中所述,要删除500多个文档的集合,就需要进行多个批处理操作。因此,进行迭代将是处理部分删除案例的好方法。我还建议您检查有关某些可调用函数limitations的文档,以了解更多详细信息。

这意味着firebase-tools一次操作最多只能删除500个文档。我删除数据库中所有集合和文档的解决方案是使用while循环:

while firebase firestore:delete --all-collections --project MYPROJECT -y; do :; done

经过一些迭代,您将看到没有可用的集合,可以停止脚本。现在,您的Firestore数据库是完全空的。

答案 1 :(得分:0)

您将要使用admin sdk来完成此任务。使用.listDocuments.listCollections构建简单的迭代来执行您的.delete操作。

如果文档.listCollections的响应长度为零或null或为空,则说明没有子集合,可以迭代/跳过。否则,迭代子集合文档以查找要删除的更深子集合。

let documentRef = firestore.doc('col/doc');

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

let collectionRef = firestore.collection('col');

return collectionRef.listDocuments().then(documentRefs => {
   return firestore.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}`);
      }
   }
});