Reputation: 311
By selecting a value from a drop-down list in my Application I need to get a list of every Object that contains the selected value in its inner node 'foodtype'.
I have the following structure in my Firebase database:
restaurants
- key: "12345"
- name: "Salad house"
- address: "Etc etc etc"
- foodtypes
- 0: "Salad"
- 1: "Fastfood"
- 2: "Seafood"
...
For example: If I select "Salad", "Fastfood" or "Seafood" I should get the object above in my restaurants list. But if I select "Japanese food" I should get none (or any other record that contains that).
Is there a way to do this in Firebase without creating lots of concatenated fields/values? I would really appreciate any suggestions!
Upvotes: 0
Views: 596
Reputation: 3625
This is possible with Cloud Firestore query, not Firebase RTDB(Realtime database) query.
If you want approach it with Firebase RTDB, your database should look like this.
restaurants
- key: "12345"
- name: "Salad house"
- address: "Etc etc etc"
- foodtype: 0 (or 1 or 2 ...)
...
You can also use string like "Salad", "Fastfood", "Seafood" but since the name could be changed in the future, I would use integer as constant variable and define it in your javascript code as const FOODTYPE_SALAD = 0
, const FOODTYPE_FASTFOOD = 1
.
Finally you can get list as below code.
return restaurantsRef.orderByChild('foodtype').equalTo(FOODTYPE_SALAD).once('value').then(snap => {
// TODO: ...
});
But this way has some disadvantages.
For example you cannot sort list as you want. What if you want to sort restaurant list as registered date?
Therefore best option for Firebase RTDB in this situation is denormalize your database and flatten the database.
You will need Server side Fan-out on Cloud Functions for Firebase.
This is final appearance of your database tables.
restaurants
- key: "12345"
- name: "Salad house"
- address: "Etc etc etc"
- foodtype: 0
- key: "22222"
- name: "Fastfood house"
- address: "Etc etc etc"
- foodtype: 1
- key: "33333"
- name: "Seafood house"
- address: "Etc etc etc"
- foodtype: 2
restaurants-salad
- key: "12345"
- name: "Salad house"
- address: "Etc etc etc"
- foodtype: 0
restaurants-fastfood
- key: "22222"
- name: "Fastfood house"
- address: "Etc etc etc"
- foodtype: 1
restaurants-seafood
- key: "33333"
- name: "Seafood house"
- address: "Etc etc etc"
- foodtype: 2
...
Remember that restaurants
should have all original restaurant
object datas.
Upvotes: 1