问题
Question--->
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 nodepowers
inside someautoID
's, not all of them, I want to retrieve only those nodes which have keypowers
in them not knowing what correspondingvalue
might be .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 particularkey
. 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
回答1:
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
})
来源:https://stackoverflow.com/questions/39420001/firebase-swift-retrieving-only-those-autoid-nodes-which-have-a-specific-key