Reputation: 2708
Is it possible to save data as transactions as per firebase docs, but without overwriting the whole node? I would like to know if there is any equivalent for updateChildValues
when calling runTransactionBlock
. The only option I see in the docs with runTransactionBlock
is to overwrite the existing data at /path/somepath.
Please provide alternative or I'd appreciate your advice if I am on a wrong path here and I should not key:value to existing data.
Upvotes: 0
Views: 416
Reputation: 181
The trick is to check the return value and if its nil append the initial value or else update it,
articleRef.runTransactionBlock({ (currentData: MutableData) -> TransactionResult in
if var viewInfo = currentData.value as? [String : AnyObject] {
var viewCount = viewInfo["viewCount"] as? Int ?? 0
viewCount += 1
viewInfo["viewCount"] = viewCount as AnyObject?
//Set value and report transaction success
currentData.value = viewInfo
return TransactionResult.success(withValue: currentData)
}
else { //Iarticle doesnt exists, add inital value
currentData.value = ["viewCount": 1]
}
return TransactionResult.success(withValue: currentData)
}) { (error, committed, snapshot) in
if let error = error {
print(error.localizedDescription)
}
}
Upvotes: 1
Reputation: 598740
When you run a transaction, your callback/handler is invoked with the existing data in the location. So all you do is update the properties that you want modified and return that combination from your callback/handler.
There is no way to just tell the client what properties to update. But since your handler is invoked with the existing value from the location it's updating, that should not lead to inefficiencies in the code.
If you're having trouble making this work, please post a single, minimal-but-complete code snippet that reproduces the problem.
Upvotes: 2