Firestore递归删除功能不删除嵌套子集合?

问题描述 投票:0回答:1

我正在尝试递归删除 Firestore 文档及其子集合,但当函数遇到包含子集合的嵌套文档时,我遇到了问题。

这是我正在处理的结构:

parentCol/uid/childCol_1/child_Doc1
parentCol/uid/childCol_1/child_Doc1/child_Col2/child_Doc2

我写了下面的递归删除函数,但是当遇到有子集合的child_Doc1时,它似乎停止了,并且没有删除child_Col2下的嵌套数据。相反,它只是记录路径,不会进一步继续。

// parentCol/uid/childCol_1/child_Doc1
// parentCol/uid/childCol_1/child_Doc1/child_Col2/child_Doc2

 const deleteDocumentAndCollections = async (path: string): Promise<void> => {
      try {
        console.log('deletePath:====>', path);
        // Get a reference to the initial document
        const documentRef = firestore.doc(path);

        // List all subcollections under the document to delete
        const subcollections = await documentRef.listCollections();

        console.log('Subcollections:====>', subcollections);

        // Error deleting document and subcollections: Error: Value for argument "documentPath" must point to a document,
        // but was parentCol/uid/childCol_1/
        // Your path does not contain an even number of components.

        // Recursively process and delete each subcollection
        for (const subcollection of subcollections) {
          try {
            // Call the function recursively to delete the subcollection recursively
            await deleteDocumentAndCollections(subcollection.path);
          } catch (error) {
            console.error('Error processing subcollection:', error);
          }
        }

        // Now, delete the document itself
        console.log('Deleting document:', documentRef.path);
        await documentRef.delete();
        console.log('Successfully deleted document:', documentRef.path);
      } catch (error) {
        console.error('Error deleting document and subcollections:', error);
      }
    };

javascript google-cloud-firestore
1个回答
0
投票

您的函数将子集合路径传递给自身,它立即假设它是文档路径。 您无法使用子集合路径创建文档引用(使用

firestore.doc()
)。 这就是错误消息试图告诉您的内容。

您将需要第二个函数,它采用子集合路径,列出其文档路径,并在每个文档路径上调用

deleteDocumentAndCollections

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.