Reputation: 355
I have a list of songs that I want to display to a user. Each song has a enqueue id. My problem is that several of these songs need to be displayed multiple times. I am currently using $in
operator to query MongoDB which only returns three objects as there is only three unique song ids. This means that when I use spacebars in my template to iterate over the objects I am not able to get the same song to display multiple times. Any help on a solution would be much appreciated.
Current Display Order:
The Order I Want it to Display
My code is below
Template.songList.helpers({
songs: function () {
var idsOfSongs = ["cEbeGLR5ujCEFPtnH", "cEbeGLR5ujCEFPtnH", "qcRfAPeYMQycwodLA", "7oK4TKZiEfvZoC5Jz"]
return Songs.find({"_id":{$in: idsOfSongs}}).fetch();
}
});
Objects returned from Songs.find
[Object, Object, Object]
0: Object
_id: "cEbeGLR5ujCEFPtnH"
album: "My Everything"
artist: "Ariana Grande"
1: Object
_id: "qcRfAPeYMQycwodLA"
album: "This an That"
artist: "Mark Miller"
2: Object
_id: "7oK4TKZiEfvZoC5Jz"
album: "Going off Again"
artist: "Pick up Sticks"
Upvotes: 0
Views: 114
Reputation: 4101
You can {{#each}}
over the array of _id
s, then inside the {{#each}}
, use a {{#with}}
to select the actual document.
{{#each songIds}}
{{#with song}}
<li><em>{{album}}</em> by {{artist}}</li>
{{/with}}
{{/each}}
Template.songList.helpers({
songIds: function () {
return ["cEbeGLR5ujCEFPtnH", ...]
},
song: function () {
return Songs.findOne({_id: this});
}
});
Upvotes: 1
Reputation: 20256
@Blake Seven is right that mongo won't do this natively. (However a SQL database could do this via an outer join/cross-product).
Here's one possibility:
Template.songList.helpers({
songs: function () {
var idsOfSongs = ["cEbeGLR5ujCEFPtnH", "cEbeGLR5ujCEFPtnH", "qcRfAPeYMQycwodLA", "7oK4TKZiEfvZoC5Jz"];
var songsXcount = [];
idsOfSongs.forEach(function(id){
songsXcount.push(Songs.findOne({_id: id}));
}
return songsXcount;
}
});
Upvotes: 1