Marcel
Marcel

Reputation: 1555

Can not connect to mongoDB with MongoClient

I have some trouble connecting to a remote mongoDB instance.

var http = require('http'),
express = require('express'),
path = require('path'),
MongoClient = require('mongodb').MongoClient,
Server = require('mongodb').Server,
CollectionDriver = require('./collectionDriver').CollectionDriver,
FileDriver = require('./fileDriver').FileDriver; //<---

var app = express();
app.set('port', process.env.PORT || 7777);
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(express.bodyParser()); // <-- add

var mongoHost = 'mongodb://username:[email protected]';
var mongoPort = 33170;
var fileDriver;  //<--
var collectionDriver;

var mongoClient = new MongoClient(new Server(mongoHost, mongoPort));

mongoClient.open(function(err, mongoClient) {
  if (!mongoClient) {
      console.error("Error! Exiting... Must start MongoDB first");
      process.exit(1);
  }
  var db = mongoClient.db("myDatabaseName");

  fileDriver = new FileDriver(db); //<--
  collectionDriver = new CollectionDriver(db);
});

If I start node on my local machine and enter localhost:7777, I always get the following error from above in the console:

Error! Exiting... Must start MongoDB first

What might be the reason for that?

Upvotes: 0

Views: 12707

Answers (1)

JohnnyHK
JohnnyHK

Reputation: 311865

The docs on MongoClient are confusing. It's typically best to use MongoClient.connect instead of creating your own MongoClient object and calling open on it as you can include the database name into the connect call's url parameter.

So something like:

MongoClient.connect(
    'mongodb://username:[email protected]:33170/myDatabaseName',
    function(err, db) { ... });

Upvotes: 2

Related Questions