4

I am trying to connect to Mongodb through ssh username/password through nodejs as below :

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

var config = {
username : 'xyz',
host: 'xx-xxx-xx.com',
port:22,
password:'xxx',
dstPort:27017,
localPort:27017
};

console.log(tunnel);
var server = tunnel(config, function (error, server) {

if(error){
    console.log("SSH connection error: " + error);
}
console.log(server);
mongoose.connect('mongodb://localhost:27017/myDB');

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

But I am getting error as below : DB connection error: { MongoError: connection 0 to localhost:27017 timed out

What is the issue here?

Sowmya
  • 453
  • 1
  • 5
  • 18

1 Answers1

3

Probably is because you are missing the 'dstHost'in the config options.

The 'dstHost' must be the destination server url.

from official tunnel-ssh doc

 var config = {
      username:'root',
      Password:'secret',
      host:sshServer,
      port:22,
      dstHost:destinationServer,
      dstPort:27017,
      localHost:'127.0.0.1',
      localPort: 27000
    };

    var tunnel = require('tunnel-ssh');
    tunnel(config, function (error, server) {
      //.... 
    });
gzp___
  • 372
  • 3
  • 13
  • I tried by adding dstHost . But I am getting the same error. – Sowmya Dec 01 '17 at 11:25
  • have you also added localHost:'127.0.0.1' to the options ? – gzp___ Dec 01 '17 at 11:31
  • Yes I tried adding localHost:'127.0.0.1' also . But getting same result. – Sowmya Dec 01 '17 at 13:21
  • can you connect to your local db without tunnelin ? If so then there must be some config missing with your ssh server, have a look at this thread https://stackoverflow.com/questions/38509995/how-to-use-node-js-to-make-a-ssh-tunneling-connection-to-a-mongodb-database?rq=1 maybe you need a private key ? – gzp___ Dec 01 '17 at 13:43
  • I can connect to localdb with no errors. I dont have any private key . Through ssh username/password I am able to connect in MongoDB Compass but not from nodejs program – Sowmya Dec 01 '17 at 15:35