title: Error handling for data returned from Mongo Query
body: <p>Still a relative newbie, but  I'm using a portal to allow people to check if a person is a member of a club. I'm using mongodb and mongoose to do this, however when a number is entered that isn't in the database an error is returned "TypeError: Cannot read property 'username' of undefined" fair enough,but i'm not sure how to handle this error, please see my code below: I know there are a few ways I can refactor and tidy up my code, but it's the mongoose error handling i would like to know about. Cheers  </p>
  
  <pre><code>app.get('/checkmembership', function(req, res) {
  
      var jsonResponse = {};
      var returnArray =[];
  
      var dbArray,
          queryArray,
          resulta,
          resultb,
          resultc,
          resultd,
          resulte,
          resultf;
  
      console.log("before running compareDetails " + returnArray);
  
      User.find({username: req.query.memberIdQuery}, function(err, foundData) {
  
          if(err){
              console.log(err);
          } else {
              dbArray = [foundData[0].username, foundData[0].emailaddress, foundData[0].surname];
              console.log(dbArray);
              dbArray = dbArray.join('|').toLowerCase().split('|');
              console.log(dbArray);
              queryArray = [req.query.memberIdQuery, req.query.emailQuery, req.query.surnameQuery];
              console.log(queryArray);
              queryArray = queryArray.join('|').toLowerCase().split('|');
              console.log(queryArray);
              returnArray = compareDetails(queryArray, dbArray);
              resulta = returnArray[0];
              resultb = returnArray[1];
              resultc = returnArray[2];
              resultd = returnArray[3];
              resulte = returnArray[4];
              resultf = returnArray[5];
          }
  
          jsonResponse = { 
              set_attributes: 
              {
                  resulta : resulta,
                  resultb : resultb,
                  resultc : resultc,
                  resultd : resultd,
                  resulte : resulte,
                  resultf : resultf
              },
          };
  
          res.send(jsonResponse);
      });
  });
  </code></pre>