21
votes

In my meteor.js app, I'm trying to write a simple admin page which can find a user by his/her email address.

I can see that in the Meteor.users collection there is an 'emails' array, which has objects like so

{ address : '[email protected]',
  verified : false
}

Normally in Mongodb I can search inside this 'emails' array like so :

Meteor.users.find({ emails.address : '[email protected]' });

But this query is throwing an error :

While building the application:
client/admin.js:224:41: Unexpected token .

Aka Meteor doesn't like the nested query...

Any ideas on how to query the Meteor.users collection by email address ?

6

6 Answers

58
votes

You can also use what you had, just put it in quotes:

Meteor.users.find({ "emails.address" : '[email protected]' });
29
votes

If on the server, Meteor has a special function for this : Accounts.findUserByEmail(email).

I believe this is the recommended way.

18
votes

Emails holds an array of emails. Each email has an address.

Try { emails: { $elemMatch: { address: "[email protected]" } } }.

Information on $elemMatch is here.

Information on emails as an array is here.

3
votes

By default, Meteor only publishes the logged in user and you can, as you mention, run queries against that user. In order to access the other users you have to publish them on the server:

Meteor.publish("allUsers", function () {
  return Meteor.users.find({});
});

And subscribe to them on the client:

Meteor.subscribe('allUsers');

And run the following command

Meteor.users.find({"emails": "[email protected]"}).fetch()

OR

Meteor.users.find({"emails.0": "[email protected]"}).fetch()

Refer this

3
votes

If you want to find all emails inside Accounts array, and do an insensitive query:

const hasUser = Meteor.users.findOne({
    emails: {
      $elemMatch: {
        address: {
          $regex : new RegExp(doc.email, "i")
        }
      }
    }
});
2
votes

One possible workaround, if this works on the server but not the client, is to use a users_by_email method on the server:

if (Meteor.isServer) {
    Meteor.methods({
        'get_users_by_email': function(email) {
            return Users.find({ emails.address: email }).fetch();
        }
    });
}
if (Meteor.isClient) {
    foo_users = Meteor.call('get_users_by_email', '[email protected]');
}