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