Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
10
Help us understand the problem. What is going on with this article?
@superman9387

FirestoreでCollectionを削除する

More than 1 year has passed since last update.

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();
  }
10
Help us understand the problem. What is going on with this article?
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
superman9387
I love Flutter 🔥❤️ 業務ではAndroidを書いていて、個人ではFlutterを書いています。 Flutterを愛しています。
zozotech
70億人のファッションを技術の力で変えていく

Comments

No comments
Sign up for free and join this conversation.
Sign Up
If you already have a Qiita account Login
10
Help us understand the problem. What is going on with this article?