Question

I'm trying to do a pub/sub for a chatroom function. What I need to do is, publish the subset of "Chatrooms" where it has field user1= current user id, or where it has field user2=current user id. So my code looks like this in coffeescript:

Meteor.publish "chatrooms1", publishFunction1 = ->
  Chatrooms.find
    user1: @userId

Meteor.publish "chatrooms2", publishFunction2 = ->
  Chatrooms.find
    user2: @userId

And in my subscription, I want it to only subscribe to chatrooms if the user is logged in:

Router.map () ->
  @route 'home',
  path: '/'

  waitOn: ->
    [
      Meteor.subscribe('users')
      Meteor.subscribe('instruments')
      Meteor.subscribe('instrumentList')
    ]
  if Meteor.user()
    waitOn: ->
      [
        Meteor.subscribe('chatrooms1')
        Meteor.subscribe('chatrooms2')
      ]

Not sure what I'm doing wrong here, the pub/sub doesn't really work so the page doesn't load. After this step, I was going to try to make the if Meteor.user() in the sub part reactive, but that will come later.

Was it helpful?

Solution

I think this is mostly a CoffeeScript problem - you can't have an if in the middle of an object literal like that (if ever in doubt, you can just paste the code into the 'try coffeesctipt' tab here). The compiled code doesn't add the 2nd waitOn to your route. Give something like this a try:

Router.map ->
  @route 'home',
    path: '/'

    waitOn: ->
      subs = [
        Meteor.subscribe 'users'
        Meteor.subscribe 'instruments'
        Meteor.subscribe 'instrumentList'
      ]

      if Meteor.user()
        subs.push Meteor.subscribe 'chatrooms1'
        subs.push Meteor.subscribe 'chatrooms2'

      subs

Alternatively, you can simplify your chatroom publications down a single function:

Meteor.publish 'chatrooms', ->
  return @ready() unless @userId
  Chatrooms.find $or: [{user1: @userId}, {user2: @userId}]

Note how it immediately returns ready if the user isn't logged in. Then your route would be:

Router.map ->
  @route 'home',
    path: '/'

    waitOn: -> [
        Meteor.subscribe 'users'
        Meteor.subscribe 'instruments'
        Meteor.subscribe 'instrumentList'
        Meteor.subscribe 'chatrooms'
    ]
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top