L4zl0w February 2016

Meteor: how to access another user's details?

Meteor.users.findOne() gives me back my user document.

Meteor.users.findOne({_id: 'my ID'}) gives me back my user document.

Meteor.users.findOne({_id: 'another users's ID'}) gives me back UNDEFINED.

This is obviously restricted by security. But how can I access another users's account details e.g. _id, name, profile, etc?

Answers


Nathaniel DSouza February 2016

Run it on the server like so:

Server:

Meteor.publish("otherUsers", function (userID) {
  return Meteor.users.findOne({_id: userID});
});

Client:

Meteor.subscribe("otherUsers", <userIdYouWantToGetDetailsFor>);

Then you can just do a Meteor.users.findOne on the client keep in mind you can only do it for your user and the userID that you passed in the meteor subscribe


David Weldon February 2016

You'll need to add a publisher for the user. Here's an example:

// The user fields we are willing to publish.
const USER_FIELDS = {
  username: 1,
  emails: 1,
};

Meteor.publish('singleUser', function (userId) {
  // Make sure userId is a string.
  check(userId, String);

  // Publish a single user - make sure only allowed fields are sent.
  return Meteor.users.find(userId, { fields: USER_FIELDS });
});

Then on the client you can subscribe like this:

Metor.subscribe('singleUser', userId);

or use a template subscription like this:

this.subscribe('singleUser', userId);

Security notes:

  1. Always check the arguments to your publishers, or clients can do bad things like pass {} for userId. If you get an error, make sure you meteor add check.
  2. Always use a fields option with the users collection. Otherwise you'll publish all of their secrets. See the "Published Secrets" section of common mistakes.

Post Status

Asked in February 2016
Viewed 3,306 times
Voted 6
Answered 2 times

Search




Leave an answer