2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

【Firebase】Functionsでcollectionを削除

Posted at

課題

Firebaseを利用してユーザーが退会することをトリガーとしてユーザーが作成したFirestoreのデータを削除したい

問題

Firestoreにデータを入力する際にcollectionの名前をfirebase authのUIDに設定していた。しかしCollectionを指定して直接削除する関数は存在しなかった。

解決法

Collectionのすべてのdocumentを持ってきて、それを反復処理を通して削除する。

コード

import * as admin from "firebase-admin";
import * as functions from "firebase-functions";

export const deleteUserData = functions.auth.user().onDelete(async (user) => {
  const db = admin.firestore();
  const uid = user.uid;
  const collectionRef = db.collection(uid);

  return collectionRef
    .get()
    .then((snapshot) => {
      const batch = db.batch();
      snapshot.forEach((doc) => {
        batch.delete(doc.ref);
      });
      return batch.commit();
    })
    .catch((error) => {
      console.error("Error deleting collection: ", error);
    });
});
2
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
2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?