5

I am seeing similar posts, however none are helping me solve my problem.

Following a Udemy tutorial that builds a MERN application from scratch, I got stuck on the mongoose connection.

Here is my index.js code:

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

const app = express();

app.use(express.json());

app.listen(5000, () => console.log("Server started on port 5000"));

app.use("/snippet", require("./routers/snippetRouter"));

mongoose.connect("mongodb+srv://snippetUser:_password_@
  snippet-manager.sometext.mongodb.net/main?retryWrites=
  true&w=majority", {
    useNewUrlParser: true,
    useUnifiedTopology: true
}, (err) => {
  if (err) return console.log("error here " + err);
  console.log("Connected to MongoDB");
});

Here is the error I am getting:

Server started on port 5000
error here MongooseServerSelectionError: Could not connect to any 
servers in your MongoDB Atlas cluster. One common reason is 
that you're trying to access the database from an IP that isn't 
whitelisted. Make sure your current IP address is on your Atlas 
cluster's IP whitelist:
https://docs.atlas.mongodb.com/security-whitelist/ 

As stated, I am seeing similar errors relating to an IP that isn't whitelisted.

However, in my mongoDB account, it seems that my IP is already whitelisted:

enter image description here

In the screenshot above, the blank part is where my IP is located (right before it says "includes your current IP address").

Since my IP is listed there, does that not mean my IP is whitelisted?

If not, how do I whitelist my IP?

John Beasley
  • 2,577
  • 9
  • 43
  • 89

6 Answers6

7

After a couple of days of frustration, I went into Mongo Atlas, then into Network Access and changed the setting to "allow access from anywhere" (shown as 0.0.0.0/0 below). It removed my IP address and changed it to a wildcard IP address.

enter image description here

This was a deviation from the tutorial I am following on Udemy, but it did work, and I can finally proceed with the rest of the course.

mikemaccana
  • 110,530
  • 99
  • 389
  • 494
John Beasley
  • 2,577
  • 9
  • 43
  • 89
2

here is an answer i left elsewhere. hope it helps someone who comes across this:

this script will be kept up to date on my gist

why

mongo atlas provides a reasonably priced access to a managed mongo DB. CSPs where containers are hosted charge too much for their managed mongo DB. they all suggest setting an insecure CIDR (0.0.0.0/0) to allow the container to access the cluster. this is obviously ridiculous.

this entrypoint script is surgical to maintain least privileged access. only the current hosted IP address of the service is whitelisted.

