Cant connect to MongoDB

Im following this tutorial: https://www.youtube.com/watch?v=7CqJlxBYj-M

When I try to test connection to MongoDB using Mongoose:

I get the following error:

[nodemon] restarting due to changes...
[nodemon] starting `node server.js`
Server is running on port: 5000
(node:12972) UnhandledPromiseRejectionWarning: MongoNetworkError: failed to connect to server [cluster0-shard-00-00-knpdv.mongodb.net:27017] on first connect [MongoNetworkError: read ECONNRESET]
    at Pool.<anonymous> (C:\Users\ksethi014\projects\mernexercisetracker\backend\node_modules\mongodb-core\lib\topologies\server.js:431:11)
    at Pool.emit (events.js:198:13)
    at connect (C:\Users\ksethi014\projects\mernexercisetracker\backend\node_modules\mongodb-core\lib\connection\pool.js:557:14)    at callback (C:\Users\ksethi014\projects\mernexercisetracker\backend\node_modules\mongodb-core\lib\connection\connect.js:109:5)
    at runCommand (C:\Users\ksethi014\projects\mernexercisetracker\backend\node_modules\mongodb-core\lib\connection\connect.js:129:7)
    at Connection.errorHandler (C:\Users\ksethi014\projects\mernexercisetracker\backend\node_modules\mongodb-core\lib\connection\connect.js:321:5)
    at Object.onceWrapper (events.js:286:20)
    at Connection.emit (events.js:198:13)
    at TLSSocket.<anonymous> (C:\Users\ksethi014\projects\mernexercisetracker\backend\node_modules\mongodb-core\lib\connection\connection.js:321:10)
    at Object.onceWrapper (events.js:286:20)
    at TLSSocket.emit (events.js:198:13)
    at emitErrorNT (internal/streams/destroy.js:91:8)
    at emitErrorAndCloseNT (internal/streams/destroy.js:59:3)
    at process._tickCallback (internal/process/next_tick.js:63:19)
