Meteor-publish returns 需要更多行 MongoDB

Meteor-publish returns more rows then required from MongoDB

我有一个 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")
        }
    ]
}

我需要 return 'userScores' 一个团队 ID 和当前用户 ID (this.userId)。所以我做了这个发布方法。

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

但在 meteor/react 应用程序中,我收到 (this.props.receivedScores) 整个文档,所有行都在 "userScores".

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

如何只获取一个团队和一个打分的用户的数据?谢谢:)

听起来你想要这样的东西。

Meteor.publish('scoresTeamByUser', function(teamId) {

    const teamScores = Scores.find({ teamId: teamId });

    const userScore = Scores.find(
    {'userScores.userId': this.userId}, {'userScores.$': 1});

    return [teamScores, userScore];
});

我检查了你的查询,它工作正常,returns userScores 数组中只有一个对象匹配 userId.

您需要使用fields筛选您要发布的字段。

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

您获取 userScores 数组中所有对象的原因是您必须有另一个发布整个记录的订阅。您可以在订阅 scoresTeamByUser 出版物之前通过 console.log(Scores.findOne({ props.teamId})) 检查。

因此,您必须找到该发布并将其限制为仅发布当前用户的分数,或者在您当前的订阅中,您必须按如下方式在客户端查询中过滤数据。

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