【问题标题】:Swift. Firestore, get document by referenceID迅速。 Firestore,通过referenceID获取文档
【发布时间】:2021-09-23 12:22:41
【问题描述】:

我是 Firestore 的新手,我不清楚如何通过引用来获取文档。例如

Users(collection):
Documents:
id: 123413 -> name: "test1", lastname: "test1"
id: we4321 -> name: "test2", lastname: "test2"
id: dsf234 -> name: "test3", lastname: "test3"
id: qwe124 -> name: "test4", lastname: "test4"

例如新系列

Animals(collection):
Documents:
id: rewerwr -> name: "Dog1", ref: "/Documents/123413"
id: sad3432 -> name: "Dog2", ref: "/Documents/we4321"
id: q4324da -> name: "Dog3", ref: "/Documents/dsf234"
id: safdsf2 -> name: "Dog4", ref: "/Documents/qwe124"

我如何为用户 id: 123413 -> name: "test1", lastname: "test1" 动物 id: rewerwr -> name: "Dog1", ref: "/Documents/123413" 获取信息

例如获取用户 - test1 会是这样的

Firestore.firestore().collection("Users").document("123413")

但是我怎样才能为这个用户获得动物呢?

【问题讨论】:

    标签: swift firebase google-cloud-firestore


    【解决方案1】:

    Firestore 可以一次从单个集合中加载数据,因为没有可用的连接。如果您想显示哪个动物属于哪个用户,您必须在您的代码中实现它。
    可以参考以下文章no sql data modeling

    【讨论】:

      【解决方案2】:

      我建议将您的 Animal 模型稍微更改为:

      struct User: Codable, Identifiable {
          @DocumentID var id: String?
          var name: String
          var lastName: String
      }
      
      struct Animal: Codable, Identifiable {
          @DocumentID var id: String?
          var name: String
          var owner: User
      }
      

      这样,当您检索Animal 文档时,您将在该文档中获得所有者信息。所以:

      animalDocumentReference.getDocument { docSnapshot, error in
          guard error == nil else { return }
          guard let animal = try? docSnapshot!.data(as: Animal.self) else { return }
          animal.owner  // You can now set this value to an @Published property or do whatever you want with it
      }
      

      如果这样更符合您的目的,您也可以反过来执行此操作。在User 中有一个名为pets 的属性。

      userDocumentReference.getDocument { docSnapshot, error in
          guard error == nil else { return }
          guard let user = try? docSnapshot!.data(as: User.self) else { return }
          user.pets  // You can now set this value to an @Published property or do whatever you want with it
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-10-26
        • 2021-01-28
        • 2018-04-23
        • 1970-01-01
        • 1970-01-01
        • 2019-04-19
        • 2021-11-19
        相关资源
        最近更新 更多