LoginSignup
19
13

More than 3 years have passed since last update.

FirestoreでCollectionを削除する

Posted at

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();
  }
19
13
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
19
13