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:
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With