42

I am new to MongoDB 4.0.6 and tried to implement it into my website using Node/Express.js, but when I try to connect to mongodb+srv://${process.env.MONGOUSER}:${process.env.MONGOPASS}@main-03xkr.mongodb.net/main I'm getting this error:

{ Error: querySrv EREFUSED _mongodb._tcp.main-03xkr.mongodb.net at QueryReqWrap.onresolve [as oncomplete] (dns.js:199:19) errno: 'EREFUSED', code: 'EREFUSED', syscall: 'querySrv', hostname: '_mongodb._tcp.main-03xkr.mongodb.net' }

I've tried connecting to mongodb://localhost:27017/main, but this does seem work.

Here is the relevant code:

require('dotenv').config();
const mongoose = require('mongoose');

// Database
const uri = `mongodb+srv://${process.env.MONGOUSER}:${process.env.MONGOPASS}@main-03xkr.mongodb.net/main`;
const localURI = 'mongodb://localhost:27017/main';

var Project = require('./models/project');

mongoose.connect(uri, { useNewUrlParser: true });
const db = mongoose.connection;

db.once('open', () => console.log('Successfully connected to MongoDB'));
db.on('error', (e) => console.log(e));

// Routes
app.get('/', (req, res) => {
  Project.find({}, (e, projects) => {
    if (e) console.log(e);

    res.render('home.ejs', {
      projects: projects
    });
  });
});

So does anyone know how to fix this error and maybe explain what is happening here?

Noodles
  • 3,888
  • 2
  • 20
  • 31

17 Answers17

74

If you're encountering this error try to use the older connection string for Node.js 2.2.12 or later:

mongodb://<username>:<password>@main-shard-00-00-03xkr.mongodb.net:27017,main-shard-00-01-03xkr.mongodb.net:27017,main-shard-00-02-03xkr.mongodb.net:27017/main?ssl=true&replicaSet=Main-shard-0&authSource=admin&retryWrites=true

According to MongoDB, SRV is possibly not working due to Mongoose.

Noodles
  • 3,888
  • 2
  • 20
  • 31
  • Thanks for the answer, it worked for me as well. But I would love to know why isn't it working with 3.0? – amine23 Mar 26 '20 at 12:58
  • 2
    When I asked the MongoDB staff, they said it might be because of Mongoose, but I don't know the specific answer. – Noodles Mar 26 '20 at 13:46
  • 1
    I encountered this error but due to inactivity of my website. The mongodb connection automatically paused the instance when there's no activity of the website. I resume the connection and all goes well. Cheers! – Grald Jul 10 '21 at 13:06
59

I had this same error when I was connecting with Node version 3.0 or later and I resolved it by downgrading to 2.2.12 or later version:

downgrade

Samuel Philipp
  • 10,631
  • 12
  • 36
  • 56
Joseph Kasule
  • 699
  • 5
  • 3
  • 1
    This works although the "mongodb" package i am using from npm is at ^v3.5.7 which should be considered for "3.0 or later" connections. But the "3.0 or later" one works for my AWS EC2 instance just fine but not locally. local node -v -> 13.0.x AWS node -v -> 10.20.1 – kaushalop Jul 21 '20 at 04:29
  • Same here, Windows runs just fine but Linux with the same configuration doesn't (mongodb@3.6.8 node@14.15.4). Using the older connection string works for some reason. – Sjeiti Jun 15 '21 at 14:06
16

In my case, it's mainly a DNS issue in mac, to resolve it, just add google DNS server under the DNS section in mac book pro settings:

8.8.8.8
4.4.4.4

enter image description here

HMagdy
  • 3,029
  • 33
  • 54
15

This error occurs sometimes when you are using MongoDB Atlas and lost your internet connectivity. You will not be able to access your database.

11

Make sure to change the node version to 2.2.12:

enter image description here

And add IP address:

enter image description here

4b0
  • 21,981
  • 30
  • 95
  • 142
MOHAMMED NABAWY
  • 221
  • 3
  • 7
  • 2
    This was my problem - the new unified connection string would sometimes work, sometimes not. It was extremely frustrating to troubleshoot. Went back to the old connection string format and it instantly worked again. – Layne Bernardo Jul 13 '21 at 09:19
5

Pass option { useNewUrlParser: true, useUnifiedTopology: true } to the MongoClient constructor

const uri = "mongodb+srv://${process.env.MONGOUSER}:${process.env.MONGOPASS}@main-03xkr.mongodb.net/main"

mongoose.connect(uri, { useNewUrlParser: true, useUnifiedTopology: true })
    .catch(error => console.log(error));
hoangdv
  • 15,138
  • 4
  • 27
  • 48
Abin Abbas
  • 51
  • 1
  • 3
4

In my case it was throwing this error due mongodb cluster auto paused because of prolonged inactivity. I just resumed it, then it started properly.

Rohit Parte
  • 3,365
  • 26
  • 26
3

You have undefined in your connection string. I don't know if this is typo or not. But try changing

const uri = `mongodb+srv://undefined:${process.env.MONGOPASS}@main-03xkr.mongodb.net/main`;

to

const uri = `mongodb+srv://${process.env.MONGOUSER}:${process.env.MONGOPASS}@main-03xkr.mongodb.net/main`;

