I've got a collection of 'tasks' that is available to all users. Users can tick off that they have 'completed a task'. When they do this, a method is called which adds their userId to an array that is attached to the task document called 'usersCompleted'. If a user has completed a task, their userId will be in that array.
I don't want to publish this array to the client, because then all users will have access to an array with other userIds in it.
However, I want to have a helper that checks if a user's ID is in this array, then returns either 'checked' or ''. This way users see the tasks they have completed.
In my publication I am able to find all tasks that the user has completed, but I am unable to return just their ID from the 'usersCompleted' array. If anyone can help me do that it would be much appreciated.
Below is my current code but the $elemMatch isn't being used correctly
Meteor.publish( 'tasks.single.lesson.completed', function(lessonNumber) {
check(lessonNumber, Number);
if(this.userId) {
return Tasks.find({ lesson: lessonNumber, usersCompleted: this.userId} , {fields: { $elemMatch: {usersCompleted: this.userId}}});
} else {
this.stop();
return;
}
});
I worked this out, and I'm posting an answer for anyone else who may have this issue.
Turns out Mongo has a modifier built for this situation: $
My working publication is now:
Meteor.publish( 'tasks.single.lesson.completed', function(lessonNumber) {
check(lessonNumber, Number);
if(this.userId) {
return Tasks.find({ lesson: lessonNumber, usersCompleted: this.userId} ,
{ fields: { "usersCompleted.$": 1}});
} else {
this.stop();
return;
}
});