How to delete all documents from a collection in Google Cloud Firestore?

To delete all documents from a Firebase collection in Firestore we need to get the collection, iterate over its elements and delete each one of them:

const db = new Firestore({
  projectId: "projectId",
  keyFilename: "./key.json"
});

db.collection("collectionName")
  .get()
  .then(res => {
    res.forEach(element => {
      element.ref.delete();
    });
  });

Comments

  1. when i try to use this, my collection got deleted too, how to only delete all the documents inside the collection without deleting the collection?

  2. I’d be careful with the provided code. Not returning the element.ref.delete(); promise means that the overall promise can resolve prior to the deletes getting through.

    Sometimes that might not matter; other times it might. Changing it is simple, by async/await and Promise.all.

    On your own – haven’t tested yet:

    const qss = await collection.get();
    const proms = qss.docs.map( qdss => qdss.ref.delete() );
    await Promise.all(proms);

  3. The Firebase CLI allows you to delete an entire collection with a single command, but it just calls the API to delete all documents in that collection in batches. If this suits your needs, I recommend you check out the (sparse) documentation for the

Leave a Reply to Cuma Toğa Cancel reply

Your email address will not be published. Required fields are marked *