Having a bit of trouble with reactively filtering arrays and updating filtered arrays

Okay so I have a few routes where I filter an array of a collection. My unfiltered PlayerCollection might look like this.

{
  "_id": "someid"
  "battletag": "fake#1234",
  "games": [{
    "_id": "somegameid",
    "name": "Starcraft II",
    "ranking": [{
      "1v1": {
         "Zerg": {
           "games_played": 100,
           "league": "Gold"
         },
        // etc etc
      }
    }]
  }, {
    "_id": "anothergameid",
    "name": "World of Warcraft",
    "ranking": [{
      "2v2": {},
      "3v3": {},
      "5v5": {}
    }]
  }]
}

However, a user may only have privileges to view a single game that this player. Let’s say they can only view the user’s SCII profile. So I publish information based on that.

Meteor.publish('Player.profile', function (playerId) {
  if(this.userId) {
    // user should only be able to see player's profile for the games he also plays, in this case, SCII
    var games = Meteor.users.findOne(this.userId).profile().games;
    return Players.find({
      "_id": playerId
    }, {
      "games": {
        $elemMatch: {
          _id: games
        }
      }
    });
  }
  return [];
});

Therefore, it should return a filtered Player.

{
  "_id": "someid",
  "battletag": "fake#1234",
  "games": [{
    "_id": "starcraftsid",
    "name": "Starcraft II",
    "ranking": { /** no need to show */ }
  }]
}

However, how does one safely update this structure? Since only a portion of the games array is returning, what is the right way to update it? I am using autoform and simple schema and keep coming across a number of problems

Why don’t you keep a separate collection of games-users or users-games as a join reference.

Your queries would become much simpler and you can scale better.

1 Like