如何 return Meteor 出版物中数组的单个索引

How to return a single index from an array in a Meteor publication

我收集了 'tasks' 供所有用户使用。用户可以勾选他们有 'completed a task'。当他们这样做时,将调用一个方法,将他们的 userId 添加到一个数组中,该数组附加到名为 'usersCompleted' 的任务文档。如果用户完成了任务,他们的 userId 将在该数组中。

我不想将此数组发布到客户端,因为这样所有用户都可以访问其中包含其他 userId 的数组。

但是,我想要一个帮助程序来检查用户的 ID 是否在此数组中,然后 returns 'checked' 或 ''。这样用户就可以看到他们已经完成的任务。

在我的出版物中,我能够找到用户已完成的所有任务,但我无法 return 仅从 'usersCompleted' 数组中找到他们的 ID。如果有人能帮助我做到这一点,将不胜感激。

下面是我当前的代码,但是 $elemMatch 没有被正确使用

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

我已经解决了这个问题,我会为可能遇到此问题的其他人发布答案。

原来 Mongo 有一个针对这种情况的修饰符:$

我的工作出版物现在是:

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