【问题标题】:How to handle "relations" with MongoDB / Meteor如何处理与 MongoDB / Meteor 的“关系”
【发布时间】:2015-05-11 02:12:58
【问题描述】:

我仍在使用 Meteor.js 应用程序,并且希望在我的页面上显示当前用户朋友的所有帖子。

目前,我只是像这样展示每个帖子:

talkthreads: function(){
  return Posts.find({parent: null},{sort: {date: -1}});
}

但我想做一些尽可能简单/有效的事情来过滤它们,并且只从用户的朋友那里得到一个。

类似的东西:

talkthreads: function(){
        return Posts.find({parent: null, owner: [match one of my friend id]}, {sort: {date: -1}});
    }

就像我对 SQL 所做的那样。

另一点是我目前将我的帖子集合发布给所有客户。但由于它的目标是与时俱进,我不想将所有帖子发布给每个客户。

我怎样才能只发布和订阅我或我的朋友拥有的帖子,并且数量有限:我不想一次加载超过 15 个最后的帖子。当我点击一个按钮时,我又加载了 15 个(比如在 FB 上,当你在页面底部滚动时,它会自动附加旧帖子)。

感谢您的帮助。

【问题讨论】:

    标签: javascript mongodb meteor


    【解决方案1】:

    您要求的是客户端加入。假设 Meteor.user().profile.friends 是一个用户 ID 数组,这样的东西应该在你的助手中工作:

    talkthreads: function() {
      // select owners who are friends of the current user
      // see the publish example if you want to include your own posts
      var owners = Meteor.user().profile.friends || [];
    
      var selector = {
        parent: null,
        owner: {$in: owners}
      };
    
      return Posts.find(selector, {sort: {date: -1}});
    }
    

    您问题的后半部分是关于分页的。这可能最好作为一个单独的问题提出,但这里有一个关于如何设置发布者的想法:

    var POSTS_PER_PAGE = 15;
    
    Meteor.publish('paginatedPosts', function(pageNumber) {
      // fetch the current user because Meteor.user() isn't available here
      var user = Meteor.findOne(this.userId);
    
      // get an array of user ids for the user's friends
      var owners = user.profile.friends || [];
    
      // also add the current userId to the list of owners
      owners.push(this.userId);
    
      var selector = {
        parent: null,
        owner: {$in: owners}
      };
    
      // publish a limited set of posts based on the current page
      var options = {
        limit: POSTS_PER_PAGE * pageNumber,
        sort: {date: -1}
      };
    
      return Posts.find(selector, options);
    });
    

    在客户端上,您需要跟踪当前页面(从 1 开始,每次他/她单击“加载更多”按钮时递增)并在页码更改时激活订阅。例如:

    Tracker.autorun(function() {
      var pageNumber = Session.get('currentPage') || 1;
      Meteor.subscribe('paginatedPosts', pageNumber);
    });
    

    当然,这可能是模板自动运行、全局或在您的路由器中,这取决于对您的应用有意义的情况。

    【讨论】:

    • 非常感谢您的提示。想到这两点在我脑海中提出了其他人的问题,我将分别问他们。再次感谢
    【解决方案2】:

    我假设您的用户有一组好友 _id,您可以使用它们进行查询。在这种情况下,您希望执行如下查询:

     Posts.find({parent: null, owner: Users.find({_id: user_is}, {friends: 1, _id: 0})}, {sort: {date: -1}});
    

    基本上,您可以使用 Mongo 嵌套搜索,就像这样,获取您需要的数据。

    【讨论】:

    • 顺便说一句,我是在手机上输入的,并没有检查以确保其格式完美且正常工作。但它应该让您了解嵌套搜索。
    • 所以我必须在所有者元素中添加朋友 id 的数组?该数组目前在 user().profile.friends 中
    • 您刚刚为对象创建了所有者搜索,仅使用 Users.findOne(user_id).friends 不是更好吗?
    猜你喜欢
    • 2011-11-29
    • 1970-01-01
    • 2020-10-09
    • 2018-09-17
    • 1970-01-01
    • 2017-06-18
    • 2021-10-07
    • 2011-02-09
    • 1970-01-01
    相关资源
    最近更新 更多