Maybe this very strange question, I would like to get current logged in user ID outside publish method.
Reason is I want to connect two Remote collection is user is on paid plan example:
if (user.isPaid) { //use normal mongo connection Items = new Mongo.Collection("items", {idGeneration: 'MONGO'}); } else { //user different connection let dbConn2 = "mongodb://user:pass@mymongo.com/dbname"; let database2 = new MongoInternals.RemoteCollectionDriver(dbConn2); Items = new Mongo.Collection("items", {idGeneration: 'MONGO', _driver: database2}); }
So, to initialise this collection on server side, I need to know current user ID.
Now, the question is, what is the reason that you call your function outside of methods.
Further from the guide:
On the server, each connection has a different logged in user, so
there is no global logged-in user state by definition. Since Meteor
tracks the environment for each Method call, you can still use the Meteor.userId()
global, which returns a different value depending on which Method you
call it from, but you can run into edge cases when dealing with
asynchronous code. Also, Meteor.userId() won’t work inside publications.
We suggest using the this.userId property on the context
of Methods and publications instead, and passing that around through
function arguments to wherever you need it.
So you can also pass the userID from the publication or method, where you get it either as Meteor.userId() or this.userId().
But yeah, @sashko the docs are not precise here, they state we can use Meteor.userId() anywhere but publications, while the guide says we actually can’t.
@pinku1 if you don’t want to pass the Id from the method or publication for some reason, you could also try Meteor.users()._id, it may work.
Lol, I meant Meteor.user()._id, not users. But I guess if Meteor.userId() doesn’t work, this one won’t work too.
Anyways, I’m glad it’s working now with new approach. If it was me, I’d probably call your function in user publication aand pass this.userId(), but whatever works is fine.
I have the same issue where I have a separate Mongo Database per user. To know the name of the Database I connect to I have to check the user collection. How did you solve this? Do you still need the user in your new approach or did you find a way around this?
Yes this.userId only works in Methods and Meteor.userId() in publish. Outside publish and meteor methods there is no way to tell what user you are. The reason is because the Server has no per user state tracking. Methods and Publish functions do because they use the DDP Protocol and get called from User requests.