0

I'm an apprentice to a software developer, so I haven't much experience with MongoDB and ExpressJS.

My task is to insert the new user into the database (MongoDB). Before that I want to assure, that the name doesn't exist in the database. If the username doesn't exist in the database, then I want to proceed the task with inserting the new user.

The following code is for ExpressJS (but the Model 'user' of MongoDB works!):

router.post('/signUp', function(req, res, next) {
    var contents = req.body;
    var pass;

    var search = user.findOne({username: contents.username});
    search.exec(function (error, user) {
        if (error) {
            res.status(500).json({failure: "An error has occured:\t" + error});
            pass = false;
        }
        if (user) {
            res.status(500).json({failure: "Username is already forgiven!\nPlease choose another username."});
            pass = false;
        } else pass = true;
    });

    console.log("Shall I insert the new user? " + pass);

    if (pass) res.status(200).json({success: "You were signed up!"});
    else res.status(500).json({failure: "You cannot sign up, because there's an internal error!"});
 });

The one thing is that pass will be always undefined, whetheter the data exists or not.

This seems for me very strange, but the global variable 'pass' was declared before the function 'search.exec()'.

What is wrong with my code?
Many thanks in advance for your help.

Best regards
t.koelpin

EDITED 04.05.2015 - 13:15 h

I solved the problem with the following code:

var search = user.findOne({username: contents.username});
search.exec(function (error, user) {
    if (error) res.status(500).json({failure: "An error has occured:\t" + error});
    if (user) res.status(500).json({failure: "Username is already forgiven!\nPlease choose another username."});
    else {
        // Code for the insertions to MongoDB
        res.status(200).json({success: "You were signed up!"});
    }
});
t.koelpin
  • 57
  • 9
  • 1
    because the exec is an async operation, when you do if(pass), the code inside the exec actually has not been executed yet. The correct way to do this is: move the if(pass) check to be under the if(user) check inside the exec block. – Surely May 04 '15 at 10:19
  • 1
    the callback provided for search.exec is executed asynchronously. So when if(pass) is executed pass is not assigned any value. you should move this inside the search.exec callback for it to work – wallop May 04 '15 at 10:25

0 Answers0