psmod2
By:
psmod2

Unable to Connect to MongoDB in Node App

January 22, 2017 754 views
MongoDB Node.js

Hi,

I'm trying to get my Node app (separate droplet) to connect to my mongoDB droplet.

I've found a npm called tunnel-ssh however am having trouble.

It says "DB connection successful", however data is not coming back. And when I do a console.log(mongoose) it shows the host and host as null.

If I do console.log(mongoose), after the console.log("DB connection successful"); then it shows me the host.

Anyhow, my code looks like:

var tunnel = require('tunnel-ssh');

var config = {
agent : 'myuser',
host: 'xxx:xxx:xxx:xxx'
agent : process.env.SSHAUTHSOCK,
privateKey:require('fs').readFileSync('id_rsa'),
port:22,
dstPort:27010,
keepAlive: true
};

var server = tunnel(config, function (error, server) {

if(error){
    console.log("SSH connection error: " + error);
}

mongoose.connect('mongodb://127.0.0.1:27017/mysuperdb');

var db = mongoose.connection;
db.on('error', console.error.bind(console, 'DB connection error:'));
db.once('open', function() {
    console.log("DB connection successful");
});

});

2 Answers

I'm having the SAME issue. Everything works perfectly on cloud9, but I can't get mongo to connect to the app. Everything in the api folder (all the nodejs files) sends a 400 error bad request - not sure it's mongo as much as connecting to the non-public parts of the server (which connect to the db). But I don't know how to fix it, either. Did you find a resolution?

Hi,

I got it all working however i can't remember exactly what I did however from what i briefly remember it was something around the port numbers. I think i had them mixed up.
My final config var looks slightly different to what I have above - it's currently like:

var config = {
      username : 'xxxxxxx',
      host: 'xxx.xxx.xxx.xxx',
      port:22,
      privateKey:require('fs').readFileSync('id_rsa'),
      dstPort:2xxx7,
      localPort: 2xxx0
  };

I'd suggest try debugging around the 3 port numbers (port, dstPort, localPort).

Good luck!

Have another answer? Share your knowledge.