Home > Mobile >  Swift snapshot and mapping a single document from Firestore
Swift snapshot and mapping a single document from Firestore

Time:12-31

I'm trying with no success on finding a way to retrieve only a single document instead of an array of documents from Firestore below is the code that I'm using for fetching ad array. Someone has suggestion on how to change fro getting only a document?

@Published var plantData: [PlantDataModel] = [] -> here I don't want an array

func loadData() {
        print("FIREBASE LOADING DETAIL DATA VIEW")
        db.collection("plantsData").whereField("plantId", isEqualTo: plant.idPlant).addSnapshotListener { querySnapshot, error in
            if let querySnapshot = querySnapshot {
                self.plantData = querySnapshot.documents.compactMap { document  in
                    do {
                        let x = try document.data(as: PlantDataModel.self)
                        return x
                    } catch let error {
                        print("Errore fetching data: \(error)")
                    }
                    return nil
                }

            }
        }
    }

thank you

CodePudding user response:

Replace

            self.plantData = querySnapshot.documents.compactMap { document  in
                do {
                    let x = try document.data(as: PlantDataModel.self)
                    return x
                } catch let error {
                    print("Errore fetching data: \(error)")
                }
                return nil
            }

With

            if let first = querySnapshot.documents.first { 
                do {
                    let x = try first.data(as: PlantDataModel.self)
                    self.plantData.append(x)
                } catch let error {
                    print("Errore fetching data: \(error)")
                } 
            }
  • Related