Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I use node-mongodb-native to connect to Heroku?

I'm getting really confused over how to connect to MongoLab on Heroku. To connect using the uri to Heroku, I was trying to follow this example: http://experiencecraftsmanship.wordpress.com/2012/01/06/heroku-node-js-mongodb-featuring-the-native-driver/

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

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

But then only the database query in 'contacts' get passed into this server then? Am I allowed to do multiple connect.createServer for each of my database access method?

The following is part of my code when just connecting to MongoDB locally. I am unsure of how to modify it to connect to MongoLab on Heroku.

Can someone teach me how to modify my code to connect? Or explain some of these concepts? I have no idea why the author of that website I posted used so many callbacks to do a database call, when my approach below seems straightforward enough (I'm new to JavaScript, 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' });
});
like image 377
gruuuvy Avatar asked Oct 07 '22 23:10

gruuuvy


1 Answers

You connect to your mongolab database (so you can't create a new "blog" database). process.env.MONGOLAB_URI includes the database name as well. See your mongolab uri:

heroku config | grep MONGOLAB_URI

It looks like: mongodb://heroku_app123456:[email protected]:27737/heroku_app123456

On github there is an example how to connect and retrieve data from a mongolab database.

like image 83
Anatoly Mironov Avatar answered Oct 12 '22 21:10

Anatoly Mironov