如何使用 SwiftUI 中的 documentID 删除特定的 Cloud Firestore 文档?

How can I delete a specific Cloud Firestore document using the documentID in SwiftUI?

我正在使用一个列表来显示用户通过表单输入的伤害数据,这些数据已成功添加到 Cloud Firestore。我现在想添加一个删除功能,删除列表中选中的伤害

这是我的 Injury 结构:

import SwiftUI
import FirebaseFirestoreSwift

struct Injury: Identifiable, Codable {
  @DocumentID var id: String? = UUID().uuidString
  var userId: String?
  var specificLocation: String
  var comment: String
  var active: Bool
  var injuryDate: Date
  var exercises: String
  var activity: String
  var location: String    
}

我的InjuriesViewModel:

import SwiftUI
import Firebase
import FirebaseFirestore
import FirebaseFirestoreSwift

class InjuriesViewModel: ObservableObject {    
  @Published var injuries = [Injury]()
    
  private var db = Firestore.firestore()

  func fetchData () {
    let userId = Auth.auth().currentUser?.uid
    
    db.collection("injuries")
      .order(by: "injuryDate", descending: true)
      .whereField("userId", isEqualTo: userId)
      .addSnapshotListener{ (querySnapshot, error) in
        guard let documents = querySnapshot?.documents else {
          print("no documents")
          return
        }
                
        self.injuries = documents.compactMap { (queryDocumentSnapshot) -> Injury? in
          return try? queryDocumentSnapshot.data(as: Injury.self)
        }
    }
  }
}

我的InjuryViewModel(这里是加减伤功能的地方,但是我不知道怎么填写文档字段):

import SwiftUI
import Firebase

class InjuryViewModel: ObservableObject {    
  @Published var injury: Injury = Injury(id: "", userId: "", specificLocation: "", comment: 
    "", active: false, injuryDate: Date(), exercises: "", activity: "", location: "")
    
  private var db = Firestore.firestore()

  func addInjury(injury: Injury) {
    do {
      var addedInjury = injury
      addedInjury.userId = Auth.auth().currentUser?.uid
      let _ = try db .collection("injuries").addDocument(from: addedInjury)
    }
    catch {
      print(error)
    }
  }
      
  func deleteInjury(injury: Injury) {
    db.collection("injury").document(??).delete() { err in
      if let err = err {
        print("Error removing document: \(err)")
      } 
      else {
        print("Document successfully removed!")
      }
    }
  }
    
  func save () {
    addInjury(injury: injury)
  }
    
  func delete () {
    deleteInjury(injury: injury)
  }
}

在此先感谢您的帮助!

这是我所在的位置:

  func addInjury(injury: Injury) {        
    do {
      var addedInjury = injury
      addedInjury.userId = Auth.auth().currentUser?.uid
      let documentRef = try db.collection("injuries").addDocument(from: addedInjury)
      addedInjury.id = documentRef.documentID
      print(documentRef.documentID)
    }
    catch {
      print(error)
    }
  }

  func deleteInjury(injury: Injury) {
    db.collection("injuries").document(injury.id!).delete() { err in
    if let err = err {
      print("Error removing document: \(err)")
    }
    else {
      print("Document successfully removed!")
    }
  }
}

deleteInjury 中,您只需访问您的视图模型持有的当前 InjurydocumentID

func deleteInjury(injury: Injury) {
  db.collection("injury").document(injury.id).delete() { err in
    if let err = err {
      print("Error removing document: \(err)")
    } 
    else {
      print("Document successfully removed!")
    }
  }
}