Search code examples
node.jsmongodbappfog

node.js application - integrate mongodb in appfog


I am starting to use appfog services in order to host node application. I am getting trouble trying to use mongodb in my application. In you tutorial here: https://docs.appfog.com/services/mongodb#walkthrough it is written to connect mongodb like this:

require('mongodb').connect(mongourl, ...

while mogourl is the url generated by the generate_mongo_url function. The problem is that I am using newer api (I think) and I cannot pass url to the open method. This is how I am using mongodb:

var mongoClient = new MongoClient(new Server('localhost', 27017));
mongoClient.open(function(err, mongoClient) { ...

Where and how can I use the generated mongourl? How can I pass the credentials and the mongo variable used in generate_mongo_url function?

UPDATE
According to @mjhm suggestion, this is my open function:

var mongoService = null;
if(process.env.VCAP_SERVICES){
    var env = JSON.parse(process.env.VCAP_SERVICES);
    mongoService = env["mongodb-1.8"][0]["credentials"];
} else {
    mongoService = {
        "hostname": "localhost",
        "port": 27017,
        "isLocal": true,
        "username": "",
        "password": "",
        "name": ""
    };
}

this.mongoClient.open(function(err, mongoClient) {
    if (!err) {
        console.log("Open DB Success");
        var db = mongoClient.db(DB_NAME);

        if (!mongoService.isLocal) {
            db.authenticate(mongoService.username,
                mongoService.password, function (err, result) {
                    if (!err) {
                        console.log("Authenticate DB Success");
                        doAction();
                    } else {
                        console.log("Authenticate DB Error: " + err);
                    }
            });
        } else {
            doAction();
        }
    } else {
        console.log("Open DB Error: " + err);
    }
});

When I am running this code on appfog, I am waiting a lot of time (more then 20 seconds) and then I get:

$ curl myappname.eu01.aws.af.cm/list
curl: (52) Empty reply from server

Any idea what is wrong?


Solution

  • What you are looking for is the MongoClient.connect function

    http://mongodb.github.com/node-mongodb-native/driver-articles/mongoclient.html#mongoclient-connect

    It takes the url you are talking about.