Skip to content

Instantly share code, notes, and snippets.

@acidtone
Last active July 26, 2022 21:38
Show Gist options
  • Save acidtone/534b025d6212a003a8a8ec3030a4d4ae to your computer and use it in GitHub Desktop.
Save acidtone/534b025d6212a003a8a8ec3030a4d4ae to your computer and use it in GitHub Desktop.
MongoDB Atlas: Deploying a collection to the cloud
PORT=3000
MONGODB_URL=mongodb+srv://<username>:<password>@cluster0<some-gibberish>.mongodb.net/myFirstDatabase?retryWrites=true&w=majority

MongoDB Atlas: Connecting to a MongoDB database in the cloud

We will not be installing MongoDB directly on our machines. Instead, we will be connecting to remote collections using the MongoDB Atlas cloud hosting platform.

1. Create a MongoDB Atlas account

  1. Create an free account with MongoDB Atlas. You will be prompted to set up your account (the Atlas interface will point you in the right direction):

  2. Screen 1: The basics

    • Organization: ABC Inc. (or whatever)
    • Project Name: Animals (or whatever)
    • Preferred Language: JavaScript (obvs)
  3. Screen 2: Choose a plan

    • Plan: Shared Clusters (Free, duh)
  4. Screen 3: Create a Shared Cluster

    • Cloud Provider: This doesn't really matter but Tony uses AWS.
    • Region: Tony uses Oregon (it's closest).

After you submit, it'll take awhile for the server to set up your Cluster.

When it's done:

2. Create a database user

Your Express app will need a login to access any databases you set up. You will need your login information later for your connection string.

  1. From the Atlas Admin panel, click Database Access (under "Security" on the left-hand side).
  2. Add New Database User
    • Authentication Method: Password
    • Username: something you'll remember.
    • Password: Do NOT use a password you use regularly; it's too easy to accidentally push it to a repo.
    • Database User Privileges: Read and write to any database (avoid Atlas admin unless you know you need it)

3. Whitelist your IP address

  1. Click Network Access (under Database Access)
  2. Add IP Address
  3. Allow Access from Anywhere
    • Caveat: This is inherently insecure but is good enough for class work. Do NOT add any sensitive information to any databases to this cluster; Tony will find it and profit off your hard work.

Optional: Load Sample Data

These are datasets that are more complex than we need for this course but they are a nice resource if you want to dip into heavier demo projects.

4. Create your Connection String

The Connection String holds all the information your application needs to connect to your database. This will be stored in your .env file (along with your PORT number).

  1. Click on Clusters (under "Data Storage" in the left-hand menu)

  2. Under Clusters, click Connect.

  3. Connect your application

  4. Copy the Connection String (starting with mongodb+srv://) into an .env file like so:

    PORT=3000
    MONGODB_URL=mongodb+srv://<username>:<password>@cluster0<some-gibberish>.mongodb.net/myFirstDatabase?retryWrites=true&w=majority
    • Your connection string will have real values, except for:
      • <password>. Paste your DB password (created in Step 2.2) here.
      • Change myFirstDatabase to myProject, favouriteThings or similar.
    • It's important that you use MONGODB_URL as a variable name; this is what Heroku uses to connect to Atlas (that's tomorrow).

5. Test your connection

  1. Clone or copy this gist into your workspace.

  2. Add your .env file (with the connection string you created above) to the root directory.

    • A sample document, .env-sample has been provided to get you started (don't forget to rename it to .env).
  3. Navigate to your root directory on the command line.

  4. Install dependencies:

    $ npm install
    
  5. Connect to your database:

    $ node server.js
    
    • Success: Connected to DB...

Troubleshooting Errors

  • The 'uri' parameter to 'openUri()' must be a string, got "undefined"
    • You probably don't have a .env file or it's not loading correctly.
  • The main error you will run into when connecting is Authentication Failed. Try the following:
    • Confirm you've set the correct username/password in your connection string. You can reset the password in the Atlas control panel.
    • Confirm you've changed the database in your connection string to myProject or similar.
    • Confirm you've whitelisted all IPs in Atlas.
{
"name": "hello-atlas",
"version": "1.0.0",
"description": "",
"main": "server.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "node server.js"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"dotenv": "^10.0.0",
"mongoose": "^6.0.12"
}
}
const mongoose = require('mongoose');
const dotenv = require('dotenv').config();
mongoose.connect(
process.env.MONGODB_URL,
{ useUnifiedTopology: true, useNewUrlParser: true },
)
.then(function(){
console.log('Connected to DB...')
})
.catch(function(err){
console.log(err)
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment