Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

To remove a whole collection using Cloud Functions, you can use the batch() method to create a batch operation and then use the delete() method to remove each document within the collection.

Here's an example code snippet:

const admin = require('firebase-admin');

exports.deleteCollection = functions.https.onCall(async (data, context) => {
  const collectionRef = admin.firestore().collection(data.collectionPath);
  const batch = admin.firestore().batch();

  const docs = await collectionRef.get();
  docs.forEach(doc => {
    batch.delete(doc.ref);
  });

  await batch.commit();

  return `Collection ${data.collectionPath} successfully deleted.`;
});

In this example, the Cloud Function is triggered when the deleteCollection function is called. The function takes a collectionPath parameter, which is the path of the collection to be deleted.

The function starts by creating a reference to the collection using admin.firestore().collection() method. It then creates a batch operation using admin.firestore().batch() method.

Next, the function retrieves all the documents in the collection using collectionRef.get() method and loops through each document using docs.forEach() method. For each document, it adds a delete operation to the batch using batch.delete(doc.ref) method.

Finally, the function commits the batch operation using batch.commit() method to remove all the documents within the collection. The function returns a success message once the operation is completed.