can not connect to documentDB aws from node js backend

Viewed 140

I'm trying to connect my document DB from my node js backed but the _mongoClient return as undefined.

I open the ssh and I have all the permissions I need but it's still not working and there is no error in the console.

can you please help?

this is my code:

const {MongoClient, ObjectID} = require('mongodb');
const fs = require('fs');

 const path = require('path');
const filePath = path.resolve(__dirname,caFile)
const ca = [fs.readFileSync(filePath)];
let hostName = 'localhost';
let _mongoClient;
const baseurl = `mongodb://${username}:${password}@${hostName}:${port}/`;
let urlParams = `ssl=true&ssl_ca_certs=rds-combined-ca-bundle.pem&retryWrites=false`;
const connectOptions = {
    sslCA: ca,
    useUnifiedTopology:true
}

_mongoClient = await MongoClient.connect(`${baseurl}?${urlParams}`, connectOptions, function (err,client) {
        console.log(err+" , "+ client);
    });

1 Answers

The issue seems to be related to async/await. You cannot have awaitwithoutasync`.

Apart from this, you will not get _mongoClient outside of callback. You can access the client only inside the callback.

MongoClient.connect(`${baseurl}?${urlParams}`, connectOptions, (err, client) => {
  if(err) console.error(err);
  else console.log(client);
});

or skip callback to get a promise

const _mongoClient = await MongoClient.connect(`${baseurl}?${urlParams}`, connectOptions);

or

MongoClient.connect(`${baseurl}?${urlParams}`, connectOptions).then(_mongoClient => {
  console.log(_mongoClient)
}).catch(error => {
  console.log(error)
});
Related