Reputation: 1059
I am running into a peculiar issue when trying to simultaneously update values at different JSON branches in Firebase. The method provided in the documentation is perfect when it comes to creating new data,
let key = ref.child("posts").childByAutoId().key
let post = ["uid": userID,
"author": username,
"title": title,
"body": body]
let childUpdates = ["/posts/\(key)": post,
"/user-posts/\(userID)/\(key)/": post]
ref.updateChildValues(childUpdates)
but when I try to update data at multiple locations, it overwrites the other keys as if I was using setValue
. Here is my code.
let userID = Auth.auth().currentUser?.uid
userRef = Database.database().reference()
let vehicle = ["make":make.text,
"model": model.text,
"year":year.text,
"color":color.text,
"doors":doors.text]
let driver = ["currentEvent":eventID]
let childUpdates = ["/users/\(userID!)": driver,
"/status/\(userID!)/driverInfo/vehicle": vehicle]
userRef.updateChildValues(childUpdates)
I have also attached a picture which shows which data is and isn't being deleted when the function is executed.
I believe what I am trying to do is possible, and from what I understand the whole purpose of updateChildValues
is so that other children aren't overwritten.
Any help is appreciated. Thanks!
Upvotes: 1
Views: 1325
Reputation: 3606
Currently you are updating the objects with objects like this:
let childUpdates = ["/users/\(userID!)": driver,
"/status/\(userID!)/driverInfo/vehicle": vehicle]
You are giving the object (a dictionary) as the value of the childUpdates
dictionary. What this does is that replace all the children with this object meaning deleting the values for which you are sending nil for example in your case you have not included info
or infoThat
.
Now if you want to change only the values you want to give like only change the value of say make
and model
for vehicle
and currentEvent
for driver
, you have to give the particular path for these values
["/users/\(userID!)/currentEvent": eventID,
"/status/\(userID!)/driverInfo/vehicle/make": make.text, "/status/\(userID!)/driverInfo/vehicle/model": model.text]
I think this will update the values of these locations as you expected.
HTH...
Upvotes: 3
Reputation: 907
Correct me if I am mistaken, but if I understand what you're trying to do this might yield better results?
let userID = Auth.auth().currentUser?.uid
userRef = Database.database().reference()
let vehicle = ["make":make.text,
"model": model.text,
"year":year.text,
"color":color.text,
"doors":doors.text]
let driver = ["currentEvent":eventID]
let childUpdates = ["/users/": userID!),
"/status/\(userID!)/driverInfo": vehicle]
userRef.updateChildValues(childUpdates)
Upvotes: 0