0

I'm new to nodeJS, so i was just trying couple of things starting from basics.

I had a problem while retrieving data from MongoDB, So here is the code:

var port = (process.env.VMC_APP_PORT || 3000);
var host = (process.env.VCAP_APP_HOST || 'localhost');
var http = require('http');
var mongo = require('mongodb');
http.createServer(function (req, res) {
    var mongoUrl = "mongodb://<userid>:<password>@linus.mongohq.com:10090/<db>";
    if (process.env.VCAP_SERVICES) {
        mongoUrl = process.env.MONGOHQ_URL;
    }
    selectTable(req, res, mongoUrl);
}).listen(port, host);

var selectTable = function (req, res, mongoUrl) {
    res.writeHead(200, { 'Content-Type': 'text/plain' });
    res.write("Start\n");
    mongo.connect(mongoUrl, function (err, conn) {
        conn.collection('Test', function (err, coll) {
            coll.find({}, {}, function (err, cursor) {
                cursor.toArray(function (err, items) {
                    for (i = 0; i < items.length; i++) {
                        res.write(JSON.stringify(items[i]) + "\n");
                    }
                    res.end();
                });
            });
        });
    });
}

this works fine in my local, it displays the rows, but when i upload it to one of my appfog's app it does not display the rows, it just stops at "Start" and nothing else is displayed.

Please help, Thanks a lot in advance.

peek4y
  • 31
  • 3

1 Answers1

0

You can check with the Document or the example on github. They provide with VCAP_SERVICES for every details you need to connect. so following (from the doc) will do all the magic.

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":27017,
"username":"",
"password":"",
"name":"",
"db":"db"
}
}
var generate_mongo_url = function(obj){
obj.hostname = (obj.hostname || 'localhost');
obj.port = (obj.port || 27017);
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);
ryh
  • 1
  • 1
  • 1
    It does work when you give the mongo url of the service provided by appfog, but it doesn't work when you try to give any 3rd party url, like mongohq or mongolab – peek4y Feb 25 '13 at 11:11