0

I have this Meteor method on my server:

returnUsers: function(){
        console.log(Meteor.users.find());
}

And the following call on my client:

'click #share_button': function(ev){
        ev.preventDefault();
        Meteor.call('returnUsers');
 }

But it returns an empty array:

LocalCollection.Cursor {collection: LocalCollection, sorter: null, _selectorId: undefined, matcher: Minimongo.Matcher, skip: undefined…}

How do I return an array of all users?

redress
  • 1,399
  • 4
  • 20
  • 34

1 Answers1

2

You need to fetch the documents in order to return an array from your method. Something like this:

returnUsers: function() {
  var selector = {};
  var options = {fields: {username: 1}};
  return Meteor.users.find(selector, options).fetch();
}

Note that it's critical that you filter the fields in order to avoid sending all of your users' secrets to the client. For more information see the "published secrets" section in my common mistakes article.

It's hard to say without knowing your use case, but instead of using a method, it may make more sense to publish some subset of users to your client, rather than fetching all of them on an event.


In order to get the result back from the server, you should invoke the method like this:

Meteor.call('returnUsers', function(err, users) {
  console.log(users);
});
David Weldon
  • 63,632
  • 11
  • 148
  • 146
  • right now Im just trying to prove that I can get a list of users upon a click event; this is in order for current user to share a document with other users. pubsub or method? – redress Mar 31 '15 at 16:53
  • A method may be appropriate if you only need the users within that event. A publish would be a better choice if you need those users in several places. In either case, I'd recommend adding some kind of selector so you don't return __all__ of the users. – David Weldon Mar 31 '15 at 17:07
  • when I use this method `console.log(Meteor.users.find().fetch());` it only returns the logged in user? – redress Mar 31 '15 at 17:13
  • On the client that will be true, unless you published all of the users. On the server, it will return all users in the database. Make sure to use a callback on your `Meteor.call` so you get the result from the server. – David Weldon Mar 31 '15 at 17:22
  • what would that callback look like? i currently dont have one because Im not passing a parameter from the client to the server – redress Mar 31 '15 at 17:24
  • I added an example to the answer. – David Weldon Mar 31 '15 at 17:31
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/74206/discussion-between-redress-and-david-weldon). – redress Mar 31 '15 at 17:33
  • how would i call this meteor method to populate a template helper? – redress Mar 31 '15 at 20:57
  • See the answers [here](http://stackoverflow.com/questions/22147813/how-to-use-meteor-methods-inside-of-a-template-helper). – David Weldon Mar 31 '15 at 21:11