I'm trying to create a small app for car maintenance notes. Now I want to fetch all car maintenance records from Firestore Database, but my code doesn't work correctly. I have a collection "Vehicles". This collection stores all vehicle documents. Every vehicle has a subcollection "MaintenanceItems", and inside this subcollection, there are some documents. I need to fetch all documents inside "MaintenanceItems" for every vehicle and display them on the screen. I wrote the class "ExpensesManager" for it, but there is a problem. After adding a new MaintenanceItem I get duplicates.
import Foundation
import FirebaseFirestore
import FirebaseFirestoreSwift
class ExpensesManager: ObservableObject {
private(set) var expenses = [MaintenanceItem]()
@Published private(set) var expenseItems = [MaintenanceItem]()
let db = Firestore.firestore()
init(vehicles: [Vehicle]) {
fetchExpenseItems(vehicles: vehicles)
print("ExpensesManager init func succeess!")
}
func fetchExpenseItems(vehicles: [Vehicle]) {
for vehicle in vehicles {
guard let vehicleID = vehicle.id else {
print("VehicleID is not found")
return
}
db.collection("Vehicles").document("\(vehicleID)").collection("MaintenanceItems").addSnapshotListener { querySnapshot, error in
guard let documents = querySnapshot?.documents else {
print("Error fetching documents: \(String(describing: error))")
return
}
print("Documents are received")
self.expenses = documents.compactMap { document -> MaintenanceItem? in
do {
return try document.data(as: MaintenanceItem.self)
} catch {
print("Error decoding document into Expense: \(error)")
return nil
}
}
for expense in self.expenses {
self.expenseItems.append(expense)
}
print("Expenses array is completed")
}
}
}
}
CodePudding user response:
I need to fetch all documents inside "MaintenanceItems" for every vehicle and display them on the screen.
If you need to get all documents that exist inside all MaintenanceItems
collections, basically the maintenance items of all vehicles, then you should consider using a collection group query:
db.collectionGroup("MaintenanceItems").addSnapshotListener { /*...*/ }