I'm trying to use Firebase to setup a new project and I'm struggling with the non-relational DB and the query system. I have read the guidelines, especially those regarding the data structure. Here is my use case: I have to handle some products and each one has a name and a family, this one is an entity too. I have created the structure below trying to follow the guidelines and the examples.
{
"families" : [ {
"name" : "easy",
"products" : [ 10, 11 ]
}, {
"name" : "ir33",
"products" : [ 12, 13 ]
} ],
"products" : {
"10" : {
"family" : 0,
"name" : "Matita"
},
"11" : {
"family" : 0,
"name" : "Penna"
},
"12" : {
"family" : 1,
"name" : "Gomma"
}
}
}
Given a family, I would like to select all the products of that one. My first solution is to access the family, retrieve the array of IDs and then perform the requests (one for each ID). It works, but this approach potentially leads to a tons of requests. Is there a better way to gain that? For example, I'm trying with this one but It doesn't work:
ref.child("products").queryOrderedByChild("family").queryEqualToValue("0", childKey: "family").observeSingleEventOfType(.Value, withBlock: { snap in
print("snap \(snap)")
})
But it always prints Snap (products) <null>
.
UPDATE
I can access the products of a given family with this query:
ref.child("products").queryOrderedByChild("family").queryEqualToValue(0).observeSingleEventOfType
Btw, Now I have this warning while running my tests:
[FirebaseDatabase] Using an unspecified index. Consider adding ".indexOn": "family" at /products to your security rules for better performance
Thanks in advance for your help!
What about this:
ref.queryOrderedByChild("family").queryEqualToValue(0).observeSingleEventOfType(.Value, with: { snap in
print("snap \(snap)")
})
Update regarding to update of question:
Add this to your database rules in the firebase console (see also screenshot). Don't forget to hit the "Publish" button:
"products": {
".indexOn": "family"
}
Here is the correct solution, I'm looking to solve the warning too:
ref.child("products").queryOrderedByChild("family").queryEqualToValue(0).observeSingleEventOfType(.Value, withBlock: { snap in
print("snap \(snap)")
expectation.fulfill()
})
Please look at @ronatory answer to handle the warning!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With