I am trying to simply update a global variable within a function but am running into an issue. Its simply not updating and firing the code below as result.
The results for console.log(duplicates) seem to be in wrong order which Im assuming is the cause of the problem.
This is in AngularJS, but I dont think this is related to the problem
Expected output in console when a user
is found:
1
0
Output Im getting:
0
1
module.exports.register = function (req, res) {
var duplicates = 0;
var user = new User();
user.name = req.body.name;
user.email = req.body.email;
user.cro = req.body.cro;
user.companyname = req.body.companyname;
user.setPassword(req.body.password);
// first, check that this email address has not been registered before
User.findOne({email: req.body.email}, function (err, user) {
// Return if user not found in database
if (!user) {
console.log('great, no user was found, we may carry on');
} else {
res.status(401).json({
"error": "This email address has already been registered."
});
duplicates = 1;
console.log(duplicates);
}
});
console.log(duplicates);
if (duplicates == 0) {
/* Fire this code if this duplicates has not updated to 1 */
}
};