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

问题描述 投票:5回答:2

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

用法:firestore:删除[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

如何删除整个数据库?

firebase google-cloud-firestore firebase-cli
2个回答
0
投票

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

目前,这是一种预期的行为。如我们的documentation所述,删除超过500个文档的集合需要多个批量操作。因此,进行迭代将是处理部分删除情况的好方法。我还建议您查看我们关于一些可调用函数limitations的文档以获取更多详细信息。

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

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

经过一些迭代后,您将看到没有剩余的集合,您可以停止脚本。您的Firestore DB现在已完全清空。


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}`);
      }
   }
});
© www.soinside.com 2019 - 2024. All rights reserved.