Mongoose not connecting on Ubuntu Ubuntu 14.04

546 Views Asked by At

I've got a node app built on Hapi using MongoDB and mongoose. Locally, I can use the app without issue. I can connect to the db, add data, find it, etc.

I've created an Ubuntu 14.04 x64 droplet on Digital Ocean.

I can ssh into my droplet and verify that my db is there with the correct name. I'm using dokku-alt to deploy and I have linked the db name to the app using dokku's mongodb:link appName mydb

I was having issues once I deployed the app where it would hang and eventually timeout. After a lot of debugging and commenting out code I found that any time I try to hit mongo like this the app will hang:

var User = request.server.plugins.db.User;
User
  .findOne({ id: request.auth.credentials.profile.raw.id })
  .exec(function(err, user){
    // do something
  });

Without this, the app loads fine, albeit without data. So my thought is that mongoose is never properly connecting.

I'm using grunt-shell-spawn to run a script which checks if mongo is already running, if not it starts it up. I'm not 100% certain that this is needed on the droplet, but I was having issues locally where mongo was already running... script:

/startMongoIfNotRunning.sh

if pgrep mongod; then
  echo running;
else
  mongod --quiet --dbpath db/;
fi

exit 0;

/Gruntfile.js

shell: {
  make_dir: {
    command: 'mkdir -p db'
  },
  mongodb: {
    command: './startMongoIfNotRunning.sh',
    options: {
      stdin: false,
    }
  }
},

And here's how I'm defining the database location:

/index.js

server.register([
  { register: require('./app/db'), options: { url: process.env.MONGODB_URL || 'mongodb://localhost:27017/mydb' } },
....

/app/db/index.js

var mongoose = require('mongoose');
var _ = require('lodash-node');
var models = require('require-all')(__dirname + '/models');

exports.register = function(plugin, options, next) {

  mongoose.connect(options.url, function() {
    next();
  });

  var db = mongoose.connection;

  plugin.expose('connection', db);
  _.forIn(models, function(value, key) {
    plugin.expose(key, value);
  });

};

exports.register.attributes = {
  name: 'db'
};

My app is looking for db files in db/. Could it be that dokku's mongodb:link appName mydb linked it to the wrong location? Perhaps process.env.MONGODB_URL is not being set correctly? I really don't know where to go from here.

1

There are 1 best solutions below

0
On BEST ANSWER

It turns out the solution to my problem was adding an entry to the hosts file of my droplet to point to the mongo db url:

127.0.0.1 mongodb.myurl.com

For some reason, linking the db to my app with Dokku didn't add this bit. I would have thought that it was automatic. The app container's host file did get a mongodb entry when i linked the db to the app.