I have recently started learning Swift and Firestore and i have a question around how to structure a database for what im doing.
At the moment i have the following structure. enter image description here
What i would like to do is to fetch the newest collection with a specific ownerID in the above structure am i right in suggesting i would have to fetch all documents and add it to an array and go from there, or would it work better with a structure where the document's id is the ownerID. I feel like fetching all the documents is a real waste and would become really problematic if there were lots of documents.
It maybe obvious that im a little lost here. Thanks in advance Luke
At the moment i have fetched the documents and sorted them from newest to oldest but now that i need the newest one with a specific ownerID i feel thats its a really clumsy way to do it.
import Foundation import FirebaseFirestore import FirebaseFirestoreSwift
class ThingManager: ObservableObject {
@Published private(set) var things: [Things] = []
@Published private(set) var lastThingId = ""
@Published var firstElement = ""
let db = Firestore.firestore()
init(){
getThings()
}
func getThings() {
db.collection("Things").addSnapshotListener { querySnapshot, error in
guard let documents = querySnapshot?.documents else {
print("Error: fetching documents \(String(describing: error))")
return
}
self.things = documents.compactMap{ document -> Things? in
do {
return try document.data(as: Things.self)
} catch {
print("Error: decoding document into Thing failed: \(error)")
return nil
}
}
self.things.sort { $0.timestamp > $1.timestamp }
if let Element = self.things.first?.thing {
self.firstElement = Element
print("First Element : \(self.firstElement)")
}
if let id = self.things.last?.id {
self.lastThingId = id
}
}
}