Unhandled Promise Rejection Warning: Mongoose Server Selection Error

Viewed 1318

UnhandledPromiseRejectionWarning: MongooseServerSelectionError Bug?*

What is the current behavior?

  • hello there I am trying to connect mongoose with URL string included everything is fine but after console.log("mongoDB database connection established successfully") this is not showing this console's text but an error is coming there Screenshot from 2021-02-03 14-54-33
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,useUnifiedTopology:true} 
   // ); // update the code provided below

mongoose
     .connect( uri, { useNewUrlParser: true, useCreateIndex: true, useUnifiedTopology: true })
     .then(() => console.log( 'Database Connected' ))
     .catch(err => console.log( err ));

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

server.js file code above and in .env the URI key is given

What is the expected behavior?

  • the expected output is MongoDB database connection established successfully.

What are the versions of Node.js, Mongoose, and MongoDB you are using? Note that "latest" is not a version.

  • "cors": "^2.8.5", "dotenv": "^8.2.0", "express": "^4.17.1", "mongoose": "^5.11.14",
2 Answers

First of all, check the port status in Firewall, is it open. Then you can actually in your Mongo Atlas add the whitelist ip address. Also, the mongoose.connection is a promise which needs to be altered like this:

mongoose
     .connect( uri, { useNewUrlParser: true, useCreateIndex: true, useUnifiedTopology: true })
     .then(() => console.log( 'Database Connected' ))
     .catch(err => console.log( err ));

If error still continues, you can follow the below steps.

Make sure your application can reach your MongoDB Atlas environment. To add the inbound network access from your application environment to Atlas, do one of the following:

  1. Add the public IP addresses to your IP access list
  2. Use VPC / VNet peering to add private IP addresses. TIP See also: IP Access List

If your firewall blocks outbound network connections, you must also open outbound access from your application environment to Atlas. You must configure your firewall to allow your applications to make outbound connections to ports 27015 to 27017 to TCP traffic on Atlas hosts. This grants your applications access to databases stored on Atlas.

For more details you can check this.

Also, you should change this to connect with mongoose:

After spending a lot of time finding solution, when I tried changing localhost to 127.0.0.1 in my connection string, it simply worked.

Related