0

I'm new to firebase and wanted to ask how I can retrieve only the latest data e.g. the last 5 activities added.

I structured my data the following way: activities have the userID as a key and the timestamp as a subkey, see:

activities
 |-uid
    |-timestamp
       |-data: {}

so for example:

activities
 |-4zDhgv1UEjb3EfZ9XhO2PAHdHYg9
    |-1621608449507
       |-distance: 12.5
    |-1621608957090
       |-distance: 9.75

I think of some query like this, which of course doesn't work atm

firebase.database.ref(`activities`).SUBLEVEL().orderByValue().limitToLast(5);

Thanks in advance for any help!

agent00i
  • 3
  • 3

1 Answers1

0

Firebase queries work on a flat list of the child nodes directly under the path you query. So you you run a query of activities, it will consider each node directly under it as a possible result.

The value to order/filter on must be at a known location under each direct child node. That means that in your current model you can only order/filter,

  • either if you know the entire activities/4zDhgv1UEjb3EfZ9XhO2PAHdHYg9 path already,
  • or only want to order/filter on the 1621608449507/distance subpath under there.

Also see:

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
  • Thank you for the answer. Seems like I have to change my model in order to achieve what I want. Just adding the timestamp as a child doesn't solve the problem, because when calling `firebase.database.ref('activities').orderByChild('timestamp').limitToLast(5);` I get the last 5 users and their activities and not as I intended the last 5 activities of all users. Do you have a suggested model with which my problem can be solved? – agent00i May 28 '21 at 13:11
  • It all depends. If you want to search across all users on a timestamp, and each user can have multiple activities, then what timestamp do you want to consider for each user? If you want it to consider all timestamps, you should store all activities/timestamps for all users as a flat list. If you want it to consider one specific timestamp (like the latest or fastest), you can store that single value as a named property for each user and query on that. – Frank van Puffelen May 28 '21 at 14:32