Mongoose is not connecting MongoDB Atlas - node.js

This is the first time I use MongoDB Atlas to work with Mongo, and while trying to connect, that's the error I get:
Error: connect ECONNREFUSED 3.209.60.172:27017
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1054:14) {
name: 'MongoNetworkError',
errorLabels: [ 'TransientTransactionError' ],
[Symbol(mongoErrorContextSymbol)]: {}
}
This is my code:
const express = require('express');
const mongoose = require('mongoose');
const app = express();
mongoose.connect('mongodb+srv://johnnybox:<password>#cluster0-cgxqx.mongodb.net/test?retryWrites=true&w=majority', {
useNewUrlParser: true
}).then(() => console.log('MongoDB Connected...'))
.catch(err => console.log(err));
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use(require('./routes'));
app.listen(3331);
ps* I'm not missing my credentials
Already looked for a solution here but there's nothing similar to my problem.
My whitelist:

try this
mongoose
.connect(
'mongodb+srv://{my_user}:{mypass}#johnnybox-cgxqx.mongodb.net/johnnybox?retryWrites=true&w=majority',
{ useNewUrlParser: true }
)
.then(() => console.log('MongoDB Connected...'))
.catch(err => console.log(err));

Try adding your IP Address in the mongo atlas IP Whitelist.
Otherwise accept every connections if you don't need secure connection.

A new answer to the new error:
According to this answer, which had the same exact error, that is:
'MongoNetworkError',
errorLabels: [ 'TransientTransactionError' ],
[Symbol(mongoErrorContextSymbol)]:
Add your current IP to whiteList following "clusters/security/whitelist" in MongoDB website.
I'm sorry, I spent at least an hour to solve this. That's all I can do.
Old answer addressing the former error (he fixed this part, but still got a new error):
If you read the error log carefully it says:
UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block
That means you needed to add catch() to your mongoose connection:
mongoose.connect({some code}).then({some code}).catch(err => console.log(err))

I tried to run this code at home and it worked perfectly!
So it was something here in my office, after some testing, the problem was with the connection port that was locked.
Take a look:
Error: connect ECONNREFUSED 3.209.60.172:27017
Note that it connects to the port 27017
**The Ip is random, so it changes after every requisition.
After my Sd opened this port, everything worked properly!!
Thanks so much for your help guys!

For those of you who tried various URIs the only thing that got it working here is to Add you IP vs allow the access from anywhere. Hope that saves you some time.

Related

MongoDB can be connected with MongoClient but not mongoose

