KindOfGuy
KindOfGuy

Reputation: 3211

Meteor find all user emails

I'm trying to gather all user emails on a Meteor server function (to send to all on an event). I have tried many constructions and have got to this:

/server/lib/mail/mailNewEvent.js

Meteor.users.find({}, {transform: function(doc) {return doc.profile}}).fetch();

which returns:

[ { name: 'Tardar',
    email: '[email protected]',
    _id: 'YyEk2sLDiQoBjC6gS' },
  { name: 'Chutney',
    email: '[email protected]',
    _id: '4Dyaa5wRmxmq7j7XF' } ]

I tried to change the above transform to return the email field with:

return doc.profile.email

but: "Transform functions must return an object" and that gives a variable.

I have also tried:

Meteor.users.find({}, {fields: {'profile.email': 1, _id:0}}).fetch();

which returns:

[ { profile: { email: '[email protected]' } },
  { profile: { email: '[email protected]' } } ]

Can I make this happen with find's own functionality or do I have to act on the array separately?

Upvotes: 0

Views: 319

Answers (2)

Kuba Wyrobek
Kuba Wyrobek

Reputation: 5273

Have you tried this :

Meteor.users.find({}).map(function(user){
   return user.profile.email
})

Documentation

Upvotes: 1

Carlos Rodrigues
Carlos Rodrigues

Reputation: 160

You can use a function from underscore.js named map (reference):

var emails = _.map(Meteor.users.find({}, {fields: {'profile.email': 1, _id:0}}).fetch(), function(user) {
    return user.profile.email;
});

Or even shorter with pluck (reference):

var emails = _.pluck(Meteor.users.find({}, {fields: {'profile.email': 1, _id:0}}).fetch(), 'profile.email');

They'll iterate over the result and produce an array with the desired data

Upvotes: 1

Related Questions