【问题标题】:How do I map my ViewModel's ID to the Document ID in Firestore?如何将 ViewModel 的 ID 映射到 Firestore 中的文档 ID?
【发布时间】:2021-07-01 05:24:03
【问题描述】:

我在这里有获取数据代码,但我不明白在不将 ID 设置为文档 ID 的情况下如何删除文档。我在这里学习本教程。 https://medium.com/swift-productions/swiftui-easy-to-do-list-with-firebase-2637c878cf1a 我假设我需要在数据映射中这样做,但我不明白如何使用这段代码。我想从 SwiftUI 列表中删除一个待办事项,并删除它的整个 Firestore 文档。

func fetchData() {
    db.collection("todos").addSnapshotListener { (querySnapshot, error) in
        guard let documents = querySnapshot?.documents else {
            print("No documents")
            return
        }
        
        self.todos = documents.map { (QueryDocumentSnapshot)  -> Todo in
            let data = QueryDocumentSnapshot.data()
            let todoDetails = data["todo"] as? String ?? ""
            
            return Todo(todoDetais: todoDetails)
        }
    }
}

查看模型

struct Todo: Codable, Identifiable {
var id: String = UUID().uuidString
var todoDetais: String?

}

【问题讨论】:

  • 为什么不想使用文档 ID?您将需要某种标识符。最好的办法是在 Firestore 文档中添加所需的 UID。然后,当首先删除时,您必须获取该文档 ID,然后删除,这使其成为一个两步过程。我建议在模型中添加文档 ID,例如 return Todo(todoDetais: todoDetails, firestoreID: docID),以便我可以在需要时访问它。
  • 我仍然不确定这如何将视图模型的 ID 映射到 Firestore 的文档 ID。 @Dharmaraj

标签: firebase firebase-realtime-database google-cloud-firestore swiftui


【解决方案1】:

我建议使用 Codable 将您的 Firestore 文档映射到 Swift 结构。这将使您的代码更容易编写,更不容易出错,并且更安全。

具体来说,它还允许您使用 @DocumentID 将 Firestore 文档 ID 映射到 Swift 结构的 id 属性。

这是一个简单的例子:

struct Book: Codable {
  @DocumentID var id: String? 
  var title: String
  var numberOfPages: Int
  var author: String
}

func fetchBook(documentId: String) {
  let docRef = db.collection("books").document(documentId)
  docRef.getDocument { document, error in
    if let error = error as NSError? {
      self.errorMessage = "Error getting document: \(error.localizedDescription)"
    }
    else {
      if let document = document {
        do {
          self.book = try document.data(as: Book.self) 
        }
        catch {
          print(error)
        }
      }
    }
  }
}

有关更多详细信息,请参阅this comprehensive guide 我写的关于将 Firestore 文档映射到 Swift 结构(以及返回)的文章。

有关如何从 SwiftUI 应用中删除 Firestore 文档的更多信息,请查看this article

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-11-09
    • 1970-01-01
    • 1970-01-01
    • 2018-06-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多