Meteor-publish returns more rows then required from MongoDB


#1

I have a collection:

{
    "_id" : "SeGtBvCT7ojF2v5x9",
    "teamId" : "d74JJ9s5k6tijeQaz",
    "userScores" : [ 
        {
            "userId" : "6ghphqzx9GFnvKYKY",
            "scores" : 10,
            "addedAt" : ISODate("2019-02-04T06:37:06.387Z")
        }, 
        {
            "userId" : "56ghp45hqzx9G2dda",
            "scores" : 1,
            "addedAt" : ISODate("2019-02-04T06:37:19.105Z")
        }, 
        {
            "userId" : "wrr3422fwefx6fFGs",
            "scores" : 4,
            "addedAt" : ISODate("2019-02-04T06:37:44.005Z")
        }
    ]
}

I need to return ‘userScores’ for one teamId and current user Id (this.userId). So I made this publish method.

Meteor.publish('scoresTeamByUser', function(teamId) {
  return Scores.find(
      { teamId }, 
      { userScores: { $elemMatch: { userId: this.userId } } }
  );
});

But in meteor/react app I receive (this.props.receivedScores) the whole document, with all rows in “userScores”.

export default withTracker(props => {
    const scoresSubscription = Meteor.subscribe('scoresTeamByUser', props.teamId);
    return {
        receivedScores: Scores.findOne(),
        scoresLoaded: scoresSubscription.ready()
    };
})(GiveScores);

How to get just data for one team and one user which gave a score? Thanks :slight_smile:


#2

Try this:

Meteor.publish('scoresTeamByUser', function(teamId) {
  return Scores.find(
    {
      teamId, 
      userScores: { $elemMatch: { userId: this.userId } },
    },
    {
      fields: { 'userScores.$': 1 },
    }
  );
});