Search code examples
node.jsmongodblocalhost

Node MongoDb { err: 'connection to [127.0.0.1:27017] timed out' }


I can connect to my mongo database from the command line by doing this:

$ mongo 127.0.0.1:27017/my_database

But when I try and connect with my node.js code I am getting back the error:

{ err: 'connection to [127.0.0.1:27017] timed out' }

Here is my code:

var mongo = require('mongodb');
var MongoClient = mongo.MongoClient;

var DB_NAME = 'my_database';
var connectionString = 'mongodb://127.0.0.1:27017/' + DB_NAME;


MongoClient.connect( connectionString, function(err, conn)
{
    console.log(err, conn);
});

I'm not finding anything to explain this error, and I don't understand why my code should be failing when I can connect from the command line.


Solution

  • The issue here was the version of mongodb.
    Version 1.3.23 has this error.
    I upgraded mongo in my repo, thus :

    $ npm uninstall mongodb --save
    $ npm install mongodb --save
    

    And that gave me version 2.2.11, and this has fixed the problem.