问题
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