1

I'm trying to do the same thing this guy's doing here How do I setup MongoDB database on Heroku with MongoLab?

The app works on Amazon EC2 and I'm deploying to Heroku with the MongoLabs add-on.

What exactly should I type to change the mongo connection to the Mongo URI?

Heroku Documentation

/** https://devcenter.heroku.com/articles/getting-started-with-nodejs#write-your-app */

var mongo = require('mongodb');

var mongoUri = process.env.MONGOLAB_URI ||
  process.env.MONGOHQ_URL ||
  'mongodb://localhost/mydb';

mongo.Db.connect(mongoUri, function (err, db) {
  db.collection('mydocs', function(er, collection) {
    collection.insert({'mykey': 'myvalue'}, {safe: true}, function(er,rs) {
    });
  });
});

app.js

/** app.js */

var express = require('express')
  , routes = require('./routes')
  , user = require('./routes/user')
  , http = require('http')
  , path = require('path')
  , EmployeeProvider = require('./employeeprovider').EmployeeProvider;

var app = express();

app.configure(function(){
  app.set('port', process.env.PORT || 8080);
  app.set('views', __dirname + '/views');
  app.set('view engine', 'jade');
  app.set('view options', {layout: false});
  app.use(express.favicon());
  app.use(express.logger('dev'));
  app.use(express.bodyParser());
  app.use(express.methodOverride());
  app.use(app.router);
  app.use(require('stylus').middleware(__dirname + '/public'));
  app.use(express.static(path.join(__dirname, 'public')));
});

app.configure('development', function(){
  app.use(express.errorHandler());
});

var employeeProvider= new EmployeeProvider('localhost', 27017);

//Routes

app.get('/', function(req, res){
  employeeProvider.findAll(function(error, emps){
       res.render('index', {
            title: 'Employees',
            employees:emps
        });
   });
});

app.get('/employee/new', function(req, res) {
    res.render('employee_new', {
        title: 'New Employee'
    });
});

//save new employee
app.post('/employee/new', function(req, res){
    employeeProvider.save({
    title: req.param('title'),
        name: req.param('name')
    }, function( error, docs) {
        res.redirect('/')
    });
});

app.listen(8080);

employeeprovider.js

var Db = require('mongodb').Db;
var Connection = require('mongodb').Connection;
var Server = require('mongodb').Server;
var BSON = require('mongodb').BSON;
var ObjectID = require('mongodb').ObjectID;

EmployeeProvider = function(host, port) {
  this.db= new Db('node-mongo-employee', new Server(host, port, {safe: true},          {auto_reconnect: true}, {}));
  this.db.open(function(){});
};


EmployeeProvider.prototype.getCollection= function(callback) {
  this.db.collection('employees', function(error, employee_collection) {
    if( error ) callback(error);
    else callback(null, employee_collection);
  });
};

//find all employees
EmployeeProvider.prototype.findAll = function(callback) {
    this.getCollection(function(error, employee_collection) {
      if( error ) callback(error)
      else {
        employee_collection.find().toArray(function(error, results) {
          if( error ) callback(error)
          else callback(null, results)
        });
       }
    });
};

//save new employee
EmployeeProvider.prototype.save = function(employees, callback) {
    this.getCollection(function(error, employee_collection) {
      if( error ) callback(error)
      else {
        if( typeof(employees.length)=="undefined")
          employees = [employees];

        for( var i =0;i< employees.length;i++ ) {
          employee = employees[i];
          employee.created_at = new Date();
        }

        employee_collection.insert(employees, function() {
          callback(null, employees);
        });
      }
    });
};

exports.EmployeeProvider = EmployeeProvider;

How would I change the employeeProvider to use the URI instead of the localhost?

Community
  • 1
  • 1
Tyler Langan
  • 249
  • 4
  • 15
  • There is an example at : https://github.com/mongolab/mongodb-driver-examples/blob/master/nodejs/nodeSimpleExample.js – nha Oct 13 '14 at 22:22

3 Answers3

10
var mongoUri = process.env.MONGOLAB_URI ||
  process.env.MONGOHQ_URL ||
  'mongodb://localhost/mydb';

This line should already be correct without having to change anything. The code short-circuits as soon as one of the values exists, so 'mongodb://localhost/mydb' is only used if neither MONGOLAB_URI or MONGOHQ_URL exist in the environment variables.

That said, chances are a given Heroku app isn't making use of both MongoDB providers, so it makes sense to only include the variable name you intend to use. My apps, for example, have:

var mongoUri = process.env.MONGOLAB_URI || 'mongodb://localhost/test'
Eric
  • 450
  • 2
  • 6
  • Thanks Eric! Should it be var employeeProvider= process.env.MONGOLAB_URI || 'mongodb://localhost/test'; – Tyler Langan Oct 15 '13 at 05:08
  • I'm commenting out var employeeProvider= new EmployeeProvider('localhost', 27017); and putting var mongoUri = process.env.MONGOLAB_URI || 'mongodb://localhost/test' in my app.js and it's giving me an application error. – Tyler Langan Oct 15 '13 at 05:12
  • I'm adding var mongoUri = process.env.MONGOLAB_URI || process.env.MONGOHQ_URL || 'mongodb://localhost/mydb'; mongo.Db.connect(mongoUri, function (err, db) { db.collection('mydocs', function(er, collection) { collection.insert({'mykey': 'myvalue'}, {safe: true}, function(er,rs) { }); }); }); to employeeprovider.js because that's where my require(mongo) is. I tried adding that to app.js and it didn't work. – Tyler Langan Oct 15 '13 at 18:46
  • i don't believe the db class has a connect method. we recommend using the mongoclient class to establish a connection as it is now the standard way to connect. you can find an example here: https://github.com/mongolab/node-connection-pooling/blob/master/good.js – Chris Chang Oct 15 '13 at 19:21
1

First check your NODE_ENV environment

$ heroku config
=== ### Config Vars
MONGODB_URI:           mongodb://heroku_lhwpq2p3:sdvsdvsdvds@sdvsdv.mlab.com:dsvsd/heroku_lsdv
NODE_ENV:              production
NPM_CONFIG_PRODUCTION: true

the name you put in var

mongoUri = process.env.MONGOLAB_URI || localhost:..

should be :

var mongoUri = process.env.MONGODB_URI || localhost:..

if the error still persists then you need to set the NODE_ENV environment variable from development to production like :

$ heroku config:set NODE_ENV="production"
$ heroku config:set NPM_CONFIG_PRODUCTION=true
eGhoul
  • 2,490
  • 1
  • 13
  • 17
0

I was using MongoHQ but its similar, first you need to create user in addon for your database and then add credentials to URI (you should see uri in your mongo addon) example:

mongodb://user:pass@paulo.mongohq.com:10000/app12345678

Leg0
  • 510
  • 9
  • 21
  • Thanks Leg0! So what lines do I need to delete in app.js and employeeproviders.js? – Tyler Langan Oct 13 '13 at 17:57
  • change 'mongodb://localhost/mydb' to your custom uri – Leg0 Oct 14 '13 at 12:25
  • hardcoding your connection URI is perfectly functional, but I recommend against it in this case. Part of the convenience of a heroku addon is that environment variables are configured for you--you don't have to include sensitive information in your code repository unless you want to. – Eric Oct 14 '13 at 23:57