首页 > 解决方案 > How To Delete Firestore Collection From Android

问题描述

Issue

I'm looking for a temporary solution to delete Collections from the client side for my proof of concept. I will eventually refactor this onto the server as recommended.

I'm adding the function to delete all of a particular Firestore user's account information including their saved Collections of content in the app. Per the Firestore documentation there is no prescribed approach to doing so from the client as it is recommended to handle this on the server.

标签: androidfirebasegoogle-cloud-firestore

解决方案


要从 Cloud Firestore 数据库中删除整个集合或子集合,您需要检索集合或子集合中的所有文档并将其删除。

如果您有较大的集合,您可能希望以较小的批次删除文档以避免内存不足错误。所以你应该重复这个过程,直到你删除了整个集合或子集合。

即使 Firebase 团队不推荐删除操作,因为它具有负面的安全性和性能影响,您仍然可以执行此操作,但仅限于small collections. 如果您需要删除整个 Web 集合,请仅从受信任的服务器环境中执行此操作。

对于 Kotlin,请使用以下函数:

private fun deleteCollection(collection: CollectionReference, executor: Executor) {
    Tasks.call(executor) {
        val batchSize = 10
        var query = collection.orderBy(FieldPath.documentId()).limit(batchSize.toLong())
        var deleted = deleteQueryBatch(query)

        while (deleted.size >= batchSize) {
            val last = deleted[deleted.size - 1]
            query = collection.orderBy(FieldPath.documentId()).startAfter(last.id).limit(batchSize.toLong())

            deleted = deleteQueryBatch(query)
        }

        null
    }
}

@WorkerThread
@Throws(Exception::class)
private fun deleteQueryBatch(query: Query): List<DocumentSnapshot> {
    val querySnapshot = Tasks.await(query.get())

    val batch = query.firestore.batch()
    for (snapshot in querySnapshot) {
        batch.delete(snapshot.reference)
    }
    Tasks.await(batch.commit())

    return querySnapshot.documents
}

推荐阅读