Setting Up a MongoDB Database

What Is MongoDB?

MongoDB is a database: a separate program whose only job is to store data and hand it back when asked. Our Node server will talk to it. Instead of reading and rewriting a JSON file, our server asks MongoDB to add, find, change, or delete things, and MongoDB keeps them safe even when our server stops, restarts, or gets redeployed on Render.

MongoDB Atlas is MongoDB's hosting service. It runs a MongoDB database for you on their computers, all day, so you don't have to install anything. It has a free tier, and that's all we'll use in this class.

You should not spend any money on Atlas. Always pick the Free cluster, and don't add a credit card or any payment method. If a screen asks you to pay, you picked the wrong option: go back.

A Few Words First

Word What it means
Cluster The MongoDB server Atlas runs for you. You get one free one.
Database A named group of collections, like csc336. One cluster can hold many.
Collection A named list of documents, like todos. Similar to an array.
Document One item in a collection. It's just a JavaScript object, like { text: "buy milk" }.
Connection string A long URL that tells your server where your cluster is, and includes your database username and password.

Step 1: Make an Atlas Account

  1. Go to mongodb.com/cloud/atlas/register.
  2. Sign up with Google, GitHub, or an email address. Any of them works.
  3. Atlas may ask some welcome questions (what you're building, what language you use). Answer them however you like, or skip them. They don't change anything.

Step 2: Create a Free Cluster

  1. After signing up, Atlas usually takes you straight to creating a cluster. If it doesn't, click Create (or Build a Cluster) on the main page.
  2. Pick the Free option. You'll see a few choices. Older guides call the free one M0. Don't pick Flex or anything with a price.
  3. Fill in the rest:
    Field What to put
    Name Leave it as Cluster0. You can't rename a cluster later.
    Provider Anything (AWS is fine)
    Region One close to you, like us-east-1 (N. Virginia)
  4. Click the button to create it. It takes a minute or two to finish setting up.

Step 3: Create a Database User

This is not your Atlas login. It's a separate username and password that your server uses to get into the database.

  1. Atlas should pop up a security screen asking you to create a database user. (If it doesn't, click Connect on your cluster, and it will ask you there.)
  2. Type a username and a password. Use only letters and numbers in the password. Symbols like @, /, or : have special meanings in a URL and will break your connection string.
  3. Copy the password somewhere now. Atlas won't show it to you again. If you lose it, you'll have to make a new one.
  4. Click Create Database User.

Step 4: Allow Your Computer to Connect

Atlas blocks every computer from connecting unless it's on your IP Access List. An IP address is a number that identifies a computer on the internet.

  1. On the same security screen, click Add Your Current IP Address. That lets your laptop in.
  2. For Render (and to save yourself headaches): also add 0.0.0.0/0. This means "allow any IP address." Render's servers don't have one fixed IP address, and your laptop's IP changes when you switch Wi-Fi networks (home, campus, a coffee shop), so without this your server will suddenly stop connecting. Your database is still protected by the username and password from Step 3.
  3. Click Finish and Close.

Step 5: Get Your Connection String

  1. Go to your cluster (left sidebar, Clusters) and click Connect.
  2. Choose Drivers, then pick Node.js from the dropdown.
  3. Copy the connection string. It looks like this:
    mongodb+srv://yourusername:<db_password>@cluster0.abc123.mongodb.net/?retryWrites=true&w=majority&appName=Cluster0
  4. Replace <db_password> with the password from Step 3. Delete the < and > too. (Some versions say <password> instead. Same idea.) For example, if your password is abc123:
    mongodb+srv://yourusername:abc123@cluster0.abc123.mongodb.net/?retryWrites=true&w=majority&appName=Cluster0
  5. Ignore the example code Atlas shows under the string. We'll write our own.
Your connection string is a secret. Anyone who has it can read, change, or delete everything in your database. Treat it like the Gemini API key: it goes in .env, never in your code, and never on GitHub.

Step 6: Make the Project

  1. Make a folder
    In VS Code, open your csc336-fall2026 folder. Make a new folder inside it called mongo-test.
  2. Make package.json inside mongo-test:
    {
      "name": "mongo-test",
      "type": "module"
    }
  3. Install the packages
    In the terminal:
    cd mongo-test
    npm install express mongodb dotenv
    express is our server, mongodb is the official package for talking to MongoDB from Node, and dotenv loads our .env file.
  4. Make .gitignore inside mongo-test, so the secret and the downloaded packages never get pushed:
    node_modules
    .env
  5. Make .env inside mongo-test. Put your connection string from Step 5 after MONGODB_URI=, all on one line, with no spaces or quotes:
    MONGODB_URI=mongodb+srv://yourusername:abc123@cluster0.abc123.mongodb.net/?retryWrites=true&w=majority&appName=Cluster0

Step 7: Write the Server

This server stores a to-do list. It has four routes, one for each thing you can do with data: list it, add to it, change it, and delete from it. People call these four things CRUD (Create, Read, Update, Delete).

Route What it does MongoDB function
GET /api/todos List every to-do find
POST /api/todos Add a to-do insertOne
PUT /api/todos/:id Change one to-do updateOne
DELETE /api/todos/:id Delete one to-do deleteOne

Make server.js inside mongo-test:

import "dotenv/config";
import express from "express";
import { MongoClient, ObjectId } from "mongodb";

let app = express();
let port = process.env.PORT || 3000;

app.use(express.json());

// The connection string has our password in it, so it lives in .env
let client = new MongoClient(process.env.MONGODB_URI);
await client.connect();
console.log("Connected to MongoDB");

// A database holds collections. A collection holds documents (just objects).
// Neither has to exist yet: Mongo creates them the first time we insert.
let database = client.db("csc336");
let todos = database.collection("todos");


// LIST: GET /api/todos
app.get("/api/todos", async (req, res) => {
    // {} is a filter that matches every document.
    // find() gives back a "cursor"; toArray() turns it into a normal array.
    let cursor = todos.find({});
    let allTodos = await cursor.toArray();
    res.json(allTodos);
});


// ADD: POST /api/todos   with a body like { "text": "buy milk" }
app.post("/api/todos", async (req, res) => {
    let newTodo = {
        text: req.body.text
    };

    // Mongo gives every new document a unique _id
    await todos.insertOne(newTodo);

    let cursor = todos.find({});
    let allTodos = await cursor.toArray();
    res.json(allTodos);
});


// MODIFY: PUT /api/todos/<id>   with a body like { "text": "buy oat milk" }
// :id in the path means "whatever is here, call it id". Express puts it in req.params.id
app.put("/api/todos/:id", async (req, res) => {
    // _id is stored as an ObjectId, not a plain string, so we convert it
    let id = new ObjectId(req.params.id);

    // First object: which document. Second object: what to change.
    // $set means "change just these fields, leave the rest alone"
    await todos.updateOne({ _id: id }, { $set: { text: req.body.text } });

    let cursor = todos.find({});
    let allTodos = await cursor.toArray();
    res.json(allTodos);
});


// DELETE: DELETE /api/todos/<id>
app.delete("/api/todos/:id", async (req, res) => {
    let id = new ObjectId(req.params.id);

    await todos.deleteOne({ _id: id });

    let cursor = todos.find({});
    let allTodos = await cursor.toArray();
    res.json(allTodos);
});


app.listen(port, () => {
    console.log("Server running at http://localhost:" + port);
});

A few things to notice:

Step 8: Run It and Try It

  1. In the terminal (inside mongo-test):
    node server.js
    You should see Connected to MongoDB and then Server running at http://localhost:3000. If it crashes instead, see If Something Goes Wrong.
  2. Visit http://localhost:3000/api/todos. You should see []: an empty list, because there's nothing in the database yet.
  3. Add a to-do. We don't have a front end, so we'll send requests from the browser console. On that same page, open the console and paste:
    let r = await fetch("/api/todos", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ text: "buy milk" })
    });
    await r.json();
    You'll get back a list with one to-do in it. Notice the _id: MongoDB made that up. Refresh the page and it's there too.
  4. Change it. Copy the _id (just the letters and numbers inside the quotes) and paste it in place of PASTE_ID:
    r = await fetch("/api/todos/PASTE_ID", {
        method: "PUT",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ text: "buy oat milk" })
    });
    await r.json();
  5. Delete it:
    r = await fetch("/api/todos/PASTE_ID", { method: "DELETE" });
    await r.json();
  6. See that it sticks. Add a couple more to-dos. Then stop the server with Ctrl+C, start it again, and refresh /api/todos. Your to-dos are still there. They aren't in your server at all: they're in Atlas.
  7. Look at it in Atlas. In Atlas, go to your cluster and click Browse Collections (or Data Explorer). You'll see a csc336 database with a todos collection inside it, holding the same documents. You can even edit or delete them right there.

