Meteor - Creating a variable within publish

ぃ、小莉子 提交于 2020-01-06 15:42:09

问题


I'm try to get the below publish function to work. I would like to retrieve all users who do not have a class that the current user has in their profile.classes array. What am I doing wrong here?

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

回答1:


Assuming profile.classes holds an array of strings and that you want to get all users who DO NOT have a class in the current user's classes, here is some code to do what you're asking for:

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

The important line of that code is:

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

The key part here is the $nin. From MongoDB documentation:

$nin selects the documents where:
- the field value is not in the specified array or
- the field does not exist.

So this should select users who either don't have a profile.classes array field, or have none of the classes the current user has.



来源:https://stackoverflow.com/questions/35784424/meteor-creating-a-variable-within-publish

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!