title: Mongoose Update Doesn't Run Before My Res.Send()
body: <p>I currently have a controller which is handling the onboarding of a user. When the user completes their onboarding flow, I update their status in Mongo from <code>New</code> to <code>Active</code>, then send them to a new page. As a method of security, I also have a middleware function on every authenticated route which checks if the user is logged in, as well as their status. If their status is <code>New</code>, I send them to the onboarding flow (because theoretically they haven't seen the onboarding flow).</p>
  <p>As I run through my experience, when I submit the onboarding flow, I get redirected back to the beginning of the flow. I check Mongo and my status is no longer <code>New</code>, so I was confused why this was happening. Eventually I realized when I am sending the user to a new page, the authentication route is checking the user's status before my <code>findOneAndUpdate()</code> has had a chance to complete. So the user gets redirected back to the onboarding flow because the last query didn't finish in time.</p>
  <p>Any idea how to fix this? I assume it has something to do with async/await but I'm not sure. Here's my code below, I'm working in Node.JS with an express framework. Also, in my post onboarding I am using a mapbox api to get the lat/long of their zip code, which is why I have the <code>request.get()</code> in the code.</p>
  <p><strong>Onboarding Controller</strong></p>
  <pre><code>exports.postOnboarding = (req, res, next) =&gt; {              
  
  var data = req.params.data;    
  var final = data.split(',');       
  
  location = final[4].toString();
  url = &quot;https://api.mapbox.com/geocoding/v5/mapbox.places/&quot; + location + &quot;.json&quot;;
      
  request.get(url)
  .query({access_token: &quot;private_key&quot;})
  .end(function(err, result) {                    
  
      User.findOneAndUpdate(
          {&quot;credentials.userId&quot;: req.session.user.credentials.userId },
          { practiceSettings: {
              businessType: final[2],
              experienceType: final[0],
              fullFee: final[3]
          },
          credentials: {
              userType: &quot;Active&quot;,
              active: true,
              userId: req.session.user.credentials.userId,
              provider: &quot;local&quot;
          },
          paySettings: {
              q1: &quot;undeternmined&quot;
          },
          license: final[1],
          zip: final[4],
          latLong: result.body.features[0].center
          }, (err, result) =&gt; {
              if (err) {
                  console.log(err);
              } else {                                                    
                  console.log(&quot;settings updated&quot;);                    
                  res.redirect('/dashboard');
              }                        
          }
      )
  
  }) };
  
      
  </code></pre>
  <p><strong>Dashboard Route</strong></p>
  <pre><code>router.get('/dashboard', isAuth, adminController.getDashboard);
  </code></pre>
  <p><strong>isAuth Middleware</strong></p>
  <pre><code>const User = require('../models/user');
  
  module.exports = (req, res, next) =&gt; {    
  
      if (!req.session.isLoggedIn) {
          return res.redirect('/login');
      } else if (req.session.user.credentials.userType == 'Unverified') {
          return res.redirect('/login?verified=false');
      } else if (req.url == '/onboarding') {
          return next();
      }
  
      User.findOne({&quot;credentials.userId&quot; : req.session.user.credentials.userId})
      .then(result =&gt; {                  
  
          res.locals.user = result;          
          if (req.session.sidebarStatus == 'closed') {
              res.locals.sidebarStatus = 'closed';
          }
                  
          if (result.credentials.userType == 'New') {            
              return res.redirect('/onboarding');
          }
  
          next();
      })        
  }
  </code></pre>
  <p>And for reference, below is a snippet of my <code>onboarding.ejs</code> file which calls the post route. This isn't the whole thing, I have a lot of nested Sweet Alert modals, but this is the important part.</p>
  <pre><code>Swal.fire({
      text: &quot;Question&quot;,
      width: &quot;90%&quot;,
      input: &quot;text&quot;,    
      inputPlaceholder: &quot;92805&quot;,   
      inputValidator: (value) =&gt; {
          if (!value) {
          return 'You must fill in this field.'
          }
  
          if (value.length != 5) {
              return 'Please use a 5 digit zip-code as your answer.'
          }
      },                       
      showCancelButton: false,
      confirmButtonText: 'Submit',
      backdrop: '#FFFFFF',
      allowOutsideClick: false
      })
      .then((result5) =&gt; {
          res3 = result3.value.replace(&quot;,&quot;, &quot;&quot;);
          final = [result1.value, result2.value, res3, result4.value, result5.value];                            
          $.ajax({                            
              url: &quot;/post-onboarding/&quot; + final,
              dataType: 'json',
              type: 'post',
              success: function (data) {
                  if ( data.length ) {
                      Swal.fire({
                          title: 'Error!',
                          text: 'Something bad happened',
                          icon: 'error',
                          confirmButtonText: 'OK'
                      });     
                  } else {
                      //redirect user                                
                  }
              }                                           
  });
  </code></pre>