ExpressJs server not getting connected with the MongoDB atlas Cluster

First of all, Thanks in Advance and a huge sorry if my Doubt sounds you stupid.
But , you know I literally wasted whole day on this error.
I am new to MongoDB and is trying to connect our MongoDB cluster with ExpressJs server. And endup in lot of errors.
I will owe you for any help.

import express from 'express';
import bodyParser from 'body-parser';
import mongoose from 'mongoose';
import cors from 'cors';

const app = express();

app.use(bodyParser.json({limit: "30mb", extended: true}));
app.use(bodyParser.urlencoded({limit: "30mb", extended: true}));

import MongoClient from 'mongodb';
import ServerApiVersion from 'mongodb';
const uri = "mongodb+srv://";
const client = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true, serverApi: ServerApiVersion.v1 });
client.connect(err => {
  const collection = client.db("test").collection("devices");
  // perform actions on the collection object

It is always better if you share the error you get.

I get authentication failed when I tried your URI. It means either the user name and/or the password is wrong for the given cluster.

Thanks steevej for letting me know,
Forget about the code I have posted , I made some changes after that code :

Following is by backend folder structure :

├── client
│ ├──
│ ├── package-lock.json
│ ├── package.json
│ ├── public
│ │ ├── favicon.ico
│ │ ├── index.html
│ │ ├── logo192.png
│ │ ├── logo512.png
│ │ ├── manifest.json
│ │ └── robots.txt
│ └── src
│ ├── App.css
│ ├── App.js
│ ├── components
│ └── index.js
└── server
├── db
│ └── config.js
├── index.js
├── models
│ └── Book.js
├── mongodb
│ └── connect.js
├── package-lock.json
└── package.json

8 directories, 18 files

Here’s my new code for index.js :

import express from 'express';
import * as dotenv from 'dotenv';
import cors from 'cors';

import connectDB from './mongodb/connect.js'


const app = express();
app.use(express.json({ limit: '50mb' }));

app.get('/', (req, res) => {
  res.send({ message: 'Hello World' });

const startServer = async () => {
  try {
    // connect to the database...

    app.listen(8080, () => console.log("Server started on port http://localhost:8080"));
  } catch (error) {


Here is my cluster’s credentials :
username : pratham786
following is my connection string :
MONGODB_URL = mongodb+srv://

Here’s my connect.js file code :

import mongoose from 'mongoose';

const connectDB = (url) => {
    mongoose.set('strictQuery', true);

        .then(() => console.log('MongoDB connected'))
        .catch((error) => console.log('Not connected'));

export default connectDB;

Here’s what actually I am getting after doing npm start :

> server@1.0.0 start
> nodemon index.js

[nodemon] 2.0.22
[nodemon] to restart at any time, enter `rs`
[nodemon] watching path(s): *.*
[nodemon] watching extensions: js,mjs,json
[nodemon] starting `node index.js`
Server started on port http://localhost:8080
Not connected

I was expecting that by backend will get connected with the cluster, but its not why?
Please I need your help really bad.
Thanks in advance!

Most API return error codes, error messages or throw exceptions to help investigation issues with code or configuration. When you code like

where you write Not connected rather than the error you hide all the information you can get to help you resolve the issue.

When we write

we want the real error message that the API provides you. Not a message that simply say it failed.

If you prefer to still hide the cause of the failure with the Not connected, you may always use Compass or mongosh with your URI to see what is the cause of Not connected. I did and your modified URI still produce

I suggest that rather than trying to make your code work, try your URI with Compass or mongosh until you can connect. Once, you can connect with software that produce real error messages, try using the same URI with your code.

1 Like

I replaced :

        .then(() => console.log('MongoDB connected'))
        .catch((error) => console.log('Not connected'));

with :

        .then(() => console.log('MongoDB connected'))
        .catch((error) => console.log(error));

This is what I am getting in the terminal after doing “npm start” :

nodemon index.js
PS C:\Users\DELL-PC\Desktop\Memories\server> npm start

server@1.0.0 start
nodemon index.js

[nodemon] 2.0.22
[nodemon] to restart at any time, enter rs
[nodemon] watching path(s): .
[nodemon] watching extensions: js,mjs,json
[nodemon] starting node index.js
Server started on port http://localhost:8080
Error: queryTxt ETIMEOUT
at QueryReqWrap.onresolve [as oncomplete] (node:internal/dns/promises:173:17) {
errno: undefined,
code: ‘ETIMEOUT’,
syscall: ‘queryTxt’,
hostname: ‘

Thanks!!! a lot for your help.
I read some community post where people had same issue even after the did everything correct.
It was the problem of DNS resolver. I changed my DNS server from settings and Yup MongoDB got connected.


This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.