AG_HIHI
AG_HIHI

Reputation: 1995

Cannot connect to mongoDB Atlas using mongoose : { MongoNetworkError: failed to connect to server }

Although I am not the first on Stackoverflow not to be able to connect to mongoDB atlas using mongoose, no one seems to have my specific error:

{ MongoNetworkError: failed to connect to server [cluster0-shard-00-00-shqnc.mongodb.net:27017] on first connect [MongoNetworkError: connection 5 to cluster0-shard-00-00-shqnc.mongodb.net:27017 closed]

Here's how my server is set-up:

Keys.js

module.exports = {
  mongoURI:
    "mongodb+srv://Ahmed:<MyMongoDBAtlasPWD>@cluster0-shqnc.mongodb.net/test?retryWrites=true&w=majority"
};  

Server.js

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

// DB Config
const db = require("./config/keys").mongoURI;

// Connect to MongoDB
mongoose
  .connect(db, {
    useNewUrlParser: true
  })
  .then(() => {
    console.log("MongoDB connected!");
  })
  .catch(err => {
    console.log(err);
  });

app.get("/", (req, res) => {
  res.send("Hello");
});

//process.env.Port is for Heroku
const port = process.env.Port || 5000;
// `` ES6 Template literal is used so that we can put a variable inside the String
app.listen(port, () => {
  console.log(`Server running on port ${port}`);
});  

And this is the code suggested by the MongoDB atlas website to be used:

const MongoClient = require('mongodb').MongoClient;
const uri = "mongodb+srv://Ahmed:<password>@cluster0-shqnc.mongodb.net/test?retryWrites=true&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();
});

But, since I don't want to use mongoClient but rather mongoose, I am having some trouble and I cannot see why the code doesn't work;

EDIT 1: I have managed to connect using the Shell command(Check-out my answer). However, connecting through the app doesn't work and gives a different error:

{ MongoNetworkError: failed to connect to server [cluster0-shard-00-01-shqnc.mongodb.net:27017] on first connect [MongoError: bad auth Authentication failed.]

EDIT 2: I made a stupid mistake. I've forgotten to remove <> from the . All is good now.

Upvotes: 3

Views: 2008

Answers (2)

AG_HIHI
AG_HIHI

Reputation: 1995

The problem is that I was trying to connect using my MongoDB Atlas account password instead of the user password. Yes, those are 2 different things.
1. Click on Database Access
enter image description here

2. Edit the current user and modify the password enter image description here

3. Use that password to connect to MongoDB Atlas
enter image description here

Upvotes: 3

Ashish Modi
Ashish Modi

Reputation: 7770

Make sure you have whitelisted your public IP. You can find that by googling "what is my ip".

Upvotes: 1

Related Questions