MongoDb Connection failed : Error: querySrv ECONNREFUSED
How can I solve this error? My node v24.13.0 and mongoose 9.1.5 are the latest versions. Also I changed my network dns to Google's dns number 8.8.8.8, and in my mongodb atlas network acc ip address is 0.0.0.0/0 so that any ip address can access and install Locally in my system.
Here is the connection code:
import express from "express";
import mongoose from "mongoose";
import cors from "cors";
import dotenv from "dotenv";
dotenv.config({ path: "./.env" });
const app = express();
const MONGO = process.env.MONGO_URL;
mongoose
.connect(MONGO)
.then(() => {
console.log("Database Successfully connected");
})
.catch((error) => {
console.error(`MongoDb Connection failed : ${error}`);
});
app.use(express.json());
app.use(cors());
app.listen(5000, () => {
console.log(`Server started on port Number : 5000`);
});
error png
Note that when I used this it works perfectly:
import express from "express";
import mongoose from "mongoose";
import cors from "cors";
import dotenv from "dotenv";
dotenv.config({ path: "./.env" });
/* works when I add this */
import dns from "node:dns/promises";
dns.setServers(["1.1.1.1", "1.0.0.1"]);
const app = express();
const MONGO = process.env.MONGO_URL;
mongoose
.connect(MONGO)
.then(() => {
console.log("Database Successfully connected");
})
.catch((error) => {
console.error(MongoDb Connection failed : ${error});
});
app.use(express.json());
app.use(cors());
app.listen(5000, () => {
console.log(Server started on port Number : 5000);
});
But the problem is I have so many projects that I already built, so I don't want to add this in every project:
import dns from "node:dns/promises";
dns.setServers(["1.1.1.1", "1.0.0.1"]);
Is there another solution?
mongodb+srv://, try forcing public DNS before connecting:js import dns from "node:dns"; dns.setServers(["1.1.1.1", "1.0.0.1"]); await mongoose.connect(MONGO_URI);This fixesquerySrv ECONNREFUSEDcaused by SRV lookup failures in newer Node.js DNS resolver. Only affects the current process, not system DNS.