【问题标题】:How can I query using .whereField for a member of an Array?如何使用 .whereField 查询数组的成员?
【发布时间】:2020-06-30 00:43:50
【问题描述】:

我正在尝试查询一组用户 ID,这些用户 ID 保存在我的 Firestore 数据库中的一个数组中。这是有效的,它成功地在我的控制台中显示了 UID。然后,我想找到字段“uid”何时等于数组的成员。这是它停止工作的地方。我似乎无法将“uid”与 followUID 数组的成员实际匹配。

我在下面详细说明了我的代码。任何帮助将不胜感激:

 func getFollowingPosts() {
                db.collection("iAmFollowing").document(currentUserID!).getDocument { (document, error) in
                if error != nil {
                    print("ERROR")
                } else {
                    if let document = document {
                        let followedUID = document["uid"] as? Array ?? [""]
                        print("followed UID is \(followedUID)")
                        
                        
                        let searchedInfo = self.db.collection("posts").whereField("uid", isEqualTo: followedUID)
                        

                       let refinedInfo = searchedInfo.order(by: "Alpha", descending: true)
                       refinedInfo.getDocuments { (documents, error) in
                                guard let documents = documents else {
                                    print("NO DOCUMENTS")
                                   return
                                }
                                for documents in documents.documents {
                                let title = documents.get("Title") as! String
                                let content = documents.get("Content") as! String
                                let username = documents.get("username") as! String
                                let postID = documents.get("postID")
                                let counter = documents.get("counter")
                                self.titleArray.append(title)
                                self.contentArray.append(content)
                                self.usernameArray.append(username)
                                self.postIDArray.append(postID as! Int)
                                self.effectsLabelArray.append(counter as! Int)
                                print(self.titleArray)
                                self.tableView.reloadData()
                                }
                            }
                            }
                       }
                    }
                    
                    }
    

谢谢!

【问题讨论】:

    标签: ios swift firebase google-cloud-firestore


    【解决方案1】:

    您的查询要求 uid 字段与给定值完全相等的文档:

    db.collection("posts").whereField("uid", isEqualTo: followedUID)
    

    如果 uid 字段是一个数组,这个查询将永远找不到任何东西,因为数组永远不等于字符串。

    如果您想查看某个字段值是否是多个值之一,请使用"in" query

    db.collection("posts").whereField("uid", in: followedUID)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-02-22
      • 1970-01-01
      • 2014-08-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多