Jiri Krewinkel
Jiri Krewinkel

Reputation: 135

Error: Connection Closed - MongoDB Node

Okay so I'm a total Node/MongoDB newbie and I'm currently following this tutorial: http://mongodb.github.io/node-mongodb-native/api-articles/nodekoarticle1.html .

This is the code I have thusfar

    var MongoClient = require('mongoDB').MongoClient;

    MongoClient.connect("mongodb://localhost:8888/exampleDb", function(err, db){
        if( !err ){
             console.log("We are connected");
        } else console.log(err);
    });

However when I run node /node/index.js my console logs:

    [Error: connection closed]

I've tried disabling my firewall and adding auto-reconnect: true, both which didn't work. I can't seem to find the problem online, what could be wrong?

EDIT: this is how I set up the server

    var server = require("./server");
    var router = require("./router");

    // in router.js
    function route(handle, pathname, response){
        console.log("About to route a request for "+pathname);
        if( typeof handle[pathname] === "function"){
            handle[pathname](response);
        } else {
            console.log("404");
            response.writeHead(404, {"Content-Type":"text/plain"});
            response.write("404 not found");
            response.end();
        }
    }

    exports.route = route;

    // in server.js
    var http = require("http");
    var url = require("url");

    function start(route, handle){
        function onRequest(request, response){
            var pathname = url.parse(request.url).pathname;
            route(handle, pathname, response);
        }

        http.createServer(onRequest).listen(8888);
    }
    exports.start = start;

    server.start(router.route, handle);

Upvotes: 3

Views: 20841

Answers (2)

Jiri Krewinkel
Jiri Krewinkel

Reputation: 135

Woops false alarm, I hadn't launched mongod.exe yet. So for anyone that encounters this error and searches the web: make sure you've installed mongodb and run the mongod.exe executable inside the installation/bin directory

Upvotes: 1

throrin19
throrin19

Reputation: 18207

Ok, your error is simple. By default, mongoDB run at port 27017 and in your code, you try to connect on mongod instance on 8888 port. This port is used for your node project, not for MongoDB.

To first, you should launch mongod instance. If you're in Ubuntu, you can start with this :

sudo service mongodb start

If you are in another platform, and the mongodb path is in your PATH env, you can launch this simply whith this command :

mongod

Change the connection uri by :

var MongoClient = require('mongoDB').MongoClient;

MongoClient.connect("mongodb://localhost:27017/exampleDb", function(err, db){
    if( !err ){
         console.log("We are connected");
    } else console.log(err);
});

Upvotes: 1

Related Questions