简体   繁体   中英

How to delete a document in firestore by fetching its autogenerated id?

如何删除 Firestore 中的文档或子文档以及如何获取其自动生成的 ID,以便当用户长按时,在列表中的行项目上选择“删除”,以便他/她可以从中删除文档应用程序的用户界面很容易。

You can't "fetch" an existing random document. In order to delete a document you need to do either one of two things:

  • Remember the generated ID on the client, and use that to build a DocumetnReference to delete the document
  • Query for the document using a field that you know in that document, then delete it after the query. Or simply query for all documents and work with them as a group.

If you can't query for a document using its fields, and you don't know it's ID, you're kind of stuck, and you will need to think more carefully about your data model.

How to delete a document or a sub-document in Firestore

To delete document you have to use delete() method

Kotlin Code :

db.collection("your_collection_name").document("documentId")
        .delete()
        .addOnSuccessListener { Log.d(TAG, "DocumentSnapshot successfully deleted!") }
        .addOnFailureListener { e -> Log.w(TAG, "Error deleting document", e) }

You need to know your collection name and documentId you want to delete. Use your collection name and documentId to delete a document from a collection.

Check this for more

how to fetch its auto-generated id

To read all document in a collection you also need to know collection name .

To read documents in a collection in Kotlin:

db.collection("your_collection_name")
        .get()
        .addOnSuccessListener { result ->
            for (document in result) {
                Log.d(TAG, "${document.id} => ${document.data}")
            }
        }
        .addOnFailureListener { exception ->
            Log.d(TAG, "Error getting documents: ", exception)
        }

document.id will give you every documentId . Use this documentId to delete a document.

To read all documents from a collection check this

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