How to Get Reference to Document Array from Firestore

Viewed 90

This is the structure of my Firestore data right now:

enter image description here

I'm having trouble just accessing the favourites array. I seem to be accessing the collection and document just fine, but I can't seem to pull the favourites array in my code.

This is the relevant code in my data model

protocol UserFavouritesProtocol {
    
    func userFavouritesRetrieved(userFavourites:[UserFavourites])
    
}

var delegateTest:UserFavouritesProtocol?
    
    func getFavourites() {
        
        // Detach any listener
        listener?.remove()
        
        // Get a reference to the database
        let db = Firestore.firestore()
        
        var query:Query = db.collection("userFavourites")
        
        self.listener = query.addSnapshotListener({ (snapshot, error) in
            
            // Check for errors
            if error == nil && snapshot != nil {
                
                var userFavourites = [UserFavourites]()
                
                // Parse documents into mealPlans
                for doc in snapshot!.documents {
                    
                    let u = UserFavourites(
                        favouriteMealPlans: doc["favourites"] as? [String])

                    userFavourites.append(u)
                }
                
                // Call the delegate and pass back the notes in the main thread
                DispatchQueue.main.async {
                    self.delegateTest?.userFavouritesRetrieved(userFavourites: userFavourites)
                }
                
                
            }
            
        })
        
    }

This is my UserFavourites struct:

struct UserFavourites {
    
    var favouriteMealPlans:[String]?
    
}

At this point, how can I access the favourites array and call a reference to it? For example, I later want to see if a particular string is contained within my favourites array.

1 Answers

This will get you closer to your solution...

// struct
import FirebaseFirestore
struct UserFavourites {
    var favouriteMealPlans:[DocumentReference]?
}
// usage
let u = UserFavourites(favouriteMealPlans: doc["favourites"] as? [DocumentReference])
Related