mongodb connect ssh tunnel nodejs code example

Example: ssh tunnel connect to mongodb in node.js

var config = {
    username:'myusername',
    host:'my.ip.address',
    agent : process.env.SSH_AUTH_SOCK,
    privateKey:require('fs').readFileSync('/Users/myusername/.ssh/id_rsa'),
    port:22,
    dstPort:27017,
    password:'mypassword'
};

var server = tunnel(config, function (error, server) {
    if(error){
        console.log("SSH connection error: " + error);
    }
    mongoose.connect('mongodb://localhost:27017/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");
    });
});