问题
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