Fred J.
Fred J.

Reputation: 6019

Meteor check if a username exist in user collection

This Meteor client code attempts to check if a username exist in the users collection, It has been verified that it is but the if condition is evaluating to false. What am I doing wrong? How to fix it? Thanks

if (Session.get('taskSelected') == 'login') {
    var username = inputDoc[0].value + '-' + inputDoc[1].value;
    if (Meteor.users.findOne({username: username})) {
      console.log('found it in');
    }
}

edit

After the answer I realised that I do have this publish code in the server file

Meteor.publish('users', function () {
    if (this.userId) {
      return Meteor.users.find({_id: this.userId});
    }
 });

Upvotes: 0

Views: 2374

Answers (1)

Kishor
Kishor

Reputation: 2677

As your publication is returning only current user, the client side got only one record, which is the currently logged in user's record. If you want to access other users, you might need to do something like this.

Meteor.publish('users', function () {
    if (this.userId) {
        return Meteor.users.find({}, { fields: { 'services': 0 } }); //to return all users.. you might have to limit the users based on your requirements.
    }
});

Once you have this publication, you might need to check whether you have subscribed to this publication in your current template or not. If you didn't subscribe to this, the subscribe to it like this,

Template.yourTemplate.onCreated(function () { //replace "yourTemplate" with your template name.
    this.subscribe('users');
});

UPDATE:

If you want to check whether the username already exists or not, you need to call a server method like this,

On server:

Meteor.methods({
    'checkIfUserExists': function (username) {
        return (Meteor.users.findOne({username: username})) ? true : false;
    }
});

On client:

if (Session.get('taskSelected') == 'login') {
    var username = inputDoc[0].value + '-' + inputDoc[1].value;
    Meteor.call('checkIfUserExists', username, function (err, result) {
        if (err) {
            alert('There is an error while checking username');
        } else {
            if (result === false) {
                alert('username not found.');
            } else {
                alert('A user with this username already exists..');
            }
        }
    });
}

Upvotes: 2

Related Questions