javascript - Meteor - 在发布中创建变量

标签 javascript mongodb meteor

我正在尝试让以下发布功能正常工作。我想检索当前用户在其 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;
});

最佳答案

假设 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 selects the documents where:
- the field value is not in the specified array or
- the field does not exist.

因此,这应该选择没有 profile.classes 数组字段或没有当前用户拥有的类的用户。

关于javascript - Meteor - 在发布中创建变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35784424/

相关文章:

javascript - src 的图像选择不起作用 jquery

scala - 如何检索 Mongodb 集合中的所有对象,包括 id?

MongoDB:如何解决连接超时错误?

javascript -/node_modules/fibres/bin/linux-x64-v8-7.6/fibres.node` 丢失。尝试重新安装 `node-fibers`?

javascript - Node.js Promise 的函数参数

javascript - 在浏览器中调试 ActionScript

meteor - 如何在 Meteor 中将 forbidClientAccountCreation 设置为 false?

javascript - Meteor,为每个用户定义 "standard route"

javascript - 访问控制允许方法似乎不起作用

node.js - 带有推送数组元素的 findOneAndUpdate 在 mongoose 中给出错误