Modifying Publications

I have the following collection:

  return Posts.find({
    networkId: user.networkId
  }, {
    sort: {createdAt: -1},
    limit: limit
  });

It has a field called likers which is used to check if you liked the post already. I have an API call that returns posts using this publication function. Instead of returning all the likers, I want to add another field didILike before returning the collection. If a publication function was returning objects, I could simply use something like _.extend but in this case, we are returning a cursor.

Is there a way to add or modify a field of a collection inside publication?

Hi @woniesong!

This will be a tricky one, here we go:

Publication:

Meteor.publish('likers-posts', function (limit) {
  var self = this;
  // I assume, that you are using Accounts 
  // from Meteor for setting userId inside DDP
  if(!this.userId) {
    return this.ready();
  }
  
  var user = Meteor.users.findOne(this.userId, {
    fields: {
      networkId: 1
    }
  }); 

  function transformPost(post) {
    post.didILike = post.likers.indexOf(self.userId) !== -1
    delete post.likers;
    return post;
  }

  var handle = Posts.find({
    networkId: user.networkId
  }, {
    sort: {createdAt: -1},
    limit: limit || 20 // what if someone doesn't pass limit? Error!
  }).observe({
    added: function (post) {
      self.added('posts', post._id, transformPost(post));
    },
    changed: function (post) {
       self.changed('posts', post._id, transformPost(post));
    },
    removed: function (post) {
       self.removed('posts', post._id)
    }
  });

  this.onStop(function () {
    handle.stop();
  });
});

This should work :wink:

1 Like