title: Node.js - Check if user exists
body: <p>I'm using NodeJS and passport to let users create an account before they can see results of a quiz they've just taken. My challenge is I need to confirm the username is available before the page refreshes because the user will lose their results if this happens. </p>
  
  <p>Again: I need to verify the username is not taken prior to refreshing.  </p>
  
  <p>I think I'm close but it is not working. How would I change my code to handle this challenge? </p>
  
  <p>Currently if the user name is taken it returns an error on trying to create an account and the user ends up on the /failpage as shown below. </p>
  
  <pre><code>app.post('/quiz', usernameToLowerCase, emailToLowerCase, function(req, res) {
  
  
      User.findOne({
          username: req.body.username
      }, function(err, user) {
          if (err) {
              alert(err)
              if (user) {
                  alert('this username is already taken. Please choose another.')
                  console.log('there was a user');
                  return false;
  
              }
          }
      });
  
      var user = new User({
          username: req.body.username,
          email: req.body.email,
          password: req.body.password,
      })
  
  
  
      user.save(function(err) {
          console.log('this is the problem' + ' ' + err)
          if (err) {
              return res.redirect('/failpage')
          }
  
  
          req.logIn(user, function(err) {
              if (err) {
                  console.log(err);
              }
              console.log('all looks good')
              res.redirect('/results');
          });
      });
  });
  </code></pre>