I have a collection of teams in my Firebase Cloud Firestore each of which have players. I have previously saved each of these players in an array inside the team document however found this to be inefficient and slow the app dramatically. After some research I have converted this array into a sub collection called players and want to access it the same way.
Here is my team and player model (simplified):
struct DBTeam: Identifiable, Codable{
@DocumentID var id: String?
var name: String
var colour: Int
var dateCreated: Date
var players: [DBPlayer] = [DBPlayer]()
var userID: String?
}
struct DBPlayer: Identifiable, Equatable, Codable{
var id: String = UUID().uuidString
var name: String
static func ==(lhs: DBPlayer, rhs: DBPlayer) -> Bool {
return lhs.name == rhs.name && lhs.id == rhs.id
}
}
I then use this repository to get all the data and feed it into my view model:
class TeamRepository: ObservableObject{
var db = Firestore.firestore()
@Published var teams = [DBTeam]()
init(){
loadData()
}
func loadData(){
let userID = Auth.auth().currentUser?.uid
db.collection("teams")
.order(by: "name")
.whereField("userID", isEqualTo: userID ?? "")
.addSnapshotListener { (querySnapshot, error) in
if let querySnapshot = querySnapshot{
self.teams = querySnapshot.documents.compactMap { document in
do{
let x = try document.data(as: DBTeam.self)
return x
}
catch{
print(error)
}
return nil
}
}
}
}
}
I have tried running this code again to see if by any chance it would work, but it didn't. By using these new sub collections, is this the most efficient way to store a bunch of players to one team and then reference them? If not any other suggestions? And how would I access these sub collections and store them into the array of players found in the DBTeam struct?