简体   繁体   中英

Cannot delete multiple documents in Firebase Cloud Firestore

I'm developing an Android Q&A application. I'd like users to delete all of their posts when they delete their accounts. I found this article so I tried the same code, but it didn't work. This is my code.

@Composable
fun DeleteAccounts(navController: NavController, uid: String) {
    val db = Firebase.firestore

    Button(
                    onClick = {
                        val batch = db.batch()
                        db.collection("posts")
                            .whereEqualTo("uid", "$uid")
                            .get().result.forEach {
                                batch.delete(it.reference)
                            }
                        batch.commit()
                            .addOnSuccessListener {
                                navController.navigate("Login")
                            }
                    }

And this is the error message.

java.lang.IllegalStateException: Task is not yet complete
    at com.google.android.gms.common.internal.Preconditions.checkState(com.google.android.gms:play-services-basement@@18.1.0:2)
    at com.google.android.gms.tasks.zzw.zzf(com.google.android.gms:play-services-tasks@@18.0.1:1)
    at com.google.android.gms.tasks.zzw.getResult(com.google.android.gms:play-services-tasks@@18.0.1:1)
    at com.example.**app.DeleteAccountsViewKt$DeleteAccounts$1$5$1$1.invoke(DeleteAccountsView.kt:124)
    at com.example.**app.DeleteAccountsViewKt$DeleteAccounts$1$5$1$1.invoke(DeleteAccountsView.kt:117)

What am I doing wrong? Thank you.

I tried another code and this works. But I don't know if this is correct.

val batch = db.batch()
                        db.collection("posts")
                            .whereEqualTo("uid", uid)
                            .get()
                            .addOnSuccessListener { result ->
                                for (document in result) {
                                    batch.delete(document.reference)
                                }
                  
              batch.commit()

It's possible there are too many documents to delete in your Android client. If you read the documentation here: https://firebase.google.com/docs/firestore/manage-data/delete-data#collections It says that batch deleting documents in a client is not recommended.

You could try writing a Cloud Function to batch delete a lot of documents instead.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM