Reputation: 157
I have a realtime database structure like below. Users have some friends. For example, I am Joe and I'd like to fetch users who have friends as Joe.
In this example, Dave and Harry have a friend called Joe, so my query should fetch Dave and Harry but shouldn't Micheal.
Is there a way to do this without fetching data in a loop?
{
"Users": {
"Joe": {
"Friends": ["Dave","Harry","Micheal"]
},
"Dave": {
"Friends": ["Joe","Jack","Brent"]
},
"Harry": {
"Friends": ["Jack","Joe"]
},
"Micheal": {
"Friends": ["Ken","Jack","Brent"]
}
}
}
Upvotes: 1
Views: 618
Reputation: 138824
Firebase
Realtime database cannot perform a query across array
members, to see if it contains a specific value in any position or to add/remove a record. Firebase
documentation recommends against using arrays. One of the many reasons Firebase recommends against using arrays is that it makes the security rules impossible to write.
As usual with NoSQL databases: if you can't perform the use-case you want with your current data structure, you can typically change/expand your data structure to allow the use-case. The best practice is to use maps
instead of arrays. A possible database structure could look like this:
"Users": {
"Joe": {
"Friends"
"Dave": true,
"Harry": true,
"Micheal": true
},
"Dave": {
"Friends"
"Joe": true,
"Jack":true,
"Brent": true
},
"Harry": {
"Friends"
"Jack": true,
"Joe": true
},
"Micheal": {
"Friends"
"Ken":true,
"Jack": true,
"Brent": true
}
}
You can also take a look, here, for more informations.
Upvotes: 1