Search code examples
javascriptnode.jsmeteorrelationships

Meteor : how to make Relationships one to many?


I am trying to create a follower system like twitter and I want to show posts only for following users. I'm not sure about my publish code.

I have 2 collections:

1- Posts {
  "_id": "3HrXtbHZ8WqHJJpyC",
  "post": " some text",
  "owner": "Wdc84ED9zt4Ssxsh4",
  "username": "MJK",
  "createdAt": "2016-01-28T11:53:33.253Z"
}

2- Follwers {
  "_id": "ShKWgeaP9BFPuQWwL",
  "follower": "MJK",
  "following": "michael"
}

publish code

Meteor.publish('posts', function() {
  var user = Meteor.users.findOne({_id: this.userId}).username;
  var follower = Followers.find({followers: user}).following;
  var posts = Posts.find({username: {$in: follower}});
  return posts;
});

subscribe

Meteor.subscribe('posts');

client code

Template.content.helpers({
  'posts': function(){
    return Posts.find({}, {sort:{createdAt: -1}});
  }
});

HTML

{{#each posts}}
<li class="collection-item avatar">
  <span class="title"><a href="/{{username}}">{{posts.username}}</a></span>
  <p>{{time}}
{{post}}
{{/each}}

But no posts appear in the browser. I think my publish code is wrong. Can anyone help me please?


Solution

  • Change your follower line to this:

    var follower = Followers.find({follower: user}).fetch().map(function(follower) {
        return follower.following;
    });
    

    The changes I made:

    1. Changed followers: user to follower:user because I don't see a followers property in your Followers collection.
    2. Added the fetch() after your find() query to return an array instead of a cursor.
    3. Used .map() to transform your array of objects into an array of username strings to feed to posts.