Hello together,
i do have the following database structure in firebase:
In general: each country has various clubs and each club has various teams with it’s own information.
I want to get for all clubs in a country all it’s teams with the individual team information. All my attempts failed. I’m driving crazy soon with the firebase database. What’s wrong with my coding or do I understand something fundamentally wrong.
Because I can’t query all these informations at once, i first query all clubs in a country. Within this query - once I have the club informations - I query for the teams in each club. And this query doesn’t work. I never get any documents back. The debugger jumps directly to the return line. Why. Is this a problem of synchronous/async task?
enclosed my code: I skipped all the definitions of the various structs. it’s not helpful anyway …
func getClubsInCountry(country: String) {
// Get a referene to the countries collection
let db = Firestore.firestore()
db.collection("countries").document("\(country)").collection("clubs")
.getDocuments() {[self] (querySnapshot, error) in
if let error = error {
print("Error getting documents: \(error)")
} else {
// Declare temporary lists for clubs
var clubs = [Club]()
for doc in querySnapshot!.documents {
var m = Club(id: doc.documentID,
name: doc["name"] as? String ?? "",
FireStorePath: doc["logoUrl"] as? String ?? "",
city: doc["city"] as? String ?? nil,
street: doc["street"] as? String ?? nil,
nr: doc["nr"] as? Int ?? nil,
zip: doc["zip code"] as? Int ?? nil,
web: doc["web"] as? String ?? nil)
// load teams which belong to the club
Task {
let test = try await getTeamsInClub(country: "\(country)", teamId: doc.documentID)
// m.teams = test
}
clubs.append(m)
print("m: \(m)")
}
}
DispatchQueue.main.async {
self.clubs = clubs
}
}
}
and the getTeamsInClub function …
func getTeamsInClub(country: String, teamId: String) async -> [Team] {
// Get a referene to the countries collection
let db = Firestore.firestore()
var teams = [Team]()
let dbPath = db.collection("countries").document("\(country)").collection("clubs").document("\(teamId)").collection("teams")
print("step 1")
dbPath.getDocuments() { (queryTeams, error) in
print("step 2")
if let error = error {
print("Error getting documents: \(error)")
} else {
// Declare temporary lists for teams belonging to the club
for doc in queryTeams!.documents {
var n = Team(id: doc.documentID,
name: doc["name"] as? String ?? "",
short: doc["short"] as? String ?? nil,
sport: doc["sport"] as? String ?? "")
teams.append(n)
}
}
}
return teams
}
when I try to find the error with debugging, I recognized, that the debugger never jumps to the line "print(“step 2”).
Appreciate your help very much!
Thanks, Peter