Petrov
Petrov

Reputation: 4250

meteor.js : find users by email

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 ?

Upvotes: 21

Views: 25166

Answers (6)

Liko
Liko

Reputation: 2300

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")
        }
      }
    }
});

Upvotes: 3

Alexandre Bourlier
Alexandre Bourlier

Reputation: 4118

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

I believe this is the recommended way.

Upvotes: 29

Jagdish Barabari
Jagdish Barabari

Reputation: 2703

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

Upvotes: 3

Tarang
Tarang

Reputation: 75945

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

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

Upvotes: 57

user728291
user728291

Reputation: 4138

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.

Upvotes: 18

Christian Ternus
Christian Ternus

Reputation: 8492

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]');
}

Upvotes: 2

Related Questions