😨

Firestoreのコレクションを全て消す

2023/02/16に公開

Batch writeとは?

FlutterFire公式を参考に試してみた!
https://firebase.flutter.dev/docs/firestore/usage

Firestore lets you execute multiple write operations as a single batch that can contain any combination of set, update, or delete operations.

First, create a new batch instance via the batch method, then perform the operations on the batch, and then commit it once ready. The below example shows how to delete all documents in a collection in a single operation:

Firestoreでは、複数の書き込み操作を1つのバッチとして実行できます。このバッチには、セット、更新、または削除の操作を任意に組み合わせることができます。

まず、バッチメソッドで新しいバッチのインスタンスを作成し、そのバッチに対して操作を実行し、準備ができたらコミットします。以下の例では、コレクション内の全文書を一度に削除しています。

ElevatedButton(
  onPressed: () async {
    // usersが無かったので追加!
    final users = FirebaseFirestore.instance.collection('users');
    WriteBatch batch = FirebaseFirestore.instance.batch();

    return users.get().then((querySnapshot) {
    querySnapshot.docs.forEach((document) {
    batch.delete(document.reference);
  });

  return batch.commit();
  });
},
child: Text('実行'))

まとめ

実行するとusersコレクションが全て削除された!
コレクションを全て削除したい処理を使いたいときに使うのでしょうね。
間違えると大変なことになりそうです😨

Flutter大学

Discussion