How to use Node.js to make a SSH tunneling connection to a MongoDB database

后端 未结 3 1527
栀梦
栀梦 2020-12-15 14:49

My credentials work perfectly with Robomongo but I can\'t make the connection with node.js
I have tried to make the connection using ssh2 and tunnel-ssh npm module and f

3条回答
  •  时光说笑
    2020-12-15 15:06

    You can do it with official mongodb client for node

    const sshTunnelConfig = {
      agent: process.env.SSH_AUTH_SOCK,
      username: 'ec2-user',
      privateKey: require('fs').readFileSync('./path-to-ec2-key.pem'),
      host: '3.98.174.12', //IP adress of VPS which is the SSH server
      port: 22,
      dstHost: 'docdb-cluster-vmabwxueb51y.eu-central-1.docdb.amazonaws.com',
      dstPort: 27017,
      localHost: '127.0.0.1',
      localPort: 27018 //or anything else unused you want
    };
    
    
    const connectionProperties = {
      sslValidate: true,
      ssl: true,
      sslCA: [fs.readFileSync('rds-combined-ca-bundle.pem')],
      useNewUrlParser: true,
      useUnifiedTopology: true,
      authMechanism: 'SCRAM-SHA-1',
      auth: {
        user: 'docdbuser',
        password: ''
      },
      tlsAllowInvalidHostnames: true,
      tlsAllowInvalidCertificates: true,
    };
    
    tunnel(sshTunnelConfig, async (error, server) => {
      if (error) {
        console.log('SSH connection error: ', error);
      }
      
       const MongoClient = require('mongodb').MongoClient;
       const client = MongoClient.connect('mongodb://localhost:27018/', propertiesConnection,
        function(err, client) {
          if(err)
            throw err;
    
          //Specify the database to be used
          db = client.db('database-name');
    
          //Specify the collection to be used
          col = db.collection('collection-name');
    
          //Insert a single document
          col.insertOne({'hello':'Amazon DocumentDB'}, function(err, result){
            //Find the document that was previously written
            col.findOne({'hello':'Amazon DocumentDB'}, function(err, result){
              //Print the result to the screen
              console.log(result);
    
              //Close the connection
              client.close()
            });
          });
        });
      
    });

提交回复
热议问题