I'm currently working on a MERN stack project and facing an issue while attempting to connect my Mongoose to MongoDB Atlas and i already set IP address to access from anywhere so,i think it's not IP address whitelisted problem . Here's a snippet of the code I'm using for the connection:
import { connect, disconnect } from "mongoose";
async function connectToDatabase() {
try {
await connect(process.env.MONGO_URL);
} catch (error) {
console.log(error);
throw new Error("Could not connect to MongoDb");
}
}
async function disconnectFromDatabase() {
try {
await disconnect();
} catch (error) {
console.log(error);
throw new Error("could not disconnect from Mongo");
}
}
export { connectToDatabase, disconnectFromDatabase };
However, I'm encountering the following error:
Error: queryTxt EREFUSED cluster1.wcblrfc.mongodb.net
at QueryReqWrap.onresolve [as oncomplete] (node:internal/dns/promises:275:17) {
errno: undefined,
code: 'EREFUSED',
syscall: 'queryTxt',
hostname: 'cluster1.wcblrfc.mongodb.net'
}
Error: Could not connect to MongoDb
What could be causing this 'EREFUSED' error, and how can I resolve it to successfully connect to my MongoDB Atlas cluster?
There is connection problem I think.
You can try this code inside the try block:
const uri = `mongodb+srv://${process.env.mongo_user}:${process.env.mongo_password}@${process.env.mongo_DB_cluster}.mongodb.net/${your_DB}`;
await connect(uri);
Instead of this code:
await connect(process.env.MONGO_URL);
I hope it will work.