KidBatman
KidBatman

Reputation: 595

Javascript running "out of order"

I am attempting to do a simple user signup, but am having trouble getting the proper checks for creating duplicate user's to run in the sequence I am intending:

route:

app.post('/user/new', user.create);

user.create:

exports.create = function(req, res) {
var exists = DoesUserExist(req, res);
console.log(exists);
if (exists === true){
    console.log("exists");
    res.redirect('/user/new');
}
else{
    //good to create user since it does not exist yet
    CreateUser(req, res);
    console.log("does not");
    res.redirect('/user/new');
}
 };

helper funcs:

function DoesUserExist(req, res){
var post = req.body;

mongo.connect("mongodb://localhost:27017/db", function(err, db){
    if(err) { return console.dir(err); }

    var collection = db.collection("users");
    collection.find({username: post.username}).count( function( err, count ){
        if (count > 0){
            console.log(count);
            return true; //already exists
        }
        else{
            console.log(count);
            return false; //does not exist
        }
    });
});
}


function CreateUser(req, res){
var post = req.body;

//connect to db server
mongo.connect("mongodb://localhost:27017/", function(err, db){
    if(err) { return console.dir(err); }

    var collection = db.collection("users");
    collection.insert({username: post.username, password : post.password}, function(error, doc){});
});

return;
}

after running the program again to see if I can add a duplicate username, my console logs return:

undefined
does not
POST /user/new 302 4ms - 74b
1

and my mongodb shows a duplicate record. The flow of the program is not adhering to what I perceive it to be. Am I failing to use a callback appropriately in this case? I am still new to javascript and would like some pointers/critiques. Thanks.

Upvotes: 3

Views: 2696

Answers (1)

BraveNewCurrency
BraveNewCurrency

Reputation: 13065

You need to read up on callbacks, because node programming is all about callbacks.

When you call DoesUserExist(), it calls mongo.connect() and immediately returns. (You can put "console.log('hi')" at the end of DoesUserExist() to verify it's called before your "if count > 0" code.) The Mongo.connect() routine takes a callback, so it is not a simple synchronous function. It calls that function (as a callback) only when the results of the query are ready. Therefore, the "return" isn't returning from DoesUserExist, but from your anonymous function passed to the mongo driver.

Instead of "return true/false", you need to call you "res.redirect" logic. You can do this by taking the "if/then" code in user.create and turn it into an anonymous function. Pass that to DoesUserExist(), which will call it in the "count" callback.

When the "count" callback runs and calls your anonymous function, it will have: 1) the value of count, and 2) the req/res object to do the redirect on.

I could write the code for you, but it's really something you need to play with and read up on until you get the "aha" moment to understand all callbacks.

Upvotes: 2

Related Questions