如何更新Firebase DB中的特定值 [英] How to update particular value of child in Firebase DB

查看:129
本文介绍了如何更新Firebase DB中的特定值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在关注这个


I am following this document. Following is my code for update:

func updateDealResultToServer(key:String,dealResult : String)
{

    let post = ["dealResul": dealResult]
    let childUpdates =
        ["/komal_xyz/\(key)": post
        ]

    rootRef.updateChildValues(childUpdates)

}

This Is my Firebase database structure:

I want to only change the value for dealResult. Whenever I try to run above code for particular child node like 1473670100726, other value except dealResul is deleted.

解决方案

For Updating values at a particular node in Firebase Realtime Database, use:-

  • You can either use 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()
            }
        })
    
     }
    

    While calling this function:-

    updateTotalNoOfPost{
           print("Updated")
          }
    

  • Or just call updateValues

        let prntRef  = FIRDatabase.database().reference().child("komal_kyz").child(your_AuroID)
        prntRef.updateChildValues(["dealResul":dealResult]) 
    

PS:- Prefer using runTransactionBlock: instead of .updateChildValues if you only want to increment a particular node. Also read this: -https://stackoverflow.com/a/39458044/6297658

这篇关于如何更新Firebase DB中的特定值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