How to Reproduce Meteor.user() Client-Server effect for a different Collection?

80 views Asked by At

Just how Meteor.user() method is available on Client & Server for the "current user" I would love to reproduce this kind of functionality for different custom collections. For example, my app uses a "clouds" collection as a type of room for a group of users to be in. Obviously there are various cloud instances and I don't always want to be passing the cloudId into every single meteor method. Ideally I could have like a Meteor.cloud() function that would give me the current cloud on the client and server.

My thoughts on approaching this:

  1. What I have been doing thus far is piggy-backing off of Meteor.user() by storing a currentCloudId property inside the user profile and setting that on a route beforeAction. However this limits the user to only being in 1 cloud at a time.

  2. Using the Meteor.connection ID somehow to keep a map of connectionIds to cloudIds. This would work great in theory....however it seems that Meteor connection IDs cannot be heavily relied on as they might change during reconnects or other random scenarios. Also you would have to then "manange" that collection of "cloudConnections" and remove old stale ones and such.

  3. Im using Iron Router....and if it were possible to get the current route data on the server that would also solve my problem but I am not sure how to access that on the server?

--- Basically I would love for a simple straight forward way to mimic Meteor.user() behavior for other collections.

Thanks for all your help :)

1

There are 1 answers

1
halbgut On

You can just create a function inside /lib that looks something like this:

getUserClouds = function getUserClouds () {
  return Clouds.find({ $elemMatch: { $eq: Meteor.userId() } })
}

This will work both on the client and on the server. But it will always return a Cursor pointing to 0 docs. So you'll need a publication:

Meteor.publish('userClouds', function () {
  return Clouds.find({ $elemMatch: { $eq: this.userId } })
})