LoginSignup
0
2

More than 3 years have passed since last update.

firestoreのコレクション内のドキュメントを削除したときにサブコレクションも削除したい

Last updated at Posted at 2020-09-02

firestoreのコレクションを削除しても、その下にあるサブコレクションは削除されない

コレクションの削除

//...省略

  db = firebase.firestore();

//...省略

 collectionDelete(docId: string) {
    this.db
      .collection("myCollection")
      .doc(docId)//myCollectionのなかのドキュメントID
      .delete()
      .then(() => {
        console.log("削除完了");
      });

これでドキュメントは削除完了
ただこの状態だとこのコレクションにあるサブコレクションは残ったまんま

サブコレクションの削除

   subCollectionDelete(docId: string) {
    this.db
      .collection("myCollection")
      .doc(docId)//myCollectionのなかのドキュメントのID
      .collection("mySubCollection")
      .get()
      .then((subDoc) => {
        subDoc.forEach((doc) => {
          console.log(doc.data());
          this.db
            .collection("myCollection")
            .doc(docId)
            .collection("mySubCollection")
            .doc(doc.id)
            .delete()
            .then(() => {
              console.log("mySubCollection削除");
            });
        });
      });
  }

これで先ほど消したドキュメントのサブコレクションが全部消せます。
サブコレクションを削除する場合は一度.get()で消したいサブコレクションを取得して
その取得したサブコレクションに対してforEachを使って一つずつ消す形になります。
サブコレクションの数が多い場合はcloudFunctionsを使って削除した方がいいのかもしれません。

後はこの二つのメソッドを実行すれば完了です。


allDelete(docId: string) {
    this.collectionDelete(docId)
    this.subCollectionDelete(docId)
  }

間違いがあったらご指摘いただけると嬉しいです。

以上です!

0
2
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
0
2