簡體   English   中英

如何通過獲取其自動生成的 id 來刪除 firestore 中的文檔?

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

如何刪除 Firestore 中的文檔或子文檔以及如何獲取其自動生成的 ID,以便當用戶長按時,在列表中的行項目上選擇“刪除”,以便他/她可以從中刪除文檔應用程序的用戶界面很容易。

您無法“獲取”現有的隨機文檔。 要刪除文檔,您需要執行以下兩項操作之一:

  • 記住客戶端上生成的 ID,並使用它來構建一個 DocumetnReference 來刪除文檔
  • 使用您在該文檔中知道的字段查詢該文檔,然后在查詢后將其刪除。 或者簡單地查詢所有文檔並將它們作為一個組進行處理。

如果您無法使用其字段查詢文檔,並且您不知道它的 ID,那么您就有點卡住了,您需要更仔細地考慮您的數據模型。

如何在 Firestore 中刪除文檔或子文檔

要刪除文檔,您必須使用delete()方法

科特林代碼

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

您需要知道要刪除的collection namedocumentId 使用您的collection namedocumentId從集合中刪除文檔。

檢查為更多

如何獲取其自動生成的 id

要讀取集合中的所有文檔,您還需要知道collection name

要在 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會給你每個documentId 使用此documentId刪除文檔。

要從集合中讀取所有文檔,請檢查

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM