0

My Use case

I have a playlist for an online music player. Currently they sorted by natural order when they are displayed.

I would like to put in a field for a track position within a playlist.

What would be the best way to implement this for a collection in meteor mongo db.

Here is my current schema for my Songs collection.

    //Schema for Songs
    Schema.Songs = new SimpleSchema({
      trackId: {
        type: String,
        label: "Track ID",
        optional: false
      },
      title: {
        type: String,
        label: "Name",
        optional: false
      },
      duration:{
        type: Number,
        label: "Duration",
        optional: false
      },
      festivalId: {
        type: SimpleSchema.RegEx.Id,
        optional: false
      }
    });

I would like to be able to reorder the songs, for example a song at position 3. I would like to move it to position 1 and then all other songs position field would update appropriately .

What would be a good starting point for this?

molleman
  • 2,934
  • 16
  • 61
  • 92

1 Answers1

0

The easiest way that comes to mind is to have a collection called playlist which as a field called songs. The songs field would be an array of strings. These would be ID's of Songs

Schema.Playlist = new SimpleSchema({
  'songs.$': {
    type: String,
  }
})

You can then create a helper to list all the song. Let's call it showPlaylist. It resolves the ID's inside the songs field to their perspective documents. I'd make the array returned by showPlaylist reactive. That would save you some work.

{{ #each showPlaylist }}
  <audio id="{{ _id }}" class="song" src="{{ src }}"></audio>
{{ /each }}

Now you'll have to write something for the user to reorder the list and call this:

function updatePlaylistOrder (oldPos, newPos, id) {
  var newList = moveElement(Playlists.findOne(id), oldPos, newPos)
  Playlists.update(playlistId, {$set: {songs: newList}})
  return newList
}

Credit for the moveElement function to /u/Matt

Community
  • 1
  • 1
halbgut
  • 2,368
  • 17
  • 22