android - 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.
解决方案
要从 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
}
推荐阅读
- arrays - window.enableMouseFlow 在 componentDidMount() 中未定义,但在 render() 中可用
- mysql - 为什么数组不能保存在sql中
- javascript - 第二个异步等待函数未调用
- git - 如何通过命令行提交文件?
- java - 为什么 Java 不能在字符串中正确显示 unicode?
- java - 复合主键上的 Spring 数据和 @EntityGraph
- java - 捕获 servlet 中的语句引发的异常会停止执行(不显示输出)
- javascript - 如何将简单参数传递给模态
- c# - Task.Run 不在后台运行,而是在 Dispatcher 上运行
- vue.js - 从一个 Vue 组件发送到另一个组件的数据仍然是响应式的