首页 > 解决方案 > 循环通过 Firestore 数据库

问题描述

我希望循环通过我的 Firestore DB 以获取与我的所有文档组合的总距离

Firestore 图像

我目前正在使用此查询来获取文档总数

    firebaseDB.collection("journey").document(key).collection("journeys")
        .getDocuments() { (querySnapshot, err) in
            if let err = err {
                print("Error getting documents: \(err)")
            }
            else
            {
                var totalJourney = 0
                for document in querySnapshot!.documents {
                    totalJourney += 1
                    print("\(document.documentID) => \(document.data())");
                }
                print("totalJourney = \(totalJourney)");
                self.totalJourney.text = String(totalJourney)
            }
        }

标签: iosswiftfirebasegoogle-cloud-firestore

解决方案


您的代码并不遥远,但您的代码中缺少一些东西 - 例如,读取每个节点中的距离子节点并将它们相加。下面是一些示例代码,用于输出行程数和总里程数。

我的结构比你的略浅,我使用了一个名为“英里”的子节点而不是距离,但概念是一样的。

func readJourneys() {
    self.db.collection("journeys").getDocuments() { (querySnapshot, err) in
        if let err = err {
            print("Error getting documents: \(err)")
        } else {
            let count = querySnapshot!.documents.count

            var totalMiles = 0
            for document in querySnapshot!.documents {
                //let journeyId = document.documentID
                let miles = document.get("miles") as! Int
                totalMiles += miles
            }
            print("There were: \(count) journeys covering: \(totalMiles) miles")
        }
    }
}

输出是

There were: 3 journeys covering: 20 miles

推荐阅读