0
1

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 3 years have passed since last update.

Firestoreでドキュメント(document)削除したけど、サブコレクション(subcollection)消えないって人へ

Posted at

Firebase/Firestoreを使って、SNSの投稿機能を実装しようとしていました。

※違うところはご指摘いただけると幸いです。

ところが、投稿(posts/{postId})を削除したのにサブコレクション(comments/{comment}が消えないじゃないか...

documentとsubcollectionの表記が雑ですみません。

そこで色々調べてみましたが...
・CloudFuctionsを使って削除する
・別途commentsのdocumentを取ってきて削除するメソッド書く
という記事ばかり。

CloudFuctionsは、あまり動作が重くなる等の理由で非推奨みたいです。

なのでTutorialを見たりしつつ熟慮の結果、

func delete(collection: CollectionReference, batchSize: Int = 100, completion: @escaping (Error?) -> ()) {
        collection.limit(to: batchSize).getDocuments { (docset, error) in
            
            guard let docset = docset else {
                completion(error)
                return
            }
            
            guard docset.count > 0 else {
                completion(nil)
                return
            }
            
            let batch = collection.firestore.batch()
            docset.documents.forEach {batch.deleteDocument($0.reference)}
            batch.commit { (batchError) in
                
                if let batchError = batchError {
                    completion(batchError)
                }
                else {
                    self.delete(collection: collection, batchSize: batchSize, completion: completion)
                }
            }
        }
    }

この関数でうまく動きました。
completionの部分は、ご自身の作りたいものに合わせて適用させてください。

自分のメモ用であり、誰か一人でもいいのでお役に立てれば思います。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?