【问题标题】:Meteor - Creating a variable within publishMeteor - 在发布中创建变量
【发布时间】:2016-03-04 18:57:07
【问题描述】:

我正在尝试使以下发布功能正常工作。我想检索所有没有当前用户在其profile.classes 数组中的类的用户。我在这里做错了什么?

Meteor.publish('classes', function () {

  var class = Meteor.users.find({_id: this.userId},{fields: {"profile.classes": 1}});

  var users = Meteor.users.find({
    roles:'is_student',
    "profile.classes": { $ne : class } 
    }});

   return users;
});

【问题讨论】:

  • var class = Meteor.users.find( /* ... */ ).fetch()[0].classes?或者使用findOne 来避免fetchfind 返回一个 Mongo 光标,而不是文档或该文档的字段。
  • classes 应该是一个数组还是单个字段?
  • 我认为是一个数组,因为可能有数学、科学、英语等
  • var class = Meteor.users.findOne({_id: this.userId},{fields: {"profile.classes": 1}}).classes;
  • 那么您是在询问所有在当前用户的课程中有课程的用户吗?另外,您的代码中的 group 是什么?

标签: javascript mongodb meteor


【解决方案1】:

假设profile.classes 拥有一个字符串数组,并且您想要获取当前用户的类中没有类的所有用户,这里有一些代码可以满足您的要求:

Meteor.publish('classes', function ( ) {

  var user = Meteor.users.findOne({_id: this.userId},{fields: {"profile.classes": 1}});
  if( user && user.profile && user.profile.classes ) {
    return Meteor.users.find({ roles: 'is_student', 'profile.classes': { $nin: user.profile.classes } });
  } else {
    return this.ready();
  }
});

该代码的重要行是:

return Meteor.users.find({ roles: 'is_student', 
            'profile.classes': { $nin: user.profile.classes } });

这里的关键部分是$nin。来自MongoDB documentation

$nin 选择以下文档:
- 字段值不在指定数组中或
- 该字段不存在。

所以这应该选择没有profile.classes 数组字段的用户,或者没有当前用户拥有的任何类。

【讨论】:

  • 谢谢斯蒂芬!这是一种享受。我只需要稍微修改一下就可以让它与我的其他条件一起工作,因此延迟了。再次感谢。
猜你喜欢
  • 2015-09-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多