Home > Software engineering >  Unable to connect Nodejs driver to MongoDB Atlas cluster
Unable to connect Nodejs driver to MongoDB Atlas cluster

Time:07-09

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.

CodePudding user response:

You need to change the connection string like below with the database name.

mongoose
  .connect(
    'mongodb srv://username:[email protected]/databaseName?retryWrites=true&w=majority'
  )
  .then(result => {
    app.listen(3000);
  })
  .catch(err => {
    console.log(err);
  });

CodePudding user response:

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

https://docs.mlab.com/troubleshooting-atlas-connection-issues/

  • Related