Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 724
Noodles Avatar asked Apr 03 '19 15:04

Noodles


People also ask

Why MongoDB Atlas is not connecting?

If you have created a user and are having trouble authenticating, try the following: Check that you are using the correct username and password for your database user, and that you are connecting to the correct database deployment. Check that you are specifying the correct authSource database in your connection string.

How does MongoDB connect to node js database?

To create a database in MongoDB, start by creating a MongoClient object, then specify a connection URL with the correct ip address and the name of the database you want to create. MongoDB will create the database if it does not exist, and make a connection to it.


Video Answer


1 Answers

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.

like image 162
Noodles Avatar answered Sep 19 '22 18:09

Noodles