使用 Mongoose 的 Node.js SSH 隧道到 MongoDB [英] Node.js SSH Tunneling to MongoDB using Mongoose

查看:51
本文介绍了使用 Mongoose 的 Node.js SSH 隧道到 MongoDB的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个 Mongo DB.一种用于我的开发环境,一种用于生产环境,如我的 Robomongo 设置所示:

I have two Mongo DBs. One for my dev environment, one for production as seen here from my Robomongo setup:

生产数据库通过 SSH 隧道连接到我的 Digital Ocean 虚拟服务器,如下所示(细节已明显改变).连接到/从我的生产网站时,此设置工作正常:

The production db is SSH tunneled to my Digital Ocean virtual server as seen here (specifics have been changed obviously). This setup works fine when connecting to/from my production website:

我现在正在从事一个不同/相关的项目,需要将我的本地机器连接到我的生产> DB,所以我假设我需要使用诸如 tunnel-ssh 之类的东西来获取它完成了.我以 this answer 为例,但我要么得到 Error: (SSH) Channel open失败:打开失败 或者它正在连接到我的开发数据库(当我使用 27017 作为我的 dstHost/dstPort/localPort 时).我一定是在考虑这个错误,或者我对我的配置很愚蠢.不可否认,我是一个完整的 Mongo/Mongoose 新手,所以两者都是同样可能的.有什么建议吗?

I am now working on a different/related project and need to connect my local machine to my production DB, so I assumed I'd need to use something like tunnel-ssh to get it done. I've followed this answer as an example, but I'm either getting Error: (SSH) Channel open failure: open failed OR it's connecting to my Dev db (when I use 27017 as my dstHost/dstPort/localPort). I must be thinking about this wrong or I'm being dumb with my configuration. I am admittedly a total Mongo/Mongoose novice, so both are equally possible. Any advice?

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

//===== db connection =====

var config = {
    username:'my.username',
    host:'my.ip.address',
    agent : process.env.SSH_AUTH_SOCK,
    privateKey:require('fs').readFileSync('/Users/myusername/.ssh/id_rsa'),
    port:22,
    dstHost:'mongodb://localhost:27000/mydbname',
    dstPort:27000,
    localHost:'127.0.0.1',
    password:'mypassword',
    localPort: 27000
};

var server = tunnel(config, function (error, server) {
    if(error){
        console.log("SSH connection error: " + error);
    }
    mongoose.connect('mongodb://localhost:27000/mydbname');

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

提前致谢!

推荐答案

dstHost 需要是主机名/IP,而不是 MongoDB 连接字符串.在这种特殊情况下,您实际上可以在这种特殊情况下省略 dstHostlocalHostlocalPort,因为它们已经默认为您使用的值提供.

dstHost needs to be a hostname/IP, not a MongoDB connection string. In this particular case, you can actually omit dstHost, localHost, and localPort in this particular case because they already default to the values you're providing.

这篇关于使用 Mongoose 的 Node.js SSH 隧道到 MongoDB的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