Search code examples
meteorchatpublish-subscribe

meteor .publish on server side: working with a client variable


I am building a chat and based on the chatroom selected by the currentUser, I want to publish messages with this function:

Meteor.publish('messages',function(){
  return Messages.find(
    {chatId: 'QMMjBgCvLcnLvJPvx'},
    sort:{timestamp: -1}
  });
});

Now the chatId is still hardcoded, but it needs to be dynamic. The chatId is passed in the URL(e.g..../chat/QMMjBgCvLcnLvJPvx). In the client based code I have used to read the chatId:

var chatId = Router.current().params._id;

Iron Router

But this doesn't work server side. Is there a way to send the chatId from the URL to the server so I use Meteor.publish as mentioned above. Any help appreciated :)


Solution

  • Pass in the variable when you subscribe I.e.

    Meteor.subscribe("messages", {chatId: Session.get("current-room")})
    

    In the publication:

    Meteor.publish('messages',function(chatId){
      return Messages.find(
        {chatId: chatId},
        sort:{timestamp: -1}
      });
    });