Retrieving data from firebase Array

980 views Asked by At

My Firebase Array has the following structure:

[
   {
  'userId': '12345',
  'itemOrdered' : 'abc',
  'status': 'pending'
   ...other attributes
   },
  {
  'userId': '6789',
  'itemOrdered' : 'def',
  'status' : 'pending',
   ...other attributes
   },
  {
  'userId': '12345',
  'itemOrdered' : 'def',
  'status' : 'complete',
   ...other attributes
   },

]  

I am not able to figure out how to retrieve the following data:

  1. Get records with userId = xxx
  2. Get all records where 'itemOrdered" = 'def'

Firebase docs talk about using orderByChild but that doesn't make much sense.

2

There are 2 answers

2
Frank van Puffelen On BEST ANSWER

Assuming you're using the JavaScript SDK to access Firebase:

  1. ref.orderByChild('userId').equalTo('xxx')

  2. ref.orderByChild('itemOrdered').equalTo('def')

If you're trying to build a query that gets order of item def from user xxx, then that's not currently possible with Firebase's querying. The only way to query the value of multiple properties is to combine them in a single property in a way that allows the query you want. E.g.

  1. ref.orderByChild('userId_itemOrdered').equalTo('xxx_def')
0
Jay On

There are additional options depending on your platform.

1) Query for the userId and then filter in code for the item you are looking for. 

2) Query for the userId and build another query based on those results.

3) Flatten your data!

For example: create a node called user_purchases and each child could be a userId node with that users purchased itemId's (that makes it a snap to know exactly what items a user purchased). Or create an items_purchased node with each child being an item number node and then associated userId's who purchased that item.