Skip to content
Permalink
Branch: master
Find file Copy path
Find file Copy path
Fetching contributors…
Cannot retrieve contributors at this time
80 lines (60 sloc) 2.18 KB
title lastmod publishdate author draft description tags
Delete a Firestore Collection
2020-02-11 14:29:28 -0700
2020-02-11 14:29:28 -0700
Jeff Delaney
false
How to delete a Firestore Collection or Subcollection
firebase
firestore

Deleting an entire collection from Firestore should be handled on a backend server. Collections can grow infinitely large, so deleting a millions of documents can be an excessively large workload to put on a clientside web or mobile app.

Option A - Use the CLI or Console

You can manually delete a collection or subcollection from the Firebase Console OR by using the CLI.

{{< file "terminal" "command line" >}} {{< highlight text >}} firebase firestore:delete path-to-delete {{< /highlight >}}

Option B - Use a Cloud Function

It is possible to interact with Firebase Tools from a Cloud Function. This works especially well with Callable functions because you most certainly want to enforce some form of user authorization.

First, obtain CI token to authenticate firebase tools.

cd functions
npm i firebase-tools -D

firebase login:ci
# your_token

firebase functions:config:set ci_token="your_token"

The function should validate the user has permission to run the operation. If allowed, it runs the CLI command recursively on the collection and its nested subcollections.

const project = process.env.GCLOUD_PROJECT;
const token = functions.config().ci_token;

exports.deleteCollection = functions.runWith({ timeoutSeconds: 540})
  .https.onCall((data, context) => {

      const path = data.path;
      const allowed = context.auth.uid === path.split('/')[0]; // TODO your own logic

    if (!allowed) {
      throw new functions.https.HttpsError(
        'permission-denied',
        'Hey, that is not cool buddy!'
      );
    }

    return firebase_tools.firestore
      .delete(path, {
        project,
        token,
        recursive: true,
        yes: true,
      })
      .then(() => ({ result: 'all done!' });
  });
You can’t perform that action at this time.