首页 > 解决方案 > Meteor-publish 返回比 MongoDB 所需的更多行

问题描述

我有一个收藏:

{
    "_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")
        }
    ]
}

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

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

但是在流星/反应应用程序中,我收到(this.props.receivedScores)整个文档,所有行都在“userScores”中。

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

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

标签: mongodbmeteorpublish-subscribemeteor-publications

解决方案


我检查了您的查询,它工作正常,并且只返回userScoresuserId.

您需要用于fields过滤要发布的字段。

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

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

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

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);


推荐阅读