将数组的所有项保存到 Firestore 数组

Save all items of an array to a Firestore array

此函数将数据保存到 Firestore。

static func createRecipe(docId:String, ingredientsAmount:Int, ingredientsName:String, completion: @escaping (Recipe?) -> Void) {
        
let db = Firestore.firestore()
        
        db.collection("recipes").document(docId).setData(
            [
             "title":title,
             "ingredients": [
                ["amount": ingredientsAmount,
                 "name": ingredientsName]
             ]
            ]) { (error) in
             }
    }

我正在使用 Codable 来解析来自外部源的数据。但是我一次只能从 ingredients 数组中保存 一项 。:

                do {
                    let decoder = JSONDecoder()
                    let recipe = try decoder.decode(Recipe.self, from: data!)

                    let uuid = UUID().uuidString
                    
                    createRecipe(
                        docId:uuid,
                        title: recipe.title ?? "",
                        ingredientsAmount: Int(recipe.ingredients?[0].amount ?? 0), // How to save EVERY item in recipe?
                        ingredientsName: recipe.ingredients?[0].name ?? "", // How to save EVERY item in recipe?
                    ) { recipeURL in
                        print("success")
                    }
                }
                catch {
                    print("Error parsing response data: \(error)")
                }

我可以说我正在成功解析 JSON 数据,因为以下输出 ingredients 数组中的每个项目:

                    for eachIngredient in recipe.ingredients! {
                        print(eachIngredient.name)
                        print(eachIngredient.amount)
                    }

如何将 ingredients 数组中的 每个 项目保存到 Firestore?

非常感谢任何指导!

我建议将 Ingredient 数组传递给函数,然后使用 map 创建字典:

static func createRecipe(docId:String, title: String, ingredients: [Ingredient], completion: @escaping (Recipe?) -> Void) {
    
    let db = Firestore.firestore()
    
    db.collection("recipes").document(docId).setData(
        [
            "title": title,
            "ingredients": ingredients.map { ["name": [=10=].name, "amount": [=10=].amount] }
        ])
        { (error) in
            //handle error
        }
}

请记住,还有一个 setData(from:) 需要一个 Codable,因此由于 RecipeCodable,您应该能够做到这一点(假设recipeRecipe 类型):

try db.collection("recipes").document(docId).setData(from: recipe)

Documentation 上面的函数