Connect to MongoHQ with node.js app on cloud9

1.2k views Asked by At

I need some help connecting my node.js app (that I am editing in cloud9) to my database at MongoHQ. So far I have succesfully connected to the database via the terminal and was able to do a few commands:

use drywall;
db.admingroups.insert({ _id: 'root', name: 'Root' });
db.admins.insert({ name: {first: 'Root', last: 'Admin', full: 'Root Admin'}, groups: ['root'] });
var rootAdmin = db.admins.findOne();
db.users.save({ username: 'root', isActive: 'yes', email: '[email protected]', roles: {admin: rootAdmin._id} });
var rootUser = db.users.findOne();
rootAdmin.user = { id: rootUser._id, name: rootUser.username };
db.admins.save(rootAdmin);

but I dont know how to connect my app to the database, so when I try to run the app.js (which I know is not going to work) an I get this error:

mongoose connection error:  [Error: failed to connect to [localhost:27017]]
/var/lib/stickshift/52c97a42e0b8cde840000069/app-root/data/727946/drywall/node_modules/connect-mongo/lib/connect-mongo.js:176
      throw new Error('Error connecting to database');
^
Error: Error connecting to database
at /var/lib/stickshift/52c97a42e0b8cde840000069/app-root/data/727946/drywall/node_modules/connect-mongo/lib/connect-mongo.js:176:17
at /var/lib/stickshift/52c97a42e0b8cde840000069/app-root/data/727946/drywall/node_modules/connect-mongo/node_modules/mongodb/lib/mongodb/db.js:273:18
at /var/lib/stickshift/52c97a42e0b8cde840000069/app-root/data/727946/drywall/node_modules/connect-mongo/node_modules/mongodb/lib/mongodb/db.js:351:18
at Server.close (/var/lib/stickshift/52c97a42e0b8cde840000069/app-root/data/727946/drywall/node_modules/connect-mongo/node_modules/mongodb/lib/mongodb/connection/server.js:210:38)
at Db.close (/var/lib/stickshift/52c97a42e0b8cde840000069/app-root/data/727946/drywall/node_modules/connect-mongo/node_modules/mongodb/lib/mongodb/db.js:347:21)
at /var/lib/stickshift/52c97a42e0b8cde840000069/app-root/data/727946/drywall/node_modules/connect-mongo/node_modules/mongodb/lib/mongodb/db.js:271:21
at null. (/var/lib/stickshift/52c97a42e0b8cde840000069/app-root/data/727946/drywall/node_modules/connect-mongo/node_modules/mongodb/lib/mongodb/connection/server.js:563:7)
at EventEmitter.emit (events.js:106:17)
at null. (/var/lib/stickshift/52c97a42e0b8cde840000069/app-root/data/727946/drywall/node_modules/connect-mongo/node_modules/mongodb/lib/mongodb/connection/connection_pool.js:140:15)
at EventEmitter.emit (events.js:98:17)

(seems to me Im trying to connect to my localhost:27017, but I dont really know what I should connect to)

this is the app.js:

'use strict';

//dependencies
var config = require('./config'),
    express = require('express'),
    mongoStore = require('connect-mongo')(express),
    http = require('http'),
    path = require('path'),
    passport = require('passport'),
    mongoose = require('mongoose');

//create express app
var app = express();

//setup the web server
app.server = http.createServer(app);

//setup mongoose
app.db = mongoose.createConnection(config.mongodb.uri);
app.db.on('error', console.error.bind(console, 'mongoose connection error: '));
app.db.once('open', function () {
  //and... we have a data store
});

//config data models
require('./models')(app, mongoose);

//setup the session store
app.sessionStore = new mongoStore({ url: config.mongodb.uri });

//config express in all environments
app.configure(function(){
  //settings
  app.disable('x-powered-by');
  app.set('port', config.port);
  app.set('views', __dirname + '/views');
  app.set('view engine', 'jade');
  app.set('strict routing', true);
  app.set('project-name', config.projectName);
  app.set('company-name', config.companyName);
  app.set('system-email', config.systemEmail);
  app.set('crypto-key', config.cryptoKey);
  app.set('require-account-verification', config.requireAccountVerification);

  //smtp settings
  app.set('smtp-from-name', config.smtp.from.name);
  app.set('smtp-from-address', config.smtp.from.address);
  app.set('smtp-credentials', config.smtp.credentials);

  //twitter settings
  app.set('twitter-oauth-key', config.oauth.twitter.key);
  app.set('twitter-oauth-secret', config.oauth.twitter.secret);

  //github settings
  app.set('github-oauth-key', config.oauth.github.key);
  app.set('github-oauth-secret', config.oauth.github.secret);

  //facebook settings
  app.set('facebook-oauth-key', config.oauth.facebook.key);
  app.set('facebook-oauth-secret', config.oauth.facebook.secret);

  //middleware
  app.use(express.favicon(__dirname + '/public/favicon.ico'));
  app.use(express.logger('dev'));
  app.use(express.static(path.join(__dirname, 'public')));
  app.use(express.bodyParser());
  app.use(express.methodOverride());
  app.use(express.cookieParser());
  app.use(express.session({
    secret: config.cryptoKey,
    store: app.sessionStore
  }));
  app.use(passport.initialize());
  app.use(passport.session());
  app.use(app.router);

  //error handler
  app.use(require('./views/http/index').http500);

  //global locals
  app.locals.projectName = app.get('project-name');
  app.locals.copyrightYear = new Date().getFullYear();
  app.locals.copyrightName = app.get('company-name');
  app.locals.cacheBreaker = 'br34k-01';
});

//config express in dev environment
app.configure('development', function(){
  app.use(express.errorHandler());
});

//setup passport
require('./passport')(app, passport);

//route requests
require('./routes')(app, passport);

//setup utilities
app.utility = {};
app.utility.sendmail = require('drywall-sendmail');
app.utility.slugify = require('drywall-slugify');
app.utility.workflow = require('drywall-workflow');

//listen up
app.server.listen(app.get('port'), function(){
  //and... we're live
});

I tried to add

var db = mongoose.connect('mongodb://<user>:<password>@alex.mongohq.com:10067/drywall');

to the app.js but didn't work. It still wants to localhost.

2

There are 2 answers

0
Andreas On

The mongodb.uri is defined in config.js:

exports.mongodb = {
  uri: process.env.MONGOLAB_URI || process.env.MONGOHQ_URL || 'localhost/drywall'
};

If neither of the process variables are set it defaults to localhost. Try setting the process.env.MONGOHQ_URL before the code above to mongodb://<user>:<password>@alex.mongohq.com:10067/drywall

0
James Gentes On

For anyone else who runs into this issue, the solution is here: https://docs.c9.io/setting_up_mongodb.html

MongoDB is preinstalled in the Cloud9 workspace. Run this:

$ mkdir data
$ echo 'mongod --bind_ip=$IP --dbpath=data --nojournal --rest "$@"' > mongod
$ chmod a+x mongod

To start the Mongodb process, run:

$ ./mongod

Then 'run' your node.js app script and you're off to the races.

Here's what the parameters mean:

--dbpath=data (because it defaults to /var/db which isn't accessible)

--nojournal because mongodb usually pre-allocates 2 GB journal file (which exceeds Cloud9 disk space quota)

--bind_ip=$IP (because you can't bind to 0.0.0.0)

--rest runs on default port 28017