Still can't wrap my head around working with data


#1

Okay, I know this is a rookie question and should be searchable, but even with all the searching I’ve done (and purchased books), I still can’t seem to grasp the concepts of the best way to be storing my data in the database, and how to call it.

For example, I’m building a site where you can create a Team, and you can create a Season, which is associated to a Team.

So I have a collection that stores my Teams, and have another for the Season. I also create a property in my Season collection to reference what team it belongs to.

Now there are several occasions on my site, where I will grab the name of the Season, but I also want to display the name of the associated team.

What is the proper way to publish the data when lets say in my template, I’m just working with the _id of the Season. I find right now I’m loading the Season collection, searching that collection for all seasons associated to the user. Then I have to wait until that is done and then I have to go through each result, to search the database again for the Team information based on the associated userID. I know this is inefficient and not quite right, but I just can’t seem to figure out what the proper way is.

Could anyone help me?


#2

Maybe this:

Meteor.publish('seasonAndTeam', function(seasonId) {
  check(seasonId, String);
  
  // Check user permission
  ...

  // Get the season
  const season = Seasons.findOne(seasonId, { fields: { teamId: 1 } });
  if (!season)
    throw new Error('season ' + seasonId + ' not found');

  // Publish
  return [
    Teams.find(season.teamId),
    Seasons.find(seasonId),
  ];
});

Notice that this publish function is not reactive: if you move a season to a new team (don’t know if it makes sense in your case), the publish function won’t trigger again and the published team won’t be updated.


#3

Thanks Steve!

Turns out I was pretty much on the right track, but your sample code there was exactly what I needed to make it click.