krishna kakade
krishna kakade

Reputation: 479

Unhandled Promise Rejection Warning: Mongoose Server Selection Error

UnhandledPromiseRejectionWarning: MongooseServerSelectionError Bug?*

What is the current behavior?

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?

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

Upvotes: 3

Views: 2169

Answers (3)

ash101
ash101

Reputation: 1

Add your IP address in the network access since mongo server has a list of IP addresses who can access the database.

Upvotes: 0

Zeeshan
Zeeshan

Reputation: 3024

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.

Upvotes: 1

Apoorva Chikara
Apoorva Chikara

Reputation: 8773

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:

Upvotes: 1

Related Questions