Putting It on Render

Follow the Render setup instructions like usual, with mongo-test as the Root Directory. Two extra things:

  1. Add your connection string to Render. Your .env file isn't on GitHub (that's the point), so Render doesn't have it. In your service's page, click Environment, add a variable named MONGODB_URI, and paste the same connection string as the value. Save, then redeploy.
  2. Make sure 0.0.0.0/0 is in your Atlas Network Access list (see Step 4). Otherwise Atlas won't let Render's servers in.

Now your local server and your Render server both use the same database. Add a to-do on one and you'll see it on the other.

Things to Know About the Free Tier

If Something Goes Wrong

Most problems happen at await client.connect(), before the server even starts.

You see It probably means
bad auth or Authentication failed Wrong username or password in your connection string. Did you replace <db_password>, and remove the < >? Is it the database user's password (Step 3), not your Atlas login?
It hangs for about 30 seconds, then a Server selection timed out error Your IP isn't allowed. Check Network Access in Atlas (Step 4). This often happens after switching Wi-Fi networks.
The "url" argument must be of type string. Received undefined process.env.MONGODB_URI is empty. Is .env inside mongo-test (not somewhere else)? Is it spelled MONGODB_URI exactly? Are you running node server.js from inside mongo-test?
Invalid scheme The connection string is mangled. It must start with mongodb+srv://. Check for extra quotes or spaces in .env.
Cannot find package 'mongodb' You didn't run npm install (or ran it in a different folder)
A 500 error when changing or deleting The id in the URL isn't a real _id. Copy it again from /api/todos.
Works on your computer, crashes on Render You forgot MONGODB_URI in Render's Environment tab, or 0.0.0.0/0 isn't in Network Access
Connection string shows up on GitHub Your .env got pushed. In Atlas, change that database user's password right away (Database Access), then fix your .gitignore.