Ask Your Question

How can a whole collection be removed using Cloud Functions?

asked 2022-01-13 11:00:00 +0000

djk gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted

answered 2023-02-14 01:00:00 +0000

qstack gravatar image

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 => {

  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.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer

Question Tools


Asked: 2022-01-13 11:00:00 +0000

Seen: 19 times

Last updated: Feb 14 '23