Help us understand the problem. What is going on with this article?

FirestoreでCollectionを削除する

Firestoreではコレクションを完全に削除するにはその下に紐づいているドキュメントを一個一個全部削除してからそのあと、コレクションを削除しないと、完全に削除できません。

公式ドキュメント↓
https://firebase.google.com/docs/firestore/manage-data/delete-data?hl=ja

また、FirestoreのBatchでは一度に500個までしかできないので、500以上まとめて削除する場合はそれぞれを500個ずつ分割して削除する必要があります。

公式ドキュメント↓
https://firebase.google.com/docs/firestore/manage-data/transactions?hl=ja

なので、それを考慮して削除するコードを記載します。

実装

const batchArray: admin.firestore.WriteBatch[] = [];
    batchArray.push(db.batch());
    let operationCounter = 0;
    let batchIndex = 0;

    const roomId = chatQuery.docs[0].id;
    const deleteDoc = await db
      .collection("test")
      .doc(testId)
      .collection("docs")
      .get();
    deleteDoc.forEach(doc => {
      batchArray[batchIndex].delete;
      operationCounter++;

      if (operationCounter === 499) {
        batchArray.push(db.batch());
        batchIndex++;
        operationCounter = 0;
      }
    });

    batchArray.forEach(async batch => await batch.commit());

    await db
      .collection("chat_room")
      .doc(roomId)
      .delete();
  }
superman9387
I love Flutter 🔥❤️ 業務ではAndroidを書いていて、個人ではFlutterを書いています。 Flutterを愛しています。
https://note.mu/shogoyamada
zozotech
70億人のファッションを技術の力で変えていく
https://tech.zozo.com/
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした