6

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?

8
  • Is main actually the name of your database or is that also a placeholder?
    – codemonkey
    Commented Jan 29, 2021 at 4:00
  • @codemonkey - You have me doubting myself. I'm looking for the actual name now. Commented Jan 29, 2021 at 4:14
  • @codemonkey - I cannot seem to locate the actual db name. I'm pretty sure it's "main" though. Commented Jan 29, 2021 at 4:18
  • On the clusters page, click "COLLECTIONS". It will show you the DB name above your collections in the column on the left hand side. You need that DB name to connect.
    – codemonkey
    Commented Jan 29, 2021 at 4:29
  • @codemonkey, It reads "DATABASES:0 COLLECTIONS: 0" . I guess "main" was just a placeholder. Commented Jan 29, 2021 at 4:39

7 Answers 7

9

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.

1
  • 2
    hey man this is one solution but it is not secure. see my answer for how to do this securely
    – vampiire
    Commented Mar 4, 2022 at 18:59
3

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 "$@"
0

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

0

remove your current IP address and add it again

2
  • 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 Commented Feb 6, 2023 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 mongodb.com/docs/atlas/security/ip-access-list Commented Feb 7, 2023 at 6: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.

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

0

Solved. In my case, Im deplying NextJS v14.0.2. Downgrading packages mongoose 8.3.4 → 8.1.0 mongodb 6.10.0 → 6.3.0 Solved the issue. NodeJS 12.13.0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.