sana
sana

Reputation: 133

Display list of user email addresses in Meteor

I'm trying to get a list of all users in meteor using Metor.methods

This is my code : server/main.js

Meteor.methods({
  'createUser': function(){
    if (Meteor.users.find({}).count()===0) {
      for (i = 0; i <= 5; i++){
        let id = Accounts.createUser({
          email: Meteor.settings.ADMIN_USE,
          password: Meteor.settings.ADMIN_PASSWORD,
          profile: { firstName: Meteor.settings.ADMIN_FIRSTNAME, lastName: Meteor.settings.ADMIN_LASTNAME }
        });
       }
     }
   },

  'returnmail': function(){
    return Meteor.users.findOne().emails[0].address;
  }
});

then i call this function in another file called Listusers.js:

Template.ListUsers.helpers({
  email: function(){
    Meteor.call('returnmail');
  },
});

I'm trying to display the value of email using this code but it doesn't work

Client/ListUsers.html

<Template name="ListUsers">
  <input id="mail" type="text" value="{{email}}" />
</Template>

Upvotes: 4

Views: 1704

Answers (1)

Michel Floyd
Michel Floyd

Reputation: 20226

Several problems. I strongly recommend you go through the tutorial at least. The Discover Meteor ebook is also invaluable. One of the first steps in understanding Meteor is moving from a traditional XHR request-response model to publish-subscribe.

  1. Your email helper needs to return a value.
  2. Meteor.call() doesn't return anything. Normally you use it with a callback that gives you an error status and the result. However you can't use that in a helper unless you use a Session variable or a promise because the return value from the call is at the wrong context level.
  3. Your returnmail method is only returning a single email address from findOne() and not any specific one either, just a quasi-random one (you can't guarantee which document findOne() is going to return!)
  4. You're creating 5 identical users with the same email address and password. 2-5 are going to fail because of a uniqueness constraint on the email field.

Now on to the solution.

  1. On the server, publish the Users collection including only the emails field (which is an array of objects)
  2. On the client, subscribe to that publication.
  3. On the client, iterate over the users collection and get the email address from a helper.

server:

Meteor.publish('allEmails',function(){
  // you should restrict this publication to only be available to admin users
  return Meteor.users.find({},{fields: { emails: 1 }});
});

client js:

Meteor.subscribe('allEmails');

Template.ListUsers.helpers({
  allUsers(){ return Meteor.users.find({}); },
  email(){ return this.emails[0].address; }
});

client html:

<Template name="ListUsers">
  {{#each allUsers}}
    <input id="mail" type="text" value="{{email}}" />
  {{/each}}
</Template>

Upvotes: 3

Related Questions