Firestore:如何读取带有documentID的子集合数据?

时间:2019-02-09 21:57:13

标签: swift firebase google-cloud-firestore

我如何只能阅读当前的用户评论?对于“我自己的评论”页面。我的代码运行了,但是如果(where field:currentuid)不存在,则不会打印(“ no data”)。仅打印(“ documents.data()”)

    let db = Firestore.firestore()
    db.collection("tweets").getDocuments { (snapshot, error) in
        for document in snapshot!.documents {
            self.db.collection("tweets").document(document.documentID).collection("comments").whereField("uid", isEqualTo: self.uid).getDocuments(completion: { (snapshot2, error2) in
                for document2 in snapshot2!.documents {
                    print("\(document2.documentID) -> \(document2.data())")
                }
            })
        }
    }

1 个答案:

答案 0 :(得分:1)

我认为您正在寻找这个:

let db = Firestore.firestore()
db.collection("tweets").getDocuments { (snapshot, error) in
    for document in snapshot!.documents {
        self.db.collection("tweets").document(document.documentID).collection("comments")
          .whereField("uid", isEqualTo: self.uid).getDocuments(completion: { (snapshot2, error2) in
            if let err = err {
                print("Error getting documents: \(err)")
            } else {
                if snapshot2.isEmpty {
                    print("No comments from \(self.uid) found")
                } else {
                    for document2 in snapshot2!.documents {
                        print("\(document2.documentID) -> \(document2.data())")
                    }
                }
            }
        })
    }
}

请注意,有关集合组查询的工作正在进行中,这将使您可以对所有名为comments的集合进行单个查询。