1

I'm trying to figure out the best way to publish and subscribe to Posts from certain authors in a Meteor App. I currently have a user setup where a list of ID's are stored in an array "friendsList". Ideally I'd like to know the best way for a user to subscribe to the posts from only the people in that array.

Here's what a user looks like in Mongo:

{ "_id" : "aLxQ2Rx7PfMLB4Ywe", "createdAt" : ISODate("2015-03-18T06:07:40.973Z"), 
"profile" : { 
    "facebookId" : "1380125628976610", 
        "friendsList" : [  "1377888062534633", "1377888062534443" ], 
        "name" : "Charlie Amicgeegfkb Fallersky" }, 
        "services" : { 
            "facebook" : { "accessToken" : "CxI", "expiresAt" : 1431821993739, "id" : "1380125628976610",
             "email" : "ucymsfy_fallersky_1426550919@tfbnw.net", 
             "name" : "Charlie Amicgeegfkb Fallersky", "first_name" : "Charlie", 
             "last_name" : "Fallersky", 
             "link" : "https://www.facebook.com/app_scoped_user_id/1380125628976610/", 
             "gender" : "male", "locale" : "en_US" }, 
        "resume" : { 
            "loginTokens" : [   {   "when" : ISODate("2015-03-18T06:07:40.977Z"),   
            "hashedToken" : "jVUmNuzQ1oloWi24KVgvlcbxG8hCPTWn22CTlJnPJEs=" } ] } } }

What I'd ideally like to happen is at the router level:

Router.configure({
    layoutTemplate: 'layout',
    loadingTemplate: 'loading',
    notFoundTemplate: 'notFound',
    waitOn: function(){ 
        return 
            //Meteor.subscribe(to all the posts where from people in the friends list);
}
});

Right now I'm currently publishing all of the Posts, but wondering if that's the best way to do it as well.

codycodes
  • 95
  • 8

1 Answers1

1

You can write a publish function like this:

Meteor.publish('postsByFriends', function() {
  var user = Meteor.users.findOne(this.userId);
  var friends = user.profile.friendsList || [];
  return Posts.find({author: {$in: friends}});
});

Be aware that this publish is not reactive, so if a user adds a fiend while the subscription is running, the posts will not be published. For more information of reactive joins, see this question.

David Weldon
  • 63,632
  • 11
  • 148
  • 146