mongodb - 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);
如何只获取一个团队和一个给出分数的用户的数据?谢谢 :)
解决方案
我检查了您的查询,它工作正常,并且只返回userScores
与userId
.
您需要用于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);
推荐阅读
- r - 数据框:将由星号分隔的数据块从长格式改成狂野格式
- python - db_create_all() 不工作并在终端上给出错误
- android-11 - 在 Android 11 上调用 getNetworkCapabilities 时出现 SecurityException
- terraform - 属性中的局部变量和变量中的 Terraform 报告错误
- animation - SwiftUI:如何保持动画隐藏和显示按钮(视图)?
- javascript - 对象数组棘手的事情
- taxonomy - Sulu:将标签字段添加到自定义实体
- java - 使用java中的流查找Integer ArrayList中元素第二次出现的索引
- c# - 如何在.netcore中将值从一个控制器传递到另一个控制器
- html - 响应式导航栏问题