Friday 24 August 2012

Use Heroku, MongoLab and Node.js and mongo node-mongodb-native

So I am trying out MongoLab for their database, and it uses a connection string, where in the node native drivers examples they instantiate a new Server() instance. I got it to work with the connection string, so I thought I would share:

My previous code:

SiteService.prototype.save = function (site, callback) {
    var db = new Db(mongods.datasource.db, new Server(mongods.datasource.hostname, mongods.datasource.port, {auto_reconnect:true}, {}));
    db.open(function () {
        self.getCollection(db, function (error, collection) {
            if (error) {
                callback(error);
            } else {
                site.created_at = new Date();
                collection.insert(site, function () {
                    callback(null, site);
                    db.close();
                });
            }
        });
    });
};


The code that uses the connection string:

SiteService.prototype.save = function (site, callback) {  
   mongodb.connect(mongods.datasource, {auto_reconnect: true}, function(error, db)  
   {  
     console.log("connected, db: " + db);  
     self.getCollection(db, function (error, collection) {  
       if (error) {  
         callback(error);  
       } else {  
         site.created_at = new Date();  
         collection.insert(site, function () {  
           callback(null, site);  
           db.close();  
         });  
       }  
     });  
   });  
 };  


Notice also that I changed how the `mongods` variable is defined. Instead of return a json with the individual properties, the connection string is now embedded into the datasource property.

No comments:

Post a Comment