So when I run my app in deployment, with the backend connecting to MongoDB using MongoClient as follow:
import { MongoClient } from 'mongodb'
const url = process.env.MONGODB_URI
MongoClient.connect(url, { useNewUrlParser: true, useUnifiedTopology: true },(err, db)=>{
console.log(url)
db.close()
})
everything works fine. But if I change it into
import mongoose from 'mongoose'
mongoose.Promise = global.Promise
mongoose.connect(url, { useNewUrlParser: true, useCreateIndex: true, useUnifiedTopology: true })
mongoose.connection.on('error', () => {
throw new Error(`unable to connect to database: ${url}`)
})
it gives the following error:
webpack://HappyHourWeb/./server/server.js?:29
throw new Error(`unable to connect to database: ${_config_config__WEBPACK_IMPORTED_MODULE_0__["default"].mongoUri}`)
^
Error: unable to connect to database: my_database_url,
at NativeConnection.eval (webpack://HappyHourWeb/./server/server.js?:29:9)
at NativeConnection.emit (node:events:390:28)
at /Users/Hieudo/Documents/Project/HappyHourWeb/node_modules/mongoose/lib/connection.js:807:30
at processTicksAndRejections (node:internal/process/task_queues:78:11)
Any help is greatly appreciated!
According to various sources, including MongoDB Connection String URI reference, Mongoose connection docs (Ctrl+F and search for srv to jump to the right topic) and the most upvoted answer on this question on SO, you should handle standard URIs and DNS URIs differently.
Mongoose accepts a dbName option that is
[...]useful if you are unable to specify a default database in the connection string like with some mongodb+srv syntax connections.
The fact that the native MongoDB driver handles it automatically doesn't necessarily means that Mongoose will. Try separating the DB name from the URI and pass it as the second argument when connecting with Mongoose.
Also, that part of your code :
mongoose.connection.on('error', () => {
throw new Error(`unable to connect to database: ${url}`)
})
doesn't check for connection errors, it emits an event if an error is encountered after the initial connection has been made.
As Joe pointed out in the comments, you should handle both the initial connection errors AND errors that may come after it, either with the try/catch syntax or the .catch callback. More info in the docs.

Error while connecting to the mongodb Atlas from shared linux hosting server

I am trying to connect to mongoDB Atlas from my nodejs app its giving me the following error:
SERVER STARTED...
listening on port 'http://localhost:8080'
Could not connect to the MongoDB database. Exiting now... { Error: connect ECONNREFUSED 13.234.134.161:27017
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1106:14)
name: 'MongoNetworkError',
errorLabels: [ 'TransientTransactionError' ],
[Symbol(mongoErrorContextSymbol)]: {} }
Also I have whitelisted IP on Mongodb Cloud (Atlas). I set it as 'Access to all' which is: 0.0.0.0/0
Same code is working fine on my local machine.
SERVER STARTED...
listening on port 'http://localhost:8080'
Successfully connected to the MongoDB database
The problem occurs when I am deploying my code to GoDaddy shared linux hosting server and trying to connect from there.
What's making difference...?
My nodejs code is:
app.set('port', process.env.PORT || 8080);
var options = {
useNewUrlParser: true,
useUnifiedTopology: true
}
mongoose.connect(dbConfig.dbUrl, options, function(err){
if(err){
console.log('Could not connect to the MongoDB database. Exiting now...', err);
process.exit();
} else {
console.log("Successfully connected to the MongoDB database");
}
});
const server = app.listen(app.get('port'), function(){
console.log(`SERVER STARTED...\nlistening on port 'http://localhost:${app.get('port')}'`);
});
DB url is as follows:
dbUrl: "mongodb+srv://<USERNAME>:<PASSWORD>#cluster0-qsfll.mongodb.net/<DATABASE>?retryWrites=true&w=majority"
If anyone got the same issue and solved it, please write the solution here. Thanks :).
Just got the same issue.
Try to remove useUnifiedTopology.
Helped for me.

Node/express application failing to connect to Mongodb Atlas using mongoose

I have a node/express application that I am trying to connect to Mongodb Atlas using mongoose.
All of my code is identical to a previous app that I had connect to Atlas (which worked fine). When I run it on my work machine (Windows 10) everything works as expected. However, when I run it on my MacBook Pro (Mojave), the express app runs but the mongoose connection to Atlas throws the following error:
{ Error: queryTxt EBADNAME development-zv5hp.mongodb.net
at QueryReqWrap.onresolve [as oncomplete] (dns.js:196:19)
errno: 'EBADNAME',
code: 'EBADNAME',
syscall: 'queryTxt',
hostname: 'development-zv5hp.mongodb.net' }
server.js
const express = require('express');
const mongoose = require('mongoose');
const app = express();
mongoose
.connect(
'mongodb+srv://client:<PASSWORD>#development-zv5hp.mongodb.net/shop',
{ useNewUrlParser: true }
)
.then(() => console.log('MongoDB Connected...'))
.catch(err => console.log(err));
const PORT = process.env.PORT || 5000;
app.listen(PORT, () => console.log(`Server running on port ${PORT}`));
What might be causing this issue?
I have checked the Atlas user and password and have whitelisted my IP (in fact whitelisted all IPs)
Using:
node v10.15.3
express v4.16.4
mongoose v5.5.1
Using Google's DNS server 8.8.8.8 and 8.8.4.4 can resolve this issue
please add autoIndex: false its working for me
mongoose
.connect(
'mongodb+srv://client:<PASSWORD>#development-zv5hp.mongodb.net/shop',
{autoIndex: false, useNewUrlParser: true }
This error is caused because the URI 'mongodb+srv://client:<PASSWORD>#development-zv5hp.mongodb.net/shop' that was passed to connect was unable to be resolved. Your DNS server does not know it and thus cannot resolve an IP. Hence ebadname.
change this like Addison mentioned

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?
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.
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:
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
This error occurs sometimes when you are using MongoDB Atlas and lost your internet connectivity. You will not be able to access your database.
Make sure to change the node version to 2.2.12:
And add IP address:
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));
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.
In our case antivirus/firewall is blocking,
Try to disable antivirus/firewall and check again. hope it will work.
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.
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 )
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.
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.
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.
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;
"Not in the root folder" scenario:
Create a .env file in the root directory of your project. https://github.com/motdotla/dotenv
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:
Solution
The first step to solve this issue is to console.log(url) and check if process.env returns the correct Connection String.
Related:
dotenv github readme: https://github.com/motdotla/dotenv#readme
Connect to a MongoDB Database Using Node.js
: https://developer.mongodb.com/quickstart/node-connect-mongodb/
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.

