Learn Courses My Dashboard

How to save Map data to Firestore?

I’m extracting this data from an external source.

I wanted to save the extendedIngredients data (in the red box) to a Map type field in Firestore. For example:

I’m good for the simple field types like String, Int, and Bool:

let db = Firestore.firestore()
        
        db.collection("recipes").document("\(documentId)").setData(
            ["veryhealthy":veryhealthy,
             "cheap":cheap,
             "title":title,
            ]) { (error) in
             }

But I’m lost as to how to setData to the Map fields. These are my data structs:

struct Recipe: Codable {
    var veryHealthy: Bool?
    var cheap: Bool?
    var title: String?
    var extendedIngredients: [ExtendedIngredients?]
}

struct ExtendedIngredients: Codable {
    var aisle: String?
    var image: String?
    var name: String?
    var amount: Double?
    var unit: String?
}

How can I go about saving data to a Map field type with different data types nested?

I was able to figure this out. The following format worked:

let db = Firestore.firestore()
        
        db.collection("recipes").document("\(documentId)").setData(
            [ "veryhealthy":veryhealthy,
             "cheap":cheap,
             "title":title,
             "extendedIngredients": [
                ["aisle": extendedIngredientsAisle,
                 "amount": extendedIngredientsAmount,
                 "image": extendedIngredientsImage,
                 "name": extendedIngredientsName,
                 "unit": extendedIngredientsUnit],
             ]]) { (error) in
             }