【问题标题】:Swift Firestore Query through Object Keys通过对象键的 Swift Firestore 查询
【发布时间】:2018-05-24 12:59:39
【问题描述】:

我使用 Firestore 作为我的 iOS 应用后端。

我有这样的结构......

/users
     /userId
           name:"Bob"
           /likedPosts  //this is the object, not a collection
                "post1":true
                "post2":true

因此 - 我试图在用户的个人资料上显示“likedPosts”(帖子类)。

我不知道如何查询结果以获取用户喜欢的帖子,然后查询以显示每个帖子。

func getUserNameAndInfo() {
    if let user = Auth.auth().currentUser {
        // User is signed in

        // References to firebase
        let userFS = Firestore.firestore().collection("users")

        // Set the navigation title to users name
        userFS.document(user.uid).getDocument { (document, error) in
            if let userInfo = document {
                let firstName = userInfo["firstName"] as! String
                let lastName = userInfo["lastName"] as! String
                let likedPostsDictionary = userInfo.data()["likedPosts"] as! NSDictionary
                for (postId, _) in likedPostsDictionary {
                    self.userLikedPostsArray.append(postId as! String)
                    print(self.userLikedPostsArray)
                }

            } else {
                print("User name does not exist")
            }
        }
}

所以我可以获取帖子的所有 ID。但我对如何查询 Firestore 以获取这些 Id 的信息感到困惑。

【问题讨论】:

  • 您是如何将对象中的数据存储到 Firestore 中的。我还想以对象形式存储数据,例如 collection/document/collection/doument/invitess1(object) :金额:20,电话号码:1234567890 ..........你能告诉我如何存储吗数据到 Firestore

标签: ios swift firebase firebase-realtime-database google-cloud-firestore


【解决方案1】:

可以在帖子中保留用户点赞,查询当前用户ID等于true的地方。

/posts
     /postId
           /userLikes
                "user1": true
                "user2": true

let userFS = Firestore.firestore().collection("posts").where("userLikes/\(user.uid)", "===", true);

否则,使用您当前的结构,您将不得不单独获取每个帖子的数据。一旦你有你的帖子键数组,你至少可以用空单元格填充某种类型的列表视图。然后对于这些单元格中的每一个,您必须为其获取数据——您可以将此责任传递给单元格本身,使其在获取该帖子的数据后自行呈现。

您可以使用 post 键检索 post 文档,如下所示:

let postDocRef = db.collection("posts").document(postId);

postDocRef.getDocument { (document, error) in
    if let document = document {
        print("Document data: \(document.data())")
    } else {
        print("Document does not exist")
    }
}

【讨论】:

  • 这是唯一的选择吗?因为我的想法是 - 我的帖子数量有限 - 所以说它是 100。所以每个用户在他们的文档中最多只能有 100 个喜欢的帖子。但是,如果我将用户 ID 存储在帖子上,那么每个帖子可能有成百上千的用户 ID! Kinda 使该文档变得非常大
  • 好吧,您可以继续使用当前的结构,但您需要单独获取每个帖子的信息。另一种选择是将帖子的数据扇出到用户的likedPosts 中,而不是只为真——但仅是在提要中显示帖子所需的数据。如果这些数据中的任何一个是可变的并且可以由所有者更改,那么您将负责维护用户喜欢的帖子中的每个帖子。
  • 嗯,扇出方法似乎很有趣。由于帖子数量有限,而且用户无法更改,而且它们只是短文本,我认为这可能是一个不错的选择。会试一试。否则我想我宁愿单独获取每个帖子......仍然不确定如何做到这一点
猜你喜欢
  • 2019-06-23
  • 1970-01-01
  • 2020-07-09
  • 2019-01-09
  • 2014-01-08
  • 1970-01-01
  • 2020-01-09
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多