2

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 Answer 1

2

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)
});
Sign up to request clarification or add additional context in comments.

4 Comments

so I need to add await on the MongoClient.connect?
I've modified the answer
when I used this const _mongoClient = await MongoClient.connect(${baseurl}?${urlParams}, connectOptions); nothing happen, can you advise?
You need to put it inside of some async function or use then/catch. updated above

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.