I have a collection (userRecipes), which should contain sub collection's containing individual recipes. (I save each sub collection with the recipe's name, in this instance it's cheese)
My issue is whenever I save each sub collection, it overwrites the previous recipe.(ie. if I saved another recipe, it would overwrite cheese) In a perfect world, I would like each sub collection saved without overwriting the existing collections. Can't see why updateData isn't working in this instance, unless I'm misinterpreting firebase's docs.
struct SaveRecipeButton: View {
@EnvironmentObject var recipeClass: Recipe
func saveRecipe (){
//saves from object in RecipeModel to arrays
var ingredientArr:[String:String] = [:]
var directionArr: [String] = []
//goes through both ingredients and directions
for item in recipeClass.ingredients {
ingredientArr[item.sizing] = item.description
}
for item in recipeClass.directions {
directionArr.append(item.description)
}
//sets up firebase w/ recipe as subcollection
let newRecipeInfo: [String: Any] = [
"userRecipes": [
recipeClass.recipeTitle: [
"recipeTitle": recipeClass.recipeTitle,
"recipePrepTime": recipeClass.recipePrepTime,
"createdAt": Date.now,
"ingredientItem": ingredientArr,
"directions": directionArr
]
]
]
//grab current user
guard let uid = FirebaseManager.shared.auth.currentUser?.uid else {
return
}
//updates data in firebase
do {
try FirebaseManager.shared.firestore.collection("users").document(uid).updateData(newRecipeInfo)
print("successfully save to database")
} catch let error {
print("Error writing recipe to Firestore: \(error)")
}
}
var body: some View {
Button(action: {
}){
HStack{
Image(systemName: "pencil").resizable()
.frame(width:40, height:40)
.foregroundColor(.white)
Button(action: {
saveRecipe()
}){
Text("Save Recipe")
.font(.title)
.frame(width:200)
.foregroundColor(.white)
}
}
.padding(EdgeInsets(top: 12, leading: 100, bottom: 12, trailing: 100))
.background(
RoundedRectangle(cornerRadius: 10)
.fill(
Color("completeGreen")))
}
}
}
CodePudding user response:
Your userRecipes
is a field in a document, not a collection. When you call updateData
it replaces the existing value in the userRecipes
with the values you specify.
If you want to update a value in a nested field, you can do so using dot notation. So:
FirebaseManager.shared.firestore.collection("users").document(uid).updateData([
"userRecipes.Cheese.recipeTitle": "Cheesiest"
])
Also see this similar question for JavaScript which I gave a few hours ago: Adding rating to a movie using Firebase and React