Meteor: How to subscribe/show usernames when this.

2019-09-08 14:56发布

Note: Whole sourcecode can be found here:

https://github.com/Julian-Th/crowducate-platform/

I have the following pub functions:

Meteor.publish('editableCourses', function () {
    return Courses.find({"canEditCourse": { $in: [ this.userId ] } });
});

Meteor.publish("userData", function () {
    if (this.userId) {
        return Meteor.users.find({_id: this.userId},
            {fields: {'realname': 1, 'username': 1, 'gender': 1, 'language': 1, 'biography': 1 }})
    }
});

Meteor.publish("allUsernamesExceptCurrent", function () {
  // Get current user
  var currentUserId = this.userId;

  // Get all users except current,
  // only get username field
  var users = Meteor.users.find(
    {_id: {$ne: currentUserId}},
    {fields: {username: 1}}
  );

  return users;
});

Here's the template:

<template name="myTeachingCourses">
  <button class="btn btn-primary js-create-course"><i class="fa fa-plus"></i> Create a Course</button>
  <hr>
  <div class="row">
      <ul class="thumbnails list-unstyled">
          {{#each courses}}
          {{>courseCard}}
          {{/each}}
      </ul>
  </div>
</template>

The helper with subscription:

Template.myTeachingCourses.helpers({
    'courses': function(){
      return Courses.find();
    }
});    

Template.myTeachingCourses.created = function () {
      // Get reference to template instance
      var instance = this;

      // Subscribe to all published courses
      instance.subscribe("editableCourses");
    };

The problem: The template doesn't render the created courses. A course creator can't see his own courses or add other collaborators. I wonder if the reason might be, because canEditCourse is now an array with usernames and not with IDs.

My JSON for Courses:
{
    "_id" : "hRX8YABpubfZ4mps8",
    "title" : "Course Title here",
    "coverImageId" : "Qojwbi2hcP2KqsHEA",
    "author" : "Name",
    "keywords" : [ 
        "test", 
        "meteor"
    ],
    "published" : "true",
    "about" : "Testing",
    "canEditCourse" : [ 
        "User1"
    ],
    "createdById" : "zBn6vtufK2DgrHkxG",
    "dateCreated" : ISODate("2015-12-29T21:42:46.936Z")
}

Via this question I found out that storing usernames in the array is not a good idea for now obvious reasons. In the beginning, I actually stored IDs instead of usernames but then changed it because to use the username for autocomplete with typeahead and rendering the IDs of all collaborators is not good thing to do. What is the best way to fix it? In other words, how is it possible to render all created courses.

1条回答
Emotional °昔
2楼-- · 2019-09-08 16:03

So, as you answered yourself, your Courses collection field canEditCourse has an array of usernames, not userId, so the query will not return anything.

查看更多
登录 后发表回答