How to get mongodb working on appfog?

回眸只為那壹抹淺笑 提交于 2019-12-13 07:05:50

问题


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.


回答1:


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);


来源:https://stackoverflow.com/questions/14995336/how-to-get-mongodb-working-on-appfog

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!