Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save guptahitesh121/3bb4c61961d0286d023d2e2a0d553459 to your computer and use it in GitHub Desktop.
Save guptahitesh121/3bb4c61961d0286d023d2e2a0d553459 to your computer and use it in GitHub Desktop.
const deepDeleteDoc = async (store: admin.firestore.Firestore, docPath: string, batchSize: number): Promise<any> => {
const doc = store.doc(docPath);
const snap = await doc.get();
if (!snap.exists) return;
console.log('Found doc - ' + docPath);
// Check if this doc has subcollections
const subCollections = await snap.ref.listCollections();
const promises: Promise<void>[] = [];
if (subCollections) {
for (const subCollection of subCollections) {
console.log('Found sub collection - ' + subCollection.path);
const subQuery = subCollection.limit(batchSize);
// Delete all sub collection docs
promises.push(deleteQueryBatch(store, subQuery, batchSize));
}
}
await Promise.all(promises);
console.log('All collections are done for doc and now deleting it - ' + docPath);
return doc.delete();
}
const deepDeleteCollection = (store: admin.firestore.Firestore, collectionPath: string, batchSize: number): Promise<any> => {
const collection = store.collection(collectionPath);
const query = collection.limit(batchSize);
return deleteQueryBatch(store, query, batchSize);
}
const deleteQueryBatch = async (store: admin.firestore.Firestore, query: admin.firestore.Query, batchSize: number): Promise<any> => {
const snaps = await query.get();
// When there are no documents left, we are done
if (snaps.size === 0) {
return;
}
const promises1: Promise<any>[] = [];
for (const doc of snaps.docs) {
// Check if this doc has subcollections
const subCollections = await doc.ref.listCollections();
const promises2: Promise<void>[] = [];
if (subCollections) {
for (const subCollection of subCollections) {
console.log('Found sub collection - ' + subCollection.path);
const subQuery = subCollection.limit(batchSize);
// Delete all sub collection docs
promises2.push(deleteQueryBatch(store, subQuery, batchSize));
}
}
await Promise.all(promises2);
// And delete the document only if all subcollections deleted succesfully
console.log('All collections are done for doc and now deleting it - ' + doc.ref.path);
promises1.push(doc.ref.delete());
}
return Promise.all(promises1);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment