title: Mongoose queries with async await
body: <p>I have an application where logged in users can create new users and add them to one of their groups.  You can see the middleware flow for this in the route:</p>
  
  <pre><code>router.post('/account/add-users',
    userController.validateRegister,
    userController.registerUser,
    userController.getNewUser,
    groupController.addUserToGroup
  );
  </code></pre>
  
  <p>I am using Passport for registration / authentication.</p>
  
  <p>Essentially once I have registered the new user I would like to be able to add them to the group the the creator has specified.</p>
  
  <p>My validateRegister method looks like:</p>
  
  <pre><code>exports.validateRegister = (req, res, next) =&gt; {
   req.sanitizeBody('name');
   req.checkBody('name', 'You must supply a name!').notEmpty();
   if(req.body.email){
    req.checkBody('email', 'That Email is not valid!').isEmail();
    req.sanitizeBody('email').normalizeEmail({
     gmail_remove_dots: false,
     remove_extension: false,
     gmail_remove_subaddress: false
    });
    req.checkBody('password', 'Password Cannot be Blank!').notEmpty();
    req.checkBody('password-confirm', 'Confirmed Password cannot be blank!').notEmpty();
    req.checkBody('password-confirm', 'Oops! Your passwords do not match').equals(req.body.password);  
    };
    const errors = req.validationErrors();
   if (errors) {
      req.flash('error', errors.map(err =&gt; err.msg));
      res.render('login', { title: 'Register', body: req.body, flashes: 
      req.flash() });
      return; // stop the fn from running
    }
    next(); // there were no errors!
  };
  </code></pre>
  
  <p>registerUser is:</p>
  
  <pre><code>exports.registerUser = async (req, res, next) =&gt; {
    console.log('registering user');
    if(req.body.email){
      await User.register(new User({email: req.body.email, name: 
      req.body.name, userType: req.body.userType}), 
      req.body.password, 
      function(err) {
        if (err) {
          console.log('error while user register!', err);
          return next(err);
        }
        console.log('user registered!');                      
        res.redirect('/');
       }
     );
  } else {
    console.log('NO EMAIL PROVIDED');
    await User.register(new User({name: req.body.name, userType: 
    req.body.userType}), 
    req.body.password, 
    function(err) {
        if (err) {
          console.log('error while user register!', err);
  
          return next(err);
        }        
      });
   };
   console.log(' user registered!');
  
  // the below are values from the form that I will need to add users to a group
   res.locals.chosenGroup = req.body.group; 
   res.locals.newUserUserName = req.body.name;
   res.locals.newUserUserType = req.body.userType;
   next();
   };
  </code></pre>
  
  <p>getNewUser is below and this is where things break down. The console.log will correctly print the value of <code>res.locals.newUserUserName</code> but when I try to use that value in the <code>User.find</code> nothing comes back</p>
  
  <pre><code>exports.getNewUser = async (req, res, next) =&gt; {
    console.log('IN GETNEWUSER '+res.locals.newUserUserName);
    res.locals.newUser = await User.find( { "name" : 
    res.locals.newUserUserName } );
    if (!res.locals.newUser) {
      console.log('User is not available yet!');
    } else {
      console.log('USER IN REGSITER USER FUNCTION IN GETNEWUSER METHOD 
      '+res.locals.newUser);
    }
   next();
  };
  </code></pre>
  
  <p>I assume this is because the user is not yet in the DB (if i hard code the name of the user into the query and go through the process again the correct record is returned which suggests it's a timing issue) so I guess I'm doing something wrong with my async / awaits.  However the <code>console.log(' user registered!')</code> in <code>registerUser</code> shows in terminal before any of the logs in <code>getNewUser</code> so I'm a bit stumped!</p>
  
  <p>----Edit----</p>
  
  <p>OK, so if in registerUser I use Promisify to rewrite</p>
  
  <pre><code>User.register(new User({name: req.body.name, userType: 
  req.body.userType}), 
  req.body.password, 
  
  function(err) {
    if (err) {
      console.log('error while user register!', err);
  
      return next(err);
    }        
  });
  </code></pre>
  
  <p>to</p>
  
  <pre><code>const user = new User({ name: req.body.name, userType: req.body.userType });
  const register = promisify(User.register, User);
  await register(user, req.body.password);
  </code></pre>
  
  <p>then everything works.  I'd really like to understand why though.</p>