简体   繁体   中英

Node.js check if user already exists

Hello guys I am trying to check if a user already exists in the database, I have managed to stop creating a user if one already exists with the same name, however I do not seem to get the error message displayed. I am not too sure why my error is not being handled correctly. Here is my code:

 // Register User
    router.post('/register', function(req, res){
        var name = req.body.name;
        var email = req.body.email;
        var username = req.body.username;
        var password = req.body.password;
        var password2 = req.body.password2;

    //Validation
    req.checkBody('name', 'Name is required').notEmpty();
    req.checkBody('email', 'Email is required').notEmpty();
    req.checkBody('email', 'Email is not valid').isEmail();
    req.checkBody('username', 'Username is required').notEmpty();
    req.checkBody('password', 'Password is required').notEmpty();
    req.checkBody('password2', 'Passwords do not match').equals(req.body.password);

    var errors = req.validationErrors();

    if(errors){
        res.render('register',{
            errors:errors
        });
    }else{var newUser = new User({
        name: name,
        email:email,
        username: username,
        password: password
    });

    User.getUserByUsername(username, function(err, user){
        if(err) throw err;
        if(user){
            return new Error('User already exists!');
        }else{
            User.createUser(newUser, function(err, user){
                if(err) throw err;
                console.log(user);
            });
        }
    });


    req.flash('success_msg', 'You are registered and can now login');

    res.redirect('/users/login');
    }
});

This will work exactly as you wish.I had the same issue trying to make it work and I assure you it does. Cheers!

User.getUserByUsername(username, function(err, user){ //must check if user exists
  if(err) throw err;
  if(user){
    console.log('existing...'); //may be deleted
    req.flash('error_msg', 'This username already exists');
    res.redirect('/users/register');
  } else {
    User.createUser(newUser, function(err, user){
    if(err) throw err;
    console.log(user);//may be deleted
    });

  req.flash('success_msg', 'You registered successfuly and you can now login');
  res.redirect('/users/login');
  }
})

Two things I see wrong:

  • You're doing synchronous operations after passing off the control to an asynchronous callback

  • You're not doing anything useful with the errors inside your asynchronous callback

Here the asynchronous callback is the function you pass to User.getUserByUsername

router.post('/register', function(req, res) {
  ...
  User.getUserByUsername(username, function(err, user) {
    // Any errors get thrown here need to be dealt with here
    // Also you can't simply "throw" or "return" errors from this,
    // You need to use Express's "next" method to handle these errors
  })

  // And since you've gone asynchronous above (User.getUserByUsername) 
  // you can't do the following here:
  req.flash('success_msg', 'You are registered and can now login')
  res.redirect('/users/login')
  // otherwise these will ALWAYS get executed, 
  // regardless of what the result of `User.getUserByUsername` may be
})

You need to do something like this:

router.post('/register', function(req, res, next) { // use `next` to handle errors
  ...
  User.getUserByUsername(username, function(err, user) {
    if (err) {
      next(err)
    } else if (user) {
      next(new Error('User already exists!'))
    } else {
      req.flash('success_msg', 'You are registered and can now login')
      res.redirect('/users/login')
    }
  })
})

PS: Also you're not saving newUser (at least not in the code you've posted)

var candidateName = username;
var queryforUsername = {};
queryforUsername['username'] = candidateName;
User.find(queryforUsername, function(err, item){
    if(err) throw (err);
    if(item.length > 0){
        req.flash('error_msg', 'User with username '+username+' already exists!');
        res.redirect('register');
    }else if(item.length == 0){
        User.createUser(newUser, function(err, user){
            if(err) throw err;
            console.log(user);
            req.flash('success_msg', 'You are registered and can now login');
            res.redirect('/users/login');
        });
    }
});

If you only want to check if user with given username exist or not, then I have used this simple trick.

What I am doing is while registering, if some error occurs then I am checking if this error is UserExistError(which is related to mongodb, and you can see it when it occurs in terminal)

If err is equal to UserExistError then I am rendering an alert which is in separate file.

register(new User({username:req.body.username}),req.body.password,function(err,user){
    if(err)
    {   var chk=1;
        console.log(err);
        if(err=='UserExistsError');
        console.log("error is here");
        return res.render("register",{chk:chk});

    }

    passport.authenticate("local")(req,res,function(){
        res.redirect("/dashboard");
    })    

});
const { usuario } = req.body;

let user = await User.findOne({ usuario});

if (user) {
    return res.status(400).json({ ok: false, msg: 'El usuario ya existe' });
}

//crear nuevo user
user = new User(req.body);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM