首页 > 解决方案 > 如何使用 Firestore 执行组集合查询?(IOS)

问题描述

大家好,这是我第一次在这里问问题,所以如果发布不正确等等......我提前道歉。我正在做一个项目,我去的大学的学生将能够请求常驻顾问为他们解锁房间。我被困在如何查询整个(根)集合以查找具有包含与我的集合 ID 匹配的值的字段的子集合。我在 Stack、Firebase 上看到了很多资源,并且我尝试实现它们,但我没有成功。

这是一张图片:

访问子集合

我的代码片段是:

db.collectionGroup("Dorms").whereField("UID", isEqualTo: UID).getDocuments { (snapshot, error) in    

// here is where i'd like to gather the fields subcollection/document and then store them as variables

提前感谢您的任何帮助和建议。非常感谢!

标签: iosswiftfirebasegoogle-cloud-firestore

解决方案


这是我第一次发布答案,所以我希望这会有所帮助,但是根据我在查询集合中的文件时的经验,我创建了forloopthen 使用 if let 语句从文档中获取变量

var someVariable : Int


db.collectionGroup("Dorms").whereField("UID", isEqualTo: "UID").getDocuments { (snapshot,  error) in
        if let e = error {
            //this is printing the error if there is one getting the documents
            print("There was an error getting the documents \(e)")
        } else {
            if let dorms = snapshot?.documents { //accesses all the documents in the collection
                for doc in dorms {
                    let data = doc.data() //Gets all the information in the document
                    //Here you would use an if let to create variables from the information in the data
                    //For example
                    if let dormRoomNumber = data["dormRoomNumber"]/*You'll put the name of your field in here, so whatever you have named it in firestore*/] as? Int //make sure the the data type here mathces the data type in your firestore database
                    {
                        someVariable = dormRoomNumber
                    }
                }
            }

        }
    }

推荐阅读