Guima Ferreira
Guima Ferreira

Reputation: 195

Meteor.users subscribe only return current user

I'm trying to get a user by the username, when I use Meteor.users.findOne, it always return the current user. And if I user Meteor.users.find, it returns all current user document, and the profile.firstName and profile.lastName of the right matched username.

Meteor.publish('userByUsername', function(username) {
    return Meteor.users.findOne({
        username: username
    }, {
        fields: {
            'profile.firstName': 1,
            'profile.lastName': 1,
        }
    });
});

How can I get only the user that match with the username?

Upvotes: 0

Views: 673

Answers (2)

Tomas Hromnik
Tomas Hromnik

Reputation: 2200

findOne finds and returns the first document that matches the selector. Publish method needs to return a cursor, you need to use find, instead of findOne:

Meteor.publish('userByUsername', function(username) {
    return Meteor.users.find({
        username: username
    }, {
        fields: {
            'profile.firstName': 1,
            'profile.lastName': 1,
        }
    });
});

Then you can call subscribe on the client:

Meteor.subscribe('userByUsername', 'bob');

And call Meteor.users.findOne({ username: 'bob' }); in your helper for example.

Upvotes: 0

k.chao.0424
k.chao.0424

Reputation: 1191

I think what you want is not publish, but a method access to particular username. Publish/Subscribe is great for datasets that often change - say posts on stackoverflow, facebook feed, news articles, etc.

You are looking to get first/last name of a particular user, this does not really change. So what you actually want is to create a server method that returns the first/last name of the user. And you can call this method from the client to access this data.

if (Meteor.isClient) {

  //get username var
  Meteor.call('findUser', username, function(err, res) {
    console.log(res.profile.firstName + " " + res.profile.lastName);
  });

}

if (Meteor.isServer) {

  Meteor.methods({
    findUser: function(username) {
      return Meteor.users.findOne({
        username: username
      }, {
        fields: {
          'profile.firstName': 1,
          'profile.lastName': 1
        }
      });
    }
  });

}

Notice that the client Meteor.call has a callback method. DB queries on Meteor server is asynchronous & non-blocking, so you need to access the result via a javascript callback function.

Upvotes: 1

Related Questions