How to fix 'Error: querySrv EREFUSED' when connecting to MongoDB Atlas?

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?


Solution 1:

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.

Solution 2:

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