我正在尝试向显微镜应用程序添加个人资料页面。感谢帮助我得到了here我能够使其大部分工作正常,但无法使到其他用户个人资料的路由正常工作。这是路线的代码。谢谢
在comment.html模板中
<span class="author"><a href="{{pathFor 'user_profile'}}">{{username}}</a></span>
路由器.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)}
});
出版物.js
Meteor.publish('userprofile', function (username) {
return user.find(username);
});
配置文件.js
Template.user_profile.helpers({
username: function() {
return this.user().username;
},
bio: function() {
return this.user().profile.bio;
}
});
最佳答案
accounts-base 和accounts-password 使用的默认Meteor 用户集合是Meteor.users
,而不是user
。另外,collection.find(x)
会查找_id
为x
的文档;如果你想查找username
为x
的文档,你需要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})}
});
我将 _username
参数重命名为 username
,这样 pathFor
帮助器将能够自动填充它。我还替换了 user
与 Meteor.users
并传入正确的选择器。
Meteor.publish('userprofile', function (username) {
return Meteor.users.find(
{username: username},
{fields: {username: 1, profile: 1}}
);
});
我用 Meteor.users
替换了 user
并再次修复了选择器,并且我限制了我们发布的字段(因为用户文档包含登录 token 等敏感数据,您不想发布整个内容)。
Template.user_profile.helpers({
username: function() {
return this.username;
},
bio: function() {
return this.profile.bio;
}
});
在 user_profile
模板内,数据上下文(您在路由的 data
参数中指定)是一个用户文档,因此 this
已经是一个用户文档。请注意,这些助手是多余的(即使没有这些助手,您也可以使用 {{username}}
获取用户名,并使用 {{profile.bio}}
获取个人简介)。
关于javascript - 到 user_profile 的这条路由有什么问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25305254/