Search code examples
javascriptgoogle-cloud-firestore

Firestore recursive delete function not deleting nested subcollections?


I'm trying to recursively delete a Firestore document and its subcollections, but I'm running into an issue when the function encounters a nested document that contains subcollections.

Here’s the structure I'm dealing with:

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

I've written the following recursive delete function, but when it encounters child_Doc1, which has subcollections, it seems to stop and doesn’t delete the nested data under child_Col2. Instead, it just logs the path and doesn't proceed further.

// 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);
      }
    };


Solution

  • Your function is passing a subcollection path to itself, which immediately assumes that it's a document path instead. You can't create a document reference (with firestore.doc()) using subcollection path. That's what the error message is trying to tell you.

    Instead of calling deleteDocumentAndCollections(subcollection.path), you're going to need a second function that takes a subcollection path, lists its nested documents paths, and calls deleteDocumentAndCollections on each of those document paths.