0

I have created a DocumentDB with SSL enabled and I am using mongodb package using NodeJS to connect this DB using a Bastion Host. The issue is that if I put a hardcoded string inside the MongoClient.connect function, I am able to successfully connect the DB. The hardcoded code would look like as shown below.

let MongoClient = require('mongodb').MongoClient;
let client = MongoClient.connect(
   'mongodb://User:PWD@DBURL:27017/DBNAME?tls=true&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false',
    {
      tlsCAFile: __dirname + `rds-combined-ca-bundle.pem` //Specify the DocDB; cert
    },
    function(err, client) {
        if(err)
            throw err;

        console.log("1111111  2222222!!");    
        //Specify the database to be used
        db = client.db('DBNAME');
        //Specify the collection to be used
        col = db.collection('COLNAME');
        console.log("1111111 connected to db!!");

       client.close();
    });

Now as that's not an ideal situation to put the hardcoded values in the code. I am trying to read the values from environment variables and trying to put the whole URL into a string variable and passing this variable into that function such as shown below.

const DBURL = "mongodb://"+user+":"+pwd+"@"+dbURL+":"+port+"/"+dbName+"?tls=true&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false";
let client = MongoClient.connect(DBURL,
    {
      tlsCAFile: __dirname + `rds-combined-ca-bundle.pem` //Specify the DocDB; cert
    },
    function(err, client) {

Now this one timesout to connect the DB.

Any suggestions on it or should I use any other packages to connect DocumentDB via NodeJS, do let me know.

Mahdi Zarei
  • 5,644
  • 7
  • 24
  • 54
Sanjib Behera
  • 101
  • 1
  • 13

1 Answers1

0

Something like this works for me:

const { MongoClient } = require('mongodb')

const DOCUMENTDB_CONNECTION_STRING = `mongodb://${process.env.DOCDB_USER}:${process.env.DOCDB_PASS}@${process.env.DOCDB_ENDPOINT}/${process.env.DOCDB_DBNAME}?tls=true&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false`

const client = MongoClient.connect(
    DOCUMENTDB_CONNECTION_STRING, {
        tlsCAFile: `rds-combined-ca-bundle.pem` //Specify the DocDB cert
    },
    function(err, client) {

Is this what you are looking for?

Mihai A
  • 351
  • 1
  • 4