usage

  • set as the entrypoint for the Dockerfile
  • run in cloud init / VM startup if not using a container (and delete the last line exec "$@" since that is just for containers

behavior

uses the mongo atlas project IP access list endpoints

  • will detect the hosted IP address of the container and whitelist it with the cluster using the mongo atlas API
  • if the service has no whitelist entry it is created
  • if the service has an existing whitelist entry that matches current IP no change
  • if the service IP has changed the old entry is deleted and new one is created

when a whitelist entry is created the service sleeps for 60s to wait for atlas to propagate access to the cluster

env

setup

  1. create API key for org
  2. add API key to project
  3. copy the public key (MONGO_ATLAS_API_PK) and secret key (MONGO_ATLAS_API_SK)
  4. go to project settings page and copy the project ID (MONGO_ATLAS_API_PROJECT_ID)

provide the following values in the env of the container service

  • SERVICE_NAME: unique name used for creating / updating (deleting old) whitelist entry
  • MONGO_ATLAS_API_PK: step 3
  • MONGO_ATLAS_API_SK: step 3
  • MONGO_ATLAS_API_PROJECT_ID: step 4

deps

# alpine / apk
apk update \
  && apk add --no-cache \
     bash \
     curl \
     jq
     
# ubuntu / apt
export DEBIAN_FRONTEND=noninteractive \
  && apt-get update  \
  && apt-get -y install \
     bash \
     curl \
     jq

script

#!/usr/bin/env bash

# -- ENV -- #
# these must be available to the container service at runtime
#
# SERVICE_NAME
#
# MONGO_ATLAS_API_PK
# MONGO_ATLAS_API_SK
# MONGO_ATLAS_API_PROJECT_ID
#
# -- ENV -- #

set -e

mongo_api_base_url='https://cloud.mongodb.com/api/atlas/v1.0'

check_for_deps() {
  deps=(
    bash
    curl
    jq
  )

 for dep in "${deps[@]}"; do
   if [ ! "$(command -v $dep)" ]
   then
    echo "dependency [$dep] not found. exiting"
    exit 1
   fi
 done
}

make_mongo_api_request() {
  local request_method="$1"
  local request_url="$2"
  local data="$3"

  curl -s \
    --user "$MONGO_ATLAS_API_PK:$MONGO_ATLAS_API_SK" --digest \
    --header "Accept: application/json" \
    --header "Content-Type: application/json" \
    --request "$request_method" "$request_url" \
    --data "$data"
}

get_access_list_endpoint() {
  echo -n "$mongo_api_base_url/groups/$MONGO_ATLAS_API_PROJECT_ID/accessList"
}

get_service_ip() {
  echo -n "$(curl https://ipinfo.io/ip -s)"
}

get_previous_service_ip() {
  local access_list_endpoint=`get_access_list_endpoint`

  local previous_ip=`make_mongo_api_request 'GET' "$access_list_endpoint" \
                    | jq --arg SERVICE_NAME "$SERVICE_NAME" -r \
                    '.results[]? as $results | $results.comment | if test("\\[\($SERVICE_NAME)\\]") then $results.ipAddress else empty end'`

  echo "$previous_ip"
}

whitelist_service_ip() {
  local current_service_ip="$1"
  local comment="Hosted IP of [$SERVICE_NAME] [set@$(date +%s)]"

  if (( "${#comment}" > 80 )); then
    echo "comment field value will be above 80 char limit: \"$comment\""
    echo "comment would be too long due to length of service name [$SERVICE_NAME] [${#SERVICE_NAME}]"
    echo "change comment format or service name then retry. exiting to avoid mongo API failure"
    exit 1
  fi
  
  echo "whitelisting service IP [$current_service_ip] with comment value: \"$comment\""

  response=`make_mongo_api_request \
            'POST' \
            "$(get_access_list_endpoint)?pretty=true" \
            "[
              {
                \"comment\" : \"$comment\",
                \"ipAddress\": \"$current_service_ip\"
              }
            ]" \
            | jq -r 'if .error then . else empty end'`

  if [[ -n "$response" ]];
  then
    echo 'API error whitelisting service'
    echo "$response"
    exit 1
  else
    echo "whitelist request successful"
    echo "waiting 60s for whitelist to propagate to cluster"
    sleep 60s
  fi 
}

delete_previous_service_ip() {
  local previous_service_ip="$1"

  echo "deleting previous service IP address of [$SERVICE_NAME]"

  make_mongo_api_request \
    'DELETE' \
    "$(get_access_list_endpoint)/$previous_service_ip"
}

set_mongo_whitelist_for_service_ip() {
  local current_service_ip=`get_service_ip`
  local previous_service_ip=`get_previous_service_ip`

  if [[ -z "$previous_service_ip" ]]; then
    echo "service [$SERVICE_NAME] has not yet been whitelisted"

    whitelist_service_ip "$current_service_ip"
  elif [[ "$current_service_ip" == "$previous_service_ip" ]]; then
    echo "service [$SERVICE_NAME] IP has not changed"
  else  
    echo "service [$SERVICE_NAME] IP has changed from [$previous_service_ip] to [$current_service_ip]"

    delete_previous_service_ip "$previous_service_ip"
    whitelist_service_ip "$current_service_ip"
  fi
}

check_for_deps
set_mongo_whitelist_for_service_ip

# run CMD
exec "$@"
vampiire
  • 1,111
  • 2
  • 15
  • 27
0

Make sure your cluster hasn't been accidentally put on pause if you're using free MongoDB Atlas enter image description here

Tyler2P
  • 2,324
  • 26
  • 22
  • 31
0

remove your current IP address and add it again

  • While this link may answer the question, it is better to include the essential parts of the answer here and provide the link for reference. Link-only answers can become invalid if the linked page changes. - [From Review](/review/late-answers/33760323) – Hardik Shah Feb 06 '23 at 11:56
  • if if your system has dynamic ip address, whitelist ip address valid only for day, check for dynamic ip address ipconfig/all https://www.mongodb.com/docs/atlas/security/ip-access-list/ – Pankaj Singh Feb 07 '23 at 06:10
0

Go to your account of MongoDB Atlas

After Login go to the below URL https://cloud.mongodb.com/v2/your_cluster_id#/security/network/accessList

Then add the IP in the IP Access List Tab

Then Click + Add IP ADDRESS

So you can access the DB from that particular IP.

==================== OR =============================

Go to Network Access

Then add the IP in the IP Access List Tab

Then Click + Add IP ADDRESS

So you can access the DB from that particular IP.

Kartik Chandra
  • 390
  • 4
  • 9
0

you should enter your cluster password in connection link--

mongodb+srv://snippetUser:_password_@
snippet-manager.sometext.mongodb.net/main?retryWrites=true&w=majority

enter your cluster password by removing password field

Tyler2P
  • 2,324
  • 26
  • 22
  • 31
RICK KAR
  • 1
  • 1