I use MongoAtlas for a project and that string (minus the undefined user) looks correct.

VtoCorleone
  • 16,813
  • 5
  • 37
  • 51
  • haha... interesting. I'd scrub that from your stack post just so people can't try and guess a password for your credentials. Can you try connecting to the instance through the CLI? https://docs.atlas.mongodb.com/mongo-shell-connection/ Just to test that your credentials and URL is correct? – VtoCorleone Apr 03 '19 at 17:39
  • Sorry for the late response. It does connect using the CLI, so I guess it must be something in my code. – Noodles Apr 11 '19 at 18:00
3

In our case antivirus/firewall is blocking,

Try to disable antivirus/firewall and check again. hope it will work.

Shaik Matheen
  • 1,233
  • 15
  • 14
3
Error: querySrv ESERVFAIL _mongodb._tcp.databasename-zcbag.mongodb.net
    at QueryReqWrap.onresolve [as oncomplete] (dns.js:202:19) {
  errno: 'ESERVFAIL',
  code: 'ESERVFAIL',
  syscall: 'querySrv',
  hostname: '_mongodb._tcp.databasename-zcbag.mongodb.net'
}

If the above code is your output then there is no error in your code. You have to check your network connection. Maybe you have to switch your network from the phone network to another or vice versa.

Tomer Shetah
  • 8,413
  • 7
  • 27
  • 35
Bimal Paul
  • 31
  • 1
2
MongoClient.connect(
  "mongodb://USER:PASSWORT@mflix-shard-00-00-r5yfb.mongodb.net/test?ssl=true&replicaSet=mflix-shard-0&authSource=admin&retryWrites=true&w=majority",
  { useNewUrlParser: true, useUnifiedTopology: true },
)
  .catch(err => {
    console.error(err.stack)
    process.exit(1)
  })
  .then(async client => {
    await MoviesDAO.injectDB(client)
    await UsersDAO.injectDB(client)
    await CommentsDAO.injectDB(client)
    app.listen(port, () => {
      console.log(`listening on port ${port}`)
    })
  })

Maybe can works with MongoClient( not Mongoose )

Hamada
  • 1,836
  • 3
  • 13
  • 27
1

In my case, this error was happening when the DNS configuration in my TP-Link Router was missing.

I've installed OpenWRT firmware on it and forgot to adjust DNS settings.

I was able to open YouTube or any other website because that's not my main router, but could not connect to database.

It was an internet issue, like @Kamesh Kumar Singh said in his answer.

I think that this is not an usual answer for this question, but may help someone.

edu4hd0
  • 301
  • 2
  • 3
1

This error occurs if you are not able to connect to mongoDB Atlas database. Your server runs successfully but you get this error while connecting to database. Make sure your internet connection is good and try again you won't see this error.

1

In my case, the issue occurred because MongoDB paused my cluster due to over 4 months of inactivity. After I logged in to my account and resumed the activity of the cluster, the issue was immediately resolved.

Timothy
  • 91
  • 1
  • 6
1

I solved mine by going into the MongoDB -> login -> databases -> connect -> connect your application (middle one) -> copy the code -> paste the code into the mongooseDB code in my .JS file:

const mongoose = require('mongoose');
require('dotenv/config');

mongoose
  .connect(process.env.THE_MONGO_DB_URL_GOES_HERE_IN_DOTENV_FILE, {
    useNewUrlParser: true,
    useUnifiedTopology: true,
    useCreateIndex: true,
  })
  .then(() => console.log("Database connected!"))
  .catch(err => console.log(err));

  const PostSchema = mongoose.Schema({
    email: String,
    password: String
  }, {strict: false});

  const DataEntry = mongoose.model('n26-users-collection', PostSchema); 

  module.exports = DataEntry; 
fruitloaf
  • 1,628
  • 15
  • 10
0

"Not in the root folder" scenario:

Create a .env file in the root directory of your project. https://github.com/motdotla/dotenv

enter image description here

One scenario for this error is to create dotenv .env file --NOT-- in the root folder (Under /src for example).

Than this code:

const url = `mongodb+srv://${process.env.DB_USER}:${
  process.env.DB_USER_PASSWORD
}@${process.env.DB_CLUSTER}.mongodb.net`;

console.log(url)

output:

mongodb+srv://undefined:undefined@undefined.mongodb.net

So the "undefined" URL connection:

const client = new MongoClient(url);

Throw 3 warnings:

(node:27240) UnhandledPromiseRejectionWarning: Error: querySrv ENOTFOUND _mongodb._tcp.undefined.mongodb.net at QueryReqWrap.onresolve [as oncomplete] (dns.js:207:19)

(node:27240) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag --unhandled-rejections=strict (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)

(node:27240) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.


One more "close" scenario: .env in the root folder but the file is empty:

enter image description here


Solution

The first step to solve this issue is to console.log(url) and check if process.env returns the correct Connection String.


Related:

Ezra Siton
  • 6,887
  • 2
  • 25
  • 37
0

For the most part this error occurs when there is a mongodb driver and comnnection string mismatch. Ensure that use the conncetion string and its equivalent driver as specified in the Mongodb atlas connect section. Important Tip, dont use the latest mongodb driver. Use the previous version. You can acert conncetion issues easily.

augustino
  • 429
  • 4
  • 4