如何更新Firebase DB中的特定值
我正在关注这个文件 。 以下是我的代码更新:
func updateDealResultToServer(key:String,dealResult : String) { let post = ["dealResul": dealResult] let childUpdates = ["/komal_xyz/\(key)": post ] rootRef.updateChildValues(childUpdates) }
这是我的Firebase数据库结构:
我只想改变dealResult
的值。 每当我尝试运行以上代码为特定的子节点像1473670100726
,除了dealResul
其他值被删除。
要在Firebase实时数据库的特定节点上更新值,请使用: –
-
您可以使用
runTransactionBlock:
func updateTotalNoOfPost(completionBlock : (() -> Void)){ let prntRef = FIRDatabase.database().reference().child("komal_kyz").child(your_AuroID).child("dealResul") prntRef.runTransactionBlock({ (resul) -> FIRTransactionResult in if let dealResul_Initial = resul.value as? Int{ //resul.value = dealResul_Initial + 1 //Or HowSoEver you want to update your dealResul. return FIRTransactionResult.successWithValue(resul) }else{ return FIRTransactionResult.successWithValue(resul) } }, andCompletionBlock: {(error,completion,snap) in print(error?.localizedDescription) print(completion) print(snap) if !completion { print("Couldn't Update the node") }else{ completionBlock() } }) }
在调用这个函数时:
updateTotalNoOfPost{ print("Updated") }
-
或者只是调用
updateValues
let prntRef = FIRDatabase.database().reference().child("komal_kyz").child(your_AuroID) prntRef.updateChildValues(["dealResul":dealResult])
PS: – 如果你只想增加一个特定的节点, .updateChildValues
使用runTransactionBlock:
而不是.updateChildValues
。 另请阅读: – https://stackoverflow.com/a/39458044/6297658
我build议使用setValue
进行单独的子更新(请记住,我使用的是Swift 3,可能会适用轻微的语法更改,但是您应该可以):
rootRef.child("komal_kyz").child(key).setValue(["dealResul":dealResult])