Skip to content

Instantly share code, notes, and snippets.

@mono0926 mono0926/batch_delete.ts
Last active Dec 12, 2018

Embed
What would you like to do?
Firestoreの特定のコレクションのドキュメントを全削除するスクリプト(TypeScript版)
// See: https://firebase.google.com/docs/firestore/manage-data/delete-data#collections
export async function deleteCollection(collectionRef: CollectionReference, batchSize: number = 500) {
const firestore = admin.firestore();
const query = collectionRef.orderBy('__name__').limit(batchSize);
await deleteQueryBatch(firestore, query, batchSize);
}
async function deleteQueryBatch(firestore: FirebaseFirestore.Firestore, query: Query, batchSize: number): Promise<void> {
const snapshot = await query.get();
// When there are no documents left, we are done
if (snapshot.size === 0) {
return;
}
// Delete documents in a batch
const results = await execute(async (batch) => {
snapshot.docs.forEach((doc) => {
batch.delete(doc.ref);
});
});
console.log(`deleted count: ${results.length}`);
return await deleteQueryBatch(firestore, query, batchSize);
}
export async function execute(f: (batch: WriteBatch) => Promise<void>): Promise<WriteResult[]> {
const batch = admin.firestore().batch();
await f(batch);
return await batch.commit();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.