【问题标题】:Meteor- projections on cursor?光标上的流星投影?
【发布时间】:2016-06-03 21:22:12
【问题描述】:

目前,我的收藏有助手(使用 dburles:collection-helpers)。

例如,在我的 Teams 集合中,我定义了以下帮助程序。我在客户端使用这个助手:

getUnlockedProblems: function() {
    return Problems.find({requirements: {$not: {$elemMatch: {$nin: this.getSolvedIds()}}}});
},

在我的 Publications.js 中,我有一个发布来发布团队已解决的问题,它基本上使用相同的查询,除了过滤掉 grader 字段:

return Problems.find({requirements: {$not: {$elemMatch: {$nin: team.getSolvedIds()}}}}, {fields: {grader: 0}});

有什么办法可以代替return team.getUnlockedProblems().project({fields: {grader: 0}}) 吗?所以我可以重复使用查询

【问题讨论】:

  • options 参数添加到getUnlockedProblems 是可接受的解决方案吗?
  • @DavidWeldon 我想这行得通。不知道为什么我没有想到这样做!谢谢
  • 太棒了。为了完整起见,我回答了我的评论。

标签: mongodb meteor


【解决方案1】:

集合助手是常规函数,因此您可以通过向getUnlockedProblems 添加options 参数来解决此问题,如下所示:

getUnlockedProblems: function(options) {
  return Problems.find({requirements: ...}, options);
}

那么你可以这样使用它:

var team = Teams.findOne();

// Get a cursor with a limited set of fields
team.getUnlockedProblems({fields: {grader: 0}});

// Get a cursor with a complete set of fields
team.getUnlockedProblems();

【讨论】:

  • 只是补充一点:我定义了使用可选参数getUnlockedProblems: function(options={}) {的函数,所以我不需要重写我对它的现有调用
  • 我认为这可能会使代码更清晰,尽管在这种情况下它不是绝对必要的,因为find(selector, undefined)find(selector) 相同。
猜你喜欢
  • 2023-03-15
  • 1970-01-01
  • 2018-06-18
  • 1970-01-01
  • 2016-08-09
  • 2022-10-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多