How to get collection of items depending on specific category using Firebase RealTime DataBase

Viewed 102

I have an application that consists of two tables or collections [coupons, categories] in Realtime Database firebase and I want to get all coupons that belong to a specific category id how could I fetch this data? so I mean implement one to many relationships in firebase

Database

+ categories
  - 1605426969
    - count: 0
    - createdDate: 1605426969
    - id: 1605426969
    - imageUri: "https://placeholder.png"
  - 160542456
    - count: 0
    - createdDate: 1605426969
    - id: 160542456
    - imageUri: "https://placeholder.png"
    
+ coupons
  - 1605515952
    - category
      - 1605426969
      - count: 0
      - createdDate: 1305426969
      - id: 1605426969
      - imageUri: "https://placeholder.png"
    - code: "L1150" 
    - description: "my description"
    - id: 1605515952
    - imageUri: "https://avatar.png"
    -url: "https://www.google.com/"
 - 16055151325
    - category
      - 1605426969
      - count: 0
      - createdDate: 1305426969
      - id: 1605426969
      - imageUri: "https://placeholder.png"
    - code: "L1150" 
    - description: "my description"
    - id: 16055151325
    - imageUri: "https://avatar.png"
    - url: "https://www.google.com/"

so I tried to fetch it like below but it does not work could you help me.


//...
const app = Firebase.initializeApp(firebaseConfig)
const categoryRef = app.database().ref().child('categories')
const couponRef = app.database().ref().child('coupons')

const coupons = couponRef.orderByChild('category').equalTo('1605426969');

console.log(coupons);
1 Answers

Firebase realtime database is a document oriented database. Therefore you can't really define a one-to-many relationship. They do describe how you should flatten your data, doing more or less the same thing: https://firebase.google.com/docs/database/web/structure-data#flatten_data_structures.

It basically comes down to using clear identifiers and doing separate calls to fetch the data you want.


In your case you could store coupons like:

+ coupons
  - 1605515952
    - category_id: 1605426969
    - code: "L1150" 
    - description: "my description"
    - id: 1605515952
    - imageUri: "https://avatar.png"
    -url: "https://www.google.com/"

Then query .where(category_id: 1605426969) and fetch the category details in a separate call.

Related