【问题标题】:Showing posts by current user - Meteor显示当前用户的帖子 - Meteor
【发布时间】:2015-10-22 12:17:54
【问题描述】:

我正在尝试显示当前登录用户的帖子。我尝试了与在相关帖子页面下显示 cmets 相同的方法,但不适用于已登录用户的帖子。

Template.myPosts.helpers({
    posts: function () {
        selector = {userId: this.userId};
        options = {sort: {createdAt: -1}};
        return Posts.find(selector, options);
    }
});

我还在 router.js 中尝试了下面的代码(安装了铁路由器包):

this.route('myPosts', {
        path:'/my-posts',
            data:function(){
                return Posts.find({userId: this.userId})
        }             
                            });
})

如果上面的代码不接近应有的样子,任何有关如何进行的提示将不胜感激。这是一个仅用于学习目的的项目。

谢谢!

【问题讨论】:

标签: meteor


【解决方案1】:

您确定您的助手的上下文具有userId 属性吗?也许你想要这个:

Template.myPosts.helpers({
  posts: function () {
    selector = {userId: Meteor.userId()};
    options = {sort: {createdAt: -1}};
    return Posts.find(selector, options);
  }
});

也值得一试:Posts.find({userId: Meteor.userId()}).fetch() 在 Web 控制台中查看您是否有任何此类帖子实际发布到客户端。

【讨论】:

  • 感谢您的评论。我有这个 userId 属性: Template.secret.helpers({ isOwner: function () { return this.owner === Meteor.userId(); }
  • 这在 Posts.insert 中“所有者:Meteor.userId(),”。我应该使用“所有者”而不是 userId 吗?
  • 天哪!有效!多么愚蠢的错误……我花了 4-5 个小时……再次非常感谢您的帮助,大卫!到目前为止,你回答了我所有的问题。我真的很感激。
【解决方案2】:

您的出版物和订阅似乎有问题。确保您已正确发布和订阅。

/server/publications.js:

Meteor.publish("postsPub", function (selector, options) {
  return Posts.find(selector, options);
});

在您的路由器上:

this.route('myPosts', {
  path:'/my-posts',
    waitOn : function () {
      selector = {userId: Meteor.userId()};
      options = {sort: {createdAt: -1}};
      return Meteor.subscribe('postsPub', selector, options);
    },
    data:function(){
      return Posts.find({userId: Meteor.userId()});
    }
});

【讨论】:

  • 自动发布和不安全都被删除。是否可以在不重新安装它们的情况下执行此操作?在过去的 4-5 个小时里,我一直在尝试……是的。 4-5 小时... 停!
  • 感谢您的回答。不幸的是返回一个空页面。尝试用 this.userId 更改“Meteor.userId()”(在不同的地方使用)。现在尝试其他一些事情。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-08-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-02-06
  • 1970-01-01
相关资源
最近更新 更多