When I tried to connect a Nodejs app with MongoDB Atlas cluster (a free cluster) with the below code block. It can be successfully connected if run with personal hotspot. But when executing with home wifi, the terminal threw errors.
const mongoose = require("mongoose");
const express = require("express");
const app = express();
const bodyParser = require("body-parser");
const connectDB = async () => {
mongoose.connect(
"mongodb+srv://username:[email protected]/?retryWrites=true&w=majority",
{ useNewUrlParser: true }
);
};
connectDB();
app.listen(8080);
When I ran the code, I replaced username & password with the real username and password.
The terminal threw errors as below:
<pre>node:internal/errors:464
ErrorCaptureStackTrace(err);
^
Error: queryTxt EBADNAME cluster0.ibx1kue.mongodb.net
at QueryReqWrap.onresolve [as oncomplete] (node:dns:213:19) {
errno: undefined,
code: 'EBADNAME',
syscall: 'queryTxt',
hostname: 'cluster0.ibx1kue.mongodb.net'
}</pre>
I tried to search solutions online, I saw someone else posted questions related to Atlas connection issues. However, the error message they got had something to do with
<pre>Error: queryTxt ETIMEOUT cluster0.ibx1kue.mongodb.net
at QueryReqWrap.onresolve [as oncomplete] (node:dns:213:19) {
errno: undefined,
code: 'ETIMEOUT', //the error I received is code: 'EBADNAME'
syscall: 'queryTxt',
hostname: 'cluster0.ibx1kue.mongodb.net'
}</pre>
I also contacted MongoDB Atlas customer service. Some tech support tried to help me. But after he did some tests from his side, the connection issue was not resolved. He suggested me to try to use MongoDB Compass to connect to the cluster. If it also failed there were probably something wrong with the cluster and it would be outside of his scope of service. So I tried to connect the same cluster to MongoDB Compass and it failed, throwing the same error message
queryTxt EBADNAME cluster0.ibx1kue.mongodb.net
Does anyone know how to solve the connection problem? I would be very appreciated.
2
Answers
I just figured out the solution. I changed the connection string to the older format of connection string ie non-SRV connection string. I found solution from
The following is relevant quotation from the link above:
My solution to the connection problem is to change SRV connection string to the non-SRV connection string.
Where to find non-SRV connection string? At least for the time when I post the answer, I would click the Connection button of the cluster, choose Connect your application. Then the window would ask you to select the driver and version, choose Driver Node.js and version 2.2.12 or later. Then you could see the non-SVR string under Add your connection string into your application code.
You need to change the connection string like below with the database name.