title: Mongodb Error: failed to connect to [localhost:27017]
body: <p>I have the following code:</p>
  
  <pre><code>var express = require('express'),
      mongoose = require('mongoose');
  
  
  var db = mongoose.connect('mongodb://localhost/bookAPI');
  
  var Book = require('./models/bookModel');
  
  var app = express();
  
  var port = process.env.PORT || 3002;
  
  
  var bookRouter = express.Router();
  
  bookRouter.route('/Books')
      .get(function(req,res){
  
          Book.find(function(err,books){
              if(err)
                  console.log(err);
              else
                  res.json(books);
          });
      });
  
  
  app.use('/api', bookRouter);
  
  
  
  app.get('/', function(req, res){
      res.send('welcome to my API!');
  });
  
  app.listen(port, function(){
      console.log('Gulp is running my app on  PORT: ' + port);
  });
  </code></pre>
  
  <p>Bookmodel.js file:</p>
  
  <pre><code>var mongoose = require('mongoose'),
      Schema = mongoose.Schema;
  
  var bookModel = new Schema({
      title: {
          type: String
      },
      author: {type: String},
      genre: {type: String},
      read: {type: Boolean, default:false}
  });
  
  module.exports= mongoose.model('Book', bookModel);
  </code></pre>
  
  <p>My gulpfile is:</p>
  
  <pre><code>var gulp = require('gulp'),
      nodemon = require('gulp-nodemon');
  
  
  gulp.task('default', function(){
      nodemon({
          script: 'app.js',
          ext: 'js',
          env: {
              PORT:8000
          },
          ignore: ['./node_modules/**']
      })
      .on('restart', function(){
          console.log('Restarting');
      });
  });
  </code></pre>
  
  <p>However I keep getting the error:</p>
  
  <pre><code>Gulp is running my app on  PORT: 8000
  events.js:85
        throw er; // Unhandled 'error' event
              ^
  Error: failed to connect to [localhost:27017]
    at null.&lt;anonymous&gt; (/Users/admin/Documents/NodeAndExpress/node_modules/mongoose/node_modules/mongodb/lib/mongodb/connection/server.js:549:74)
  </code></pre>
  
  <p>This is quite frustrating because I am following a Pluralsight course very closely. I've installed all the neccessary npm packages etc. It is definitely the mongoose connection that is causing the error as it goes away when I remove the connection line. The database has not been created but the instructor mentioned it should be automatically created if it doesn't already exist.</p>
  
  <p>I've tried starting the mongoose connection manually with <code>mongod</code> but I get the error:</p>
  
  <pre><code> ERROR: dbpath (/data/db) does not exist.
   Create this directory or give existing directory in --dbpath.
  </code></pre>