如何使用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

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

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

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
}
}
}
}
}

最新更新