简体   繁体   English

如何通过获取其自动生成的 id 来删除 firestore 中的文档?

[英]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记住客户端上生成的 ID,并使用它来构建一个 DocumetnReference 来删除文档
  • 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.如果您无法使用其字段查询文档,并且您不知道它的 ID,那么您就有点卡住了,您需要更仔细地考虑您的数据模型。

How to delete a document or a sub-document in Firestore如何在 Firestore 中删除文档或子文档

To delete document you have to use delete() method要删除文档,您必须使用delete()方法

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.您需要知道要删除的collection namedocumentId Use your collection name and documentId to delete a document from a collection.使用您的collection namedocumentId从集合中删除文档。

Check this for more检查为更多

how to fetch its auto-generated id如何获取其自动生成的 id

To read all document in a collection you also need to know collection name .要读取集合中的所有文档,您还需要知道collection name

To read documents in a collection in Kotlin:要在 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 . document.id会给你每个documentId Use this documentId to delete a document.使用此documentId删除文档。

To read all documents from a collection check this要从集合中读取所有文档,请检查

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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