Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I add temp. fields to a Meteor publish

Is there any way to add an temp extra field on the server inside of a publish function? I can't seem to get observe or transform to work.

I have two subscriptions for the same collection 'listings'. There are times when I want to subscribe to certain listings so they're available for the chatroom list... but the problem is they're showing up in my 'listings' template. The unique part was on the server for performance (large array).

Ideally I wish I could add an extra field like 'forChat:true' so that I can check for that in the listings template and only pull in listings that dont have a 'forChat' field.

Currently i'm getting around it by sending down the 'liked' & 'disliked' array in each listing so the listings template can check if the user's id is inside of it. However this won't scale well with time (and on mobile) due to the length ~= (users / 2).

// ideal-ish pseudo code if we could return arrays:

Meteor.publish('chats', function(id) {
    lists = Listings.find(...).fetch();

    return lists.map(function(list){
        return list.forChat = true;
    });
});

Is this even possible? Kind of hacky, but I suppose I could add the field to every listing and omit it on the rest of the publications.

Working code from accepted answer below:

Meteor.publish('listingsForChats', function(id) {
    var cursor = Listings.find(...);

    // insert a temp `forChats:true` field to filter in listings template
    cursor.forEach(function(doc) {
      doc.forChats = true;
      this.added('listings', doc._id, doc);
    }, this);

    this.ready(); 
});
like image 451
SkinnyGeek1010 Avatar asked Jan 15 '14 01:01

SkinnyGeek1010


1 Answers

Yes, that is possible. See my answer here: How to 'transform' data returned via a Meteor.publish?

It basically comes down to the extended example of publish in the meteor documentation: http://docs.meteor.com/#meteor_publish.

like image 51
Christian Fritz Avatar answered Nov 07 '22 08:11

Christian Fritz