Atlas MongoDB connection

I am trying to connect to Atlas MongoDB with the following URI (provided by mongodb connection string )
module.exports = {
mongoURI:'mongodb+srv://<user>:<password>#cluster0-un6sk.mongodb.net/test?
retryWrites=true'
};
//connect to mongoose
mongoose
.connect(db)
.then( ()=>console.log('mongoDB connected'))
.catch(err => console.log(err));
I get the following error :
{ MongoNetworkError: connection 3 to cluster0-shard-00-00-un6sk.mongodb.net:27017 closed
at TLSSocket.<anonymous> (C:\Users\KARTIT Ismail\Desktop\devconnector\node_modules\mongodb-core\lib\connection\connection.js:352:9)
at Object.onceWrapper (events.js:273:13)
at TLSSocket.emit (events.js:182:13)
at _handle.close (net.js:606:12)
at TCP.done (_tls_wrap.js:386:7)
name: 'MongoNetworkError',
errorLabels: [ 'TransientTransactionError' ],
[Symbol(mongoErrorContextSymbol)]: {} }
Make sure you have whitelisted your IP in the Atlas Control panel.
You can enter 0.0.0.0, if you wish to allow access from any host.
Then you can have a connection string like below:
var connectionString= 'mongodb://<username>:<password>#<clustername>/<dbname>?ssl=true&replicaSet=<replica setname>&authSource=admin';
var db = mongoose.connect(connectionString).catch((error) => { console.log(error); });
Whitelist the IP address, the best option allows access from any host, I believe everyone had installed mongoose, if not then use this command
npm i mongoose
First copy your application connection string from mongodb.com -> clusters->connect->connect your application
Now chose driver Node.js and version latest, now copy connection string.
Now connection.js
const mongoose = require('mongoose');
const conStr = 'mongodb+srv://lord:<password>#cluster5-eeev8.mongodb.net/test?retryWrites=true&w=majority'
const DB = conStr.replace(
'<password>',
myPass
);
const DB = conStr.replace(
'test',
myDatabaseName
);
//remember mongoose.connect() return promise
mongoose
.connect(DB, {
usedNewUrlParser: true,
useCreateIndex: true,
useFindAndModify: false,
})
.then((con) => {
console.log(con.connection);
console.log('DB connection successful');
});
In order to connect to Atlas MongoDB you should configure IP whitelist. Go to MongoDB Atlas website, login. Then, from the Clusters view, select the Security tab, then IP Whitelist. You will see an IP address. Click "Edit" Button then "current IP address". Press OK. Then restart your server.
Useful link : https://docs.atlas.mongodb.com/security-whitelist/#add-whitelist-entries
What version of mongoose are you using? Versions of mongoose less than version 5.0.15 doesn't appear to support the mongodb+srv:// server url.
The other common issue, is white listed IP addresses.
Source:
Error at connecting to MongoDb Atlas Server
Just whitelist the IP from the Atlas UI no need to restart the application.

Resources