0

I am attempting to use JavaScript and MongoDB to check if a username is present in a dataset. I am looking to have it return a simple true or false statement. I am using the following syntax:

checkUserName = function (usernameIn) {

  User.findOne({username: usernameIn}, function(err, item) {
    if (err) throw err;
            if(item === null) {
              console.log("Does not exist")
                return false;
            }
            else {
                console.log("Username already exists.")
                return true;
            }

    });

However, when I call the function it only returns undefined instead of the true or false statements.

EDIT:

I do call var User = mongoose.model('Users') at the top of the script. The function does correctly execute the conole.log() operations, however it just does not return a result when I perform var result = checkUserName(username).

Many thanks

Dan
  • 449
  • 3
  • 16
  • It seems that "User" object is not accessible inside the function. – Luke P. Issac Oct 10 '16 at 07:28
  • Many apologises, I call var User = mongoose.model('Users'); at the top of the function. The console.log() events are correctly triggered, but the return of the function just provides as undefined. – Dan Oct 10 '16 at 07:43
  • 1
    This is because database operations are asynchronous. You will have to use promises or the callbacks to make sure that database read is complete at instant when you trying to use the return of the function. – Luke P. Issac Oct 10 '16 at 07:47

1 Answers1

0
Try This:

Write a callback to a function when it is called.

checkUserName = function (usernameIn,callback) {

  User.findOne({username: usernameIn}, function(err, item) {
    if (err) throw err;
            if(item === null) {
              console.log("Does not exist")
                return callback(false);
            }
            else {
                console.log("Username already exists.")
                return callback(true);
            }

    });
Shantanu Madane
  • 617
  • 5
  • 14