Node js connecting to mongo db

512 Views Asked by At

db beginner trying to get mongodb and nodejs to talk to each other on the cloud.

I am hosting an app on app-fog, but even when I try to do the most rudimentary of queries, I fail. This is the content of app.js file pushed to the cloud. I believe I have installed all the necessary dependencies (npm install mongodb && express && bson && shrinkwarp) but it is possible that I have failed somewhere along the way, even though I went through the whole process twice.

var port = (process.env.VMC_APP_PORT || 3000);
var host = (process.env.VCAP_APP_HOST || 'localhost');
var http = require('http');


if(process.env.VCAP_SERVICES){
        var env = JSON.parse(process.env.VCAP_SERVICES);
        var mongo = env['mongodb-1.8'][0]['credentials'];
    }   else   {
    var mongo = {
        "hostname":"localhost",
        "port":3000,
        "username":"",
        "password":"",
        "name":"",
        "db":"db"
    }
}
var generate_mongo_url = function(obj){
    obj.hostname = (obj.hostname || 'localhost');
    obj.port = (obj.port || 3000);
    obj.db = (obj.db || 'test');
    if(obj.username && obj.password){
        return "mongodb://" + obj.username + ":" + obj.password + "@" + obj.hostname + ":" + obj.port + "/" + obj.db;
    }else{
        return "mongodb://" + obj.hostname + ":" + obj.port + "/" + obj.db;
        }
    }
var mongourl = generate_mongo_url(mongo);



var record_visit = function(req, res){
/* Connect to the DB and auth */
    require('mongodb').connect(mongourl, function(err, conn){
        if(err){
            console.log(">>",err);
        }
        conn.collection('ips', function(err, coll){
            /* Simple object to insert: ip address and date */
            object_to_insert = { 'ip': req.connection.remoteAddress, 'ts': new Date() };
            /* Insert the object then print in response */
            /* Note the _id has been created */
            coll.insert( object_to_insert, {safe:true}, function(err){
            res.writeHead(200, {'Content-Type': 'text/plain'});
            res.write(JSON.stringify(object_to_insert));
            res.end('\n');
            });
        });
    });
}

http.createServer(function(res,req){
    record_visit(req,res);
    require('mongodb').connect(mongourl,function(err,conn){
        console.log(conn+"\n\n");   
    });
    console.log('Hello from us.\n');

}).listen(process.env.VCAP_APP_PORT || 3000);

Now I always seem to get this error:

node_modules/mongodb/lib/mongodb/mongo_client.js:378
          throw err
                ^
TypeError: Cannot call method 'collection' of null

The problem seems to be not just with collection, but mainly with its parent, conn, which I tried to print out but was unsuccessful. (I am suspicious it is itself undefined.)

I know that this is probably a simple, RTFM-type error, but all of these concepts are sort of over my head at this point.

Thank you!

1

There are 1 best solutions below

1
heinob On

You will find your error easily if you log err of connect:

require('mongodb').connect(mongourl, function(err, conn){
    if( err ) {
        console.log( err ); // <-- here
        ...
    }
    conn.collection('ips', function(err, coll){

BTW: You anyway should check on err always before proceeding to use the second parameter of a callback.