【问题标题】:how to apply a position field to a collection within Meteor mongo?如何将位置字段应用于 Meteor mongo 中的集合?
【发布时间】:2015-06-20 00:24:35
【问题描述】:

我的用例

我有一个在线音乐播放器的播放列表。目前,它们在显示时按自然顺序排序。

我想为播放列表中的曲目位置输入一个字段。

在meteor mongo db中实现这个集合的最佳方法是什么。

这是我的歌曲收藏的当前架构。

    //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
      }
    });

我希望能够重新排序歌曲,例如位置 3 的歌曲。我想将其移动到位置 1,然后所有其他歌曲位置字段将相应更新。

什么是一个好的起点?

【问题讨论】:

    标签: javascript mongodb meteor


    【解决方案1】:

    想到的最简单的方法是拥有一个名为playlist 的集合,它作为一个名为songs 的字段。 songs 字段将是一个字符串数组。这些将是 Songs 的 ID

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

    然后您可以创建一个助手来列出所有song。我们称之为showPlaylist。它将songs 字段中的ID 解析为他们的透视文档。我会让showPlaylist 响应的数组返回。这样可以为您节省一些工作。

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

    现在您必须为用户编写一些内容来重新排序列表并调用它:

    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 到 /u/Matt

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-02-23
      • 2017-04-05
      • 2014-09-16
      • 2014-07-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-01-26
      相关资源
      最近更新 更多