iOS Firebase -How to remove children with same key

2020-05-09 12:06发布

问题:

I have a ref named Following. Under that ref there are 2 different userIds who are following the same user. If the user they are both following wants to delete their account I want to delete them from the Following node. Multi location update doesn't seem correct to achieve this.

How can it be done?

User kk8qFOIw... is the user who is deleting their account. Once deleted their keys should be removed from the other user's nodes.

回答1:

This is how you can do it :

First get all the nodes where your id = 1 , then run a multipath update and set them to empty.

 let userId = "yourUserId"
    self.ref.child("following").queryOrdered(byChild: userId).queryEqual(toValue: 1).observeSingleEvent(of: .value) { (snasphot) in
        guard let value = snasphot.value as? [String : Any] else {return}


        var multipathUpdate = [String:Any]()
        value.keys.forEach({ (key) in
            multipathUpdate["following/"+key+"/"+userId] = [:]
        })
        self.ref.updateChildValues(multipathUpdate, withCompletionBlock: { (err, ref) in

        })
    }