Here a code that solve the issue for me:


const { MongoClient } = require("mongodb");

const uri =
  "mongodb+srv://<name>:<pw>@<server>/<db></db>?retryWrites=true&w=majority";

const client = new MongoClient(uri, {
  tls: true,
  serverSelectionTimeoutMS: 3000,
  autoSelectFamily: false,
});

async function connectToDatabase() {
  try {
    await client.connect();
    console.log("Connected to MongoDB successfully.");
    // Add your database operations here
  } catch (error) {
    console.error("Connection failed", error);
  } finally {
    await client.close();
  }
}

connectToDatabase();

2 Likes