Connection to MongoDB with SSH in my Node App

狂风中的少年 提交于 2019-12-25 16:56:28

问题


My DB is with DigitalOcean and I'm trying to connect to it in my node app.

I've found a npm called tunnel-ssh however am having trouble connecting to it. My code is below.

It says DB connection successful, however 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.

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

var config = {
    agent : 'myuser',
    host: 'xxx:xxx:xxx:xxx'
    agent : process.env.SSH_AUTH_SOCK,
    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");
    });

});

回答1:


Here's the working code:

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

var config = {
    username : 'myuser',
    host: 'xxx:xxx:xxx:xxx',
    privateKey:require('fs').readFileSync('id_rsa'),
    port:22,
    dstPort:27010,
    localPort: 2000
};

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

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

    mongoose.connect('mongodb://127.0.0.1:2000/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:


Your ports aren't matching up. You have dstPort: 27010 but your connection string is 'mongodb://127.0.0.1:27017/mysuperdb'. One or the other needs to be corrected.



来源:https://stackoverflow.com/questions/41792528/connection-to-mongodb-with-ssh-in-my-node-app

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!