(node:12972) 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(). (rejection id: 1)
(node:12972) [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.

My server.js file looks like this

const express = require('express');

const cors = require('cors');

const mongoose = require('mongoose');

require('dotenv').config();

const app = express();

const port = process.env.PORT || 5000;

app.use(cors());

app.use(express.json());

const uri = process.env.ATLAS_URI;

console.log(uri)

mongoose.connect(uri, { useNewUrlParser: true, useCreateIndex: true }

);

const connection = mongoose.connection;

connection.once('open', () => {

console.log("MongoDB database connection established successfully");

})

app.listen(port, () => {

console.log(`Server is running on port: ${port}`);

});

I have downloaded all the required dependencies and all IPs are whitelisted and have removed < > from the password in connection string.

Welcome to freecodecamp forum @ksethi2211! :grinning:

Since everything seemed correct i tried to use your code to connect and it worked without a flaw^^

Most likely there’s something wrong with the atlas uri: you created your own cluster right? Did you also replaced the username:password with your actual username and password ( not only removing the angular brackets)?

yup i did that @Layer . can u check with this once:

ATLAS_URI=mongodb+srv://ksethi2211:qwerty123@cluster0-knpdv.mongodb.net/test?retryWrites=true&w=majority

Try this one:

ATLAS_URI=mongodb+srv://ksethi2211:qwerty123@cluster0-knpdv.mongodb.net/test

nope same problem occurs::sob:


(node:16820) UnhandledPromiseRejectionWarning: MongoNetworkError: failed to connect to server [cluster0-shard-00-00-knpdv.mongodb.net:27017] on first connect [MongoNetworkError: read ECONNRESET]
    at Pool.<anonymous> (C:\Users\ksethi014\projects\mernexercisetracker\backend\node_modules\mongodb-core\lib\topologies\server.js:431:11)
    at Pool.emit (events.js:198:13)
    at connect (C:\Users\ksethi014\projects\mernexercisetracker\backend\node_modules\mongodb-core\lib\connection\pool.js:557:14)
    at callback (C:\Users\ksethi014\projects\mernexercisetracker\backend\node_modules\mongodb-core\lib\connection\connect.js:109:5)
    at runCommand (C:\Users\ksethi014\projects\mernexercisetracker\backend\node_modules\mongodb-core\lib\connection\connect.js:129:7)    at Connection.errorHandler (C:\Users\ksethi014\projects\mernexercisetracker\backend\node_modules\mongodb-core\lib\connection\connect.js:321:5)
    at Object.onceWrapper (events.js:286:20)
    at Connection.emit (events.js:198:13)
    at TLSSocket.<anonymous> (C:\Users\ksethi014\projects\mernexercisetracker\backend\node_modules\mongodb-core\lib\connection\connection.js:321:10)
    at Object.onceWrapper (events.js:286:20)
    at TLSSocket.emit (events.js:198:13)
    at emitErrorNT (internal/streams/destroy.js:91:8)
    at emitErrorAndCloseNT (internal/streams/destroy.js:59:3)
    at process._tickCallback (internal/process/next_tick.js:63:19)
(node:16820) 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(). (rejection id: 1)
(node:16820) [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.

Have you whitelisted your IP in from the Atlas dashboard?
Either you can whitelist your own ip, or temporarily allow access to every IPs like so:

1 Like

yaa for now everyone has access to the project.

i had entered 0.0.0.0/0 before only. Can u access the project using your console and the above code?

Just tested this on glich, and it’s working.
You can fork it from here: https://glitch.com/edit/#!/remix/few-question

i dont know it still shows the same error for me. it might be a issue with my system.

can u check with this once: […]

Just tested this on glich, and it’s working.

Yeah, it worked on my side too :confused: ( now change your password asap :stuck_out_tongue: )

On the .env file there is no need of quotes around the strings (just a random source of error). Do uri prints correctly when you run the file?

Did you ever find a fix for this? I’ve got the same issue, enabled all IPs, nothing.

I ran into the same problem too. I went ahead and looked up Mongodb ATLAS and I used this instead:

const MongoClient = require('mongodb').MongoClient;
const uri = "mongodb+srv://kay:myRealPassword@cluster0.mongodb.net/test?w=majority";
const client = new MongoClient(uri, { useNewUrlParser: true });
client.connect(err => {
  const collection = client.db("test").collection("devices");
 // perform actions on the collection object
  client.close();
});

I finally got it to connect. I know you will be able to see the password but I will put that into an env file later. I hope this helps.

looks good but didnt work for me

why to write 0.0.0.0/0 ?

I had same issue, but it works now ! What I had done which I changed connection string with originally from Atlas and change white IP to 0.0.0.0/0

this is my connection string:

// Database Connection
const MongoClient = require('mongodb').MongoClient;
const uri = "mongodb+srv://<user>:<password>@bumimakh1-awitx.mongodb.net/test?retryWrites=true&w=majority";
const client = new MongoClient(uri, { 
    useNewUrlParser: true,
    useUnifiedTopology: true 
});
console.log('Connected to Atlas');
client.connect(err => {
  const collection = client.db("test").collection("devices");
  // perform actions on the collection object
  client.close();
});

I hope this help

2 Likes

It worked for me, thanks a lot

1 Like

Thanks a lot,
It worked for me.

Enter “Network Access” in the MongoDB Dashboard, change the Database User Pass and try again.

I am having a similar problem. Here is my code for server.js

const express = require("express");
const cors = require("cors");
const mongoose = require("mongoose");

require("dotenv").config();

const app = express();
const port = process.env.PORT || 5000;

app.use(cors());
app.use(express.json());

const uri = process.env.ATLAS_URI;
mongoose.connect(uri, { useNewUrlParser: true, useCreateIndex: true });
const connection = mongoose.connection;
connection.once("open", () => {
  console.log("MongoDB database connection established successfully!");
});

app.listen(port, () => {
  console.log(`Server is running on port: ${port}`);
});

My terminal says:
TypeError: connection.once is not a function
at Object. (C:\Users\Lisa\Desktop\exercise-tracker\mern-exercise-tracker\backend\server.js:16:12)

I think my other problem is this:
In my .env file, I have pasted the ATLAS_URI= connection string from my mongodb Atlas file and it still isn’t working. I did not yet change the – I can’t figure out what the name should be! Can anyone help?

1 Like