从文档中查找并限制数组中的数组值

find and limit array values in an array from a document

我可以用 facebook 来解​​释我的问题,

获取一个新闻提要(一个post),其中有

post-内容、图片、视频

赞、评论、分享

我将 post_content、图片、视频(仅限 URL)和点赞计数保存在一个名为 post

的集合中

以及另一个名为 post_likes

的集合中的所有点赞

现在在时间轴上我从 db

中获得前 10 posts
Posts.find({},{sort: {createdAt: -1}}.limit(10)

现在,每当用户点击赞时,我都会调用一个将用户 ID 插入集合的方法

post_likes.update({post_id:id},{$push:{userids: this.userId}})

post_likes对象

{_id:"xxxx",post_id:"Id of the post",userids:["xxx","yyy",....]

我在我的模板中显示使用

{{#each posts}}
.............
.........
........
.......
 {{#if likes}}
 //show dislike button
 {{else}}
 //show like button
 {{/if}}
{{/each}}

我的问题是

我想知道当前用户是否特别喜欢post。

我无法将所有 liked_users 加载到客户端并检查。

所以我只想将一个值从数组发布到客户端

怎么做?

或者是否有任何替代方法可以做到这一点,欢迎和赞赏任何想法。

有几种选择:

  1. 为每个用户发布post_likes

    Meteor.publish('user_post_likes', function() {
        return post_likes.find({userids: this.userId});
    });
    
  2. 将 post id 附加到用户文档,反之亦然:

    post_likes.update({post_id:id},{$push:{userids: this.userId}}); // AND
    Meteor.users.update({_id: this.userId}, {$push: {'profile.post_likes': id}});
    

    然后您将在 Meteor 自动订阅的用户文档中看到喜欢的内容。如果需要,您可以使用 matb33:collection-hooks 之类的东西来保持两个集合同步。

  3. 写一个方法来按需检索喜欢的post:

    Meteor.methods({
        get_liked_posts: function() {
            return post_likes.find({userids: this.userId});
        }
    });
    

第三个较少 "meteoric",但如果让大量用户独立订阅他们自己的 posts_likes 订阅对服务器来说是一项艰巨的工作,则可能更可取。但是,在那种情况下,选项 2 可能更可取。