Dravidian Dravidian - 2 months ago 18
iOS Question

Firebase,Swift: Retrieving only those `autoID` node's which have a specific key

Question--->


  1. Is there a way to retrieve a node whose key is an
    autoID
    , which Might contain a particular key. Like in below JSON structure i have a child node
    powers
    inside some
    autoID
    's, not all of them, I want to retrieve only those nodes which have key
    powers
    in them not knowing what corresponding
    value
    might be .

  2. In the below two suggested approach which one would consume less BandWidth?



My JSON Tree

node1
-node12
-autoId1

expo: "5122223333"
users:
-MqrvHRBTRcPzrvAOdkklBzeFW7E2
firstName: "Margery"
lastName: "Lady"
-autoId2
powers: "Triple3"
expo: "2123338983"
users:
-LqrsadaDs12BTRcPzrvABzeFW7E2
firstName: "Tyrion"
lastName: "Imph"
-node21
-autoId3
powers: "Triple"
expo: "5123333"
users:
-MqrvHRBTRcPzrvAOdkklBzeFW7E2
firstName: "Cersie"
lastName: "Lady"
-autoId4
powers: "Quad"
expo: "2128983"
users:
-LqrsadaDs12BTRcPzrvABzeFW7E2
firstName: "Sansa"
lastName: "Lady"


What Have I Tried--->


  • Retrieve the entire
    node12
    and then checking which of the autoId's have a particular
    key
    . for eg lets say powers: "Triple3"

    let prntRef = FIRDatabase.database().reference().child("node1").child("node12")
    prntRef.observeSingleEventOfType(.Value, withBlock: {(snap) in

    if snap.exists(){

    for each in snap.value as! [String:AnyObject]{

    prntRef.child(each.0 as! String).child("powers").observeSingleEventOfType(.Value, withBlock: {(IMsnap) in

    if IMsnap.exists(){

    //Found The correct node
    }
    })
    }
    }else{

    //
    }
    })

  • My other alternative solution is:-

    FIRDatabase.database().reference().child("node1").child("node12").queryOrderedByChild("powers").observeSingleEventOfType(.Value, withBlock: {(snap) in

    if let snapDict = snap.value! as? [String : AnyObject]{

    print(snapDict.keys.first!) //Retrieving My AutoID .Nut this gives me entire node.

    }

    for each in snap.value as! [String:AnyObject]{

    print(each.0) //Retrieving My AutoID

    }
    })

    })



Note:- I found somewhat similar Q posted in Firebase forum, but no one seems to answer it :-https://groups.google.com/forum/#!topic/firebase-talk/ZDHKwxRMiKQ

Answer

If you don't care about the value of powers, you only care that the key exists under the autoId node, you just need .queryEqualToValue("") (this is dependent on the value of the key-value pair being a string, for a number, instead of "" just use 0 [dependent on your values being greater than or equal to 0]).

let ref = FIRDatabase.database().referenceWithPath("node1/node12")

ref.queryOrderedByChild("powers")
ref.queryEqualToValue("")
ref.observeEventOfType(.Value, withBlock: { snap in

    print(snap) // all the autoId nodes that have the powers key
})