How to retrieve email address on server

I am trying to access a users email address from the isServer using a user id and for some reason it is not working. I want to search through the MessagesList collection to find messages that below to the current user by email or user id. Is there a different way to access the email while on the server side?

Meteor.publish(“messagesList”,function(){
var currentUserId = this.userId;
var currentUserEmail = Meteor.user.emails[0].address;
console.log(“test text”)
return MessagesList.find({$or: [{createdBy: currentUserID}, {email: currentUserEmail}]});
});

I am subscribed and everything, just getting this error:
I20160425-20:43:46.137(-7)? Exception from sub messagesList id SyjBvWtTEwu8qw7fC TypeError: Cannot read property ‘0’ of undefined
I20160425-20:43:46.138(-7)? at Subscription._handler (server/server.js:10:25)
I20160425-20:43:46.138(-7)? at maybeAuditArgumentChecks (packages/ddp-server/livedata_server.js:1704:12)
I20160425-20:43:46.138(-7)? at Subscription._runHandler (packages/ddp-server/livedata_server.js:1026:17)
I20160425-20:43:46.138(-7)? at Session._startSubscription (packages/ddp-server/livedata_server.js:845:9)
I20160425-20:43:46.138(-7)? at Session.sub (packages/ddp-server/livedata_server.js:617:12)
I20160425-20:43:46.138(-7)? at packages/ddp-server/livedata_server.js:551:43

Anyone suggestions?

You need to do a search of the users collection.
The server doesn’t have ‘Meteor.user()’ available to it.
Only this.userId.

So this:

Meteor.users.findOne(this.userId)

(I’m on mobile, could be slightly incorrect)

1 Like

I think that returns the user id. I am looking to get the user email from the user id

thanks

No,

const user = Meteor.users.findOne(this.userId);

returns the user. Afterwards you can do stuff like

const email = user.emails[0].address;
...
2 Likes

Thank you so much!!! that worked!

Thanks @jhuenges for clearing that up :slight_smile:

@mfhawley - this is how you could diagnose the errors you saw:

Your original error was: Cannot read property '0' of undefined because your call Meteor.user.emails[0].address failed… because of that you should see that this meant your call to Meteor.user.emails didn’t work. The reason is because Meteor.user() is only available on the client (you had this incorrect anyway, missing the parenthesis). So replacing Meteor.user with the findOne you’re all good! :smiley:

1 Like