简体   繁体   中英

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.

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
在此处输入图片说明

2. Edit the current user and modify the password 在此处输入图片说明

3. Use that password to connect to MongoDB Atlas
在此处输入图片说明

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM