Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Query data on firebase for web

So I'm building a music platform, using firebase, where users can upload their songs. When a user logs in, I save their data on the "usuarios" node. And when they upload a song, I push to the "musicas" node (child of usuarios). This way, I know who uploaded the song.

But the problem is: I want to get a list of all the last 15 songs uploaded. How do I do that? Did I structure my data wrong?

Here's what I tried:

  var musicsRef = firebase.database().ref('usuarios').orderByChild('musicas');
  musicsRef.on('value', function(snapshot) {
  console.log(snapshot.child('musicas');
});

Here's my database structured:enter image description here

like image 933
Rosário Pereira Fernandes Avatar asked Jun 09 '26 02:06

Rosário Pereira Fernandes


1 Answers

With Firebase (like with most NoSQL databases) you often end up modeling your data for the way you app wants to consume it. So if you need to find a global list of the most recently uploaded songs, you should keep such a list:

songsByDate
  $pushIdOfSong: true

You'll note that we don't keep a real value in this list. It is just the ID of each song and a true value. This is called a secondary index and so command that we explain it in our documentation on creating a scalable data structure.

With that structure in place you can query with:

var recents = ref.child('songsByDate').orderByKey().limitToLast(15);
recents.on('child_added', function(snapshot) {
  var key = snapshot.key;
  // load the song by its key
});

I highly recommend reading this article on NoSQL data modeling.

like image 171
Frank van Puffelen Avatar answered Jun 10 '26 16:06

Frank van Puffelen