Last active
December 5, 2021 00:11
-
-
Save mono0926/78c3d3e078323d566b46929c7540b15b to your computer and use it in GitHub Desktop.
Firestoreの特定のコレクションのドキュメントを全削除するスクリプト(TypeScript版)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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