title: MongoDB Find Next Document or Go To First
body: <p>I have an Express app with Node / MongoDB / Mongoose ODM. The app displays data about projects stored in the DB, and each project page should have a link to the previous and next project (the link is also stored in the DB). If the app is at the last project in the DB, how can I query the database for the first project, instead of looking for the (non-existent) next one?</p>
  
  <pre><code>app.get('/projects/:_id', function(req, res){
  var nextProject = Project.find({_id: {$gt: req.params._id}}).sort({_id: 1 }).limit(1)
  var prevProject = Project.find({_id: {$lt: req.params._id}}).sort({_id: -1 }).limit(1)
  Project.findById(req.params._id, function(err, foundProject){
    if(err){
      console.log('Error finding project');
      console.log(err);
    } else {
        nextProject.exec(function(err, next){
          if(err){
            console.log('err');
            console.log(err);
          } else {
            prevProject.exec(function(err, prev){
              if(err){
                console.log('err');
                console.log(err);
              } else {
                console.log(prev[0].title);
                console.log('==============================================');
                console.log(foundProject);
                console.log('==============================================');
                console.log(next[0].title);
                res.render('project', {project: foundProject, nextProject: next[0], prevProject: prev[0]});
              }
            });
          }
        });
      }
    });
  });
  </code></pre>
  
  <p>Thank you!</p>
  
  <p><strong>EDIT</strong> (New code trying to retrieve first document if 'next' comes back empty...</p>
  
  <pre><code>app.get('/projects/:_id', function(req, res){
  Project.find({_id: {$gt: req.params._id}}).sort({_id: 1 }).limit(1), function(err, next){
    if(err){
      console.log('err getting next project');
      console.log(err);
    } else if(next){
      var nextProject = next
      console.log('this is the next project');
      console.log(nextProject);
    } else {
      var nextProject = Project.find().sort({_id: 1 }).limit(1);
      console.log('this is the first project');
      console.log(nextProject);
    }
  }
  Project.find({_id: {$lt: req.params._id}}).sort({_id: -1 }).limit(1), function(err, prev){
    if(err){
      console.log('error getting previous project');
      console.log(err);
    } else if(prev){
      var prevProject = prev
      console.log('this is the previous project');
      console.log('prevProject');
    } else {
      var prevProject = Project.find().sort({_id: -1}).limit(1);
      console.log('this is the last project');
      console.log(prevProject);
    }
  }
  Project.findById(req.params._id, function(err, foundProject){
    if(err){
      console.log('Error finding project');
      console.log(err);
    } else {
        nextProject.exec(function(err, next){
          if(err){
            console.log('err');
            console.log(err);
          } else {
            prevProject.exec(function(err, prev){
              if(err){
                console.log('err');
                console.log(err);
              } else {
                console.log(prev[0].title);
                console.log('==============================================');
                console.log(foundProject);
                console.log('==============================================');
                console.log(next[0].title);
                res.render('project', {project: foundProject, nextProject: next[0], prevProject: prev[0]});
              }
            });
          }
        });
      }
  });
  </code></pre>
  
  <p><strong>2nd Edit</strong> with more code that isn't working:</p>
  
  <pre><code>app.get('/projects/:_id', function(req, res){
    var nextProject = Project.find({_id: {$gt: req.params._id}}).sort({_id: 1 }).limit(1)
    var prevProject = Project.find({_id: {$lt: req.params._id}}).sort({_id: -1 }).limit(1)
    // find the project for the clicked link
    Project.findById(req.params._id, function(err, foundProject){
      if(err){ // handle any errors
        console.log('Error finding project');
        console.log(err);
      } else {
        nextProject.exec(function(err, next){ // if no errors, execute the query object for the next project
      if(err){ // handle any errors
        console.log('Error getting next project');
        console.log(err);
      } else if(next){ // if next has a value...
        prevProject.exec(function(err, prev){ // ... execute the query object for the previous project
          if(err){  // handle any errors
            console.log('error getting previous project');
            console.log(err);
          } else if(prev){ // if previous has a value...
            console.log('prev and next have a value');
            console.log('============================foundProject============================');
            console.log(foundProject);
            console.log('============================prevProject============================');
            console.log(prev);
            console.log('============================nextProject============================');
            console.log(next);
            res.render('project', {project: foundProject, nextProject: next[0], prevProject: prev[0]});//... render the project page with current project, next project and previous project
          } else if(prev){ // if previous doesn't have a value...
            var prevProject = Project.find().sort({_id: -1}).limit(1);//... get a query object for the last document in the database
            prevProject.exec(function(err, prev){ // execute the query object for the last document
              if(err){ // handle any errors
                console.log('error getting last document');
                console.log(err);
              } else { // with no errors...
                console.log('next has a value, but previous does not. Gone to last project');
                res.render('project', {project: foundProject, nextProject: next[0], prevProject: prev[0]}); // ... render the page
              }
            })
          }
        })
      } else if(next){ //if next doesn't have a value...
        var nextProject = Project.find().sort({_id: 1 }).limit(1);//get a query object for the first document
        nextProject.exec(function(err, next){ // execute the query object
          if(err){
            console.log('error getting first project');
            console.log(err);
          } else { // with no errors...
            console.log('previous has a value, but next does not. Gone to first project');
            res.render('project', {project: foundProject, nextProject: next[0], prevProject: prev[0]});//render the page
          }
        });
      }
    });
  }
  </code></pre>
  
  <p>});
  });</p>