Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to recursively delete collection in firestore?

I needed a way to quickly clear an entire firestore DB but couldn't find great documentation for how to do it. Eventually I found on stack overflow this answer (Clear Firestore database of all data?) but was a bit nervous about how long it would take to clear my entire DB of millions of documents, so I want a way to just recursively delete a collection at a time.

Background: I've been running some tests migrating large amounts of data from an old DB to firestore, and after each run I want a clean slate to work with in firestore. Do NOT use this on production data!

like image 424
Alex Egli Avatar asked Jan 25 '23 12:01

Alex Egli


1 Answers

This is now documented via recursiveDelete function:

  • https://googleapis.dev/nodejs/firestore/latest/Firestore.html#recursiveDelete

Note that this is a relatively new feature, so you need to make sure your Firebase libraries are updated.

// Setup
const admin = require('firebase-admin');
const serviceAccount = require("./files/my-file.json");
admin.initializeApp({
  credential: admin.credential.cert(serviceAccount)
});
const firestore = admin.firestore();

// Delete
const documentRef = firestore
      .collection("users")
      .doc("M3S2iPhsiu2ZQmOK8ZcC");
await firestore.recursiveDelete(documentRef);
like image 186
kgaidis Avatar answered Mar 31 '23 19:03

kgaidis