what is wrong with this route to user_profile?

2019-09-06 16:28发布

问题:

I am trying to add a profile page to the microscope app. Thanks to help I got here I was able to get most of it working but I can't get the route to another users profile to work. This is the code for the route. Thanks

in comment.html template

<span class="author"><a href="{{pathFor 'user_profile'}}">{{username}}</a></span>

router.js

this.route('user_profile',{
    path: '/profile/:_username',
    waitOn: function () {
    return Meteor.subscribe('userprofile', this.params._username)
  },
    data: function () {return user.findOne(this.params._username)}
});

publications.js

Meteor.publish('userprofile', function (username) {
   return user.find(username);
}); 

profile.js

Template.user_profile.helpers({
  username: function() {
      return this.user().username;
  },
  bio: function() {
      return this.user().profile.bio;
  }
});

回答1:

The default Meteor user collection used by accounts-base and accounts-password is Meteor.users, not user. Also, collection.find(x) will find a document whose _id is x; if you want to find documents whose username is x, you need collection.find({username: x}).

this.route('user_profile',{
  path: '/profile/:username',
  waitOn: function () {
    return Meteor.subscribe('userprofile', this.params.username)
  },
  data: function () {return Meteor.users.findOne({username: this.params.username})}
});

I renamed the _username parameter to username, that way the pathFor helper will be able to automatically fill it in. I also replaced user with Meteor.users and passed in the correct selector.

Meteor.publish('userprofile', function (username) {
  return Meteor.users.find(
    {username: username},
    {fields: {username: 1, profile: 1}}
  );
}); 

I replaced user with Meteor.users and fixed the selector again, and I limited which fields we publish (since the user document contains sensitive data like login tokens, you don't want to publish the whole thing).

Template.user_profile.helpers({
  username: function() {
    return this.username;
  },
  bio: function() {
    return this.profile.bio;
  }
});

Inside the user_profile template, the data context (which you specified in the data parameter in the route) is a user document, so this is already a user document. Note that these helpers are redundant (you can get the username with {{username}} and the bio with {{profile.bio}} even without these helpers).