How to use node-Mongodb-native to connect to Heroku?

I am very confused about how to connect to MongoLab on Heroku. To connect via uri to Heroku, I tried to follow this example: http://experiencecraftsmanship.wordpress.com/2012/01/06/heroku-node-js-mongodb-feature-the-native-driver/

I looked at his web.js and deep.js. They both do something like:

connect.createServer(
    require( 'connect-jsonrpc' )( contacts )
).listen( port );

But then only the database request in "contacts" will be transferred to this server? Can I make several connect.createServer for each of the database access methods?

When connected to MongoDB locally, this is part of my code. I am not sure how to change it to connect to MongoLab on Heroku.

Can someone teach me how to modify my connection code? Or explain some of these concepts? I have no idea why the author of this website I posted used so many callbacks to call the database when my approach below seems simple enough (I'm new to JavaScript, but not good with callbacks).

var app = module.exports = express.createServer(
  form({ keepExtensions: true })
);

var Db = require('mongodb').Db;
var Server = require('mongodb').Server;
var client = new Db('blog', new Server('127.0.0.1', 27017, {}));

var posts;
var getAllPosts = function(err, collection) {
  collection.find().toArray(function(err, results) {
    posts = results;
    console.log(results);
    client.close();
  });
}


app.get('/', function(req, response) {
  client.open(function(err, pClient) {
    client.collection('posts', getAllPosts);
  });

  // some code
  response.render('layout', { posts: posts, title: 'Raymond', contentPage: 'blog' });
});
+5
source share
2 answers

You are connecting to your mongolab database (therefore you cannot create a new blog database). process.env.MONGOLAB_URI also contains the database name. See your mongolab uri:

heroku config | grep MONGOLAB_URI

Seem to be: mongodb://heroku_app123456:password@dbh73.mongolab.com:27737/heroku_app123456

Github has an example of connecting and retrieving data from the mongolab database .

+2
source

Use "connect" to connect to mongo, instead of defining db, server, client:

var connect = require('connect');
var mongo = require('mongodb');
var database = null;

var mongostr = [YOUR MONGOLAB_URI];

mongo.connect(mongostr, {}, function(error, db)
    {       
            console.log("connected, db: " + db);

            database = db;

            database.addListener("error", function(error){
            console.log("Error connecting to MongoLab");

            });
});
+2
source

All Articles