Search code examples
node.jsdatabasemongodbconnectionbackend

Connection timeout when connecting to MongoDB


I am trying to connect to the newly created database on MongoDB Atlas, but unfortunately, I am unable to do so. Here are the steps I followed to try resolving this issue (The project's name is 'inspector' as well as the database name):

  1. Inserting the connection string into the index.js file:
const express = require("express");
const app = express();
const dotenv = require("dotenv");
const mongoose = require("mongoose");

const port = 3000;
dotenv.config();

mongoose
  .connect(
    "mongodb+srv://<userName>:<password>@inspector.kkcifxp.mongodb.net/inspector"
  )
  .then(() => console.log("db connected"))
  .catch((err) => console.log(err));

app.get("/", (req, res) => res.send("Hello World!"));
app.listen(port, () => console.log(`Example app listening on port ${port}!`));


  1. Installing MongoDB for VS Code and tried connecting using the connection string.

  2. Changing the DNS on my PC to 8.8.8.8.

Unfortunately, none of the mentioned steps worked and the output was as follows:

Example app listening on port 3000!
Error: queryTxt ETIMEOUT inspector.kkcifxp.mongodb.net
    at QueryReqWrap.onresolve [as oncomplete] (node:internal/dns/promises:251:17) {
  errno: undefined,
  code: 'ETIMEOUT',
  syscall: 'queryTxt',
  hostname: 'inspector.kkcifxp.mongodb.net'
}

Can anyone help me overcome this issue?

Thanks in advance.


Solution

  • Go to MongoDB Atlas and click on Network Access and add your current IP address, this helps you to connect to MongoDB database. Most importantly don't forget to add your username and password in your MongoDB connection string.

    While you are deploying your backend just provide the IP address of the server in order to connect your backend to your MongoDB Atlas.