[SWIFT] For those who have deleted a document in Firestore but the subcollection does not disappear

I was trying to implement the posting function of SNS using Firebase / Firestore.

However, even though I deleted the posts (posts / {postId}), the sub-collection (comments / {comment} does not disappear ...

Sorry for the cluttered notation of document and subcollection.

I did a lot of research there, but ... ・ Delete using Cloud Fuctions -Write a method to fetch the comment document separately and delete it Only articles.

CloudFuctions seems to be deprecated because it is too slow.

So, as a result of careful consideration while looking at the 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)
                }
            }
        }
    }

This function worked fine. Please apply the completion part according to what you want to make.

It's for my own memo, and I hope it helps because anyone can do it.

Recommended Posts

For those who have deleted a document in Firestore but the subcollection does not disappear
I put in a gem bullet (for those who don't notice the N + 1 problem themselves)
E: The repository'http://ppa.launchpad.net/daniel.pavel/solaar/ubuntu focal Release' does not have a Release file.
A must-see for those who don't understand the second Heroku deployment!
must not return in the for statement
For those who get the error Unprintable ASCII character found in source file
An introduction to Java that conveys the C language to those who have been doing it for a long time
Does the escape sequence (\) not work? (for Mac)
Guidelines for writing processing when a value exists / does not exist in Java Optional