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.
| 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. |
| 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) |
This is not your Atlas login. It's a separate username and password that your server uses to get into the database.
@, /, or : have special
meanings in a URL and will break your connection string.
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.
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.
0.0.0.0/0 into the box yourself.
Click Confirm.
mongodb+srv://yourusername:<db_password>@cluster0.abc123.mongodb.net/?retryWrites=true&w=majority&appName=Cluster0
<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
.env, never
in your code, and never on GitHub.
csc336-fall2026 folder. Make a new folder inside it called
mongo-test.
package.json inside mongo-test:
{
"name": "mongo-test",
"type": "module"
}
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.
.gitignore inside mongo-test, so the secret and
the downloaded packages never get pushed:
node_modules
.env
.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
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:
async and each database call has await, just like
fetch.
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.
[]: an empty list, because there's nothing in the database yet.
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.
_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();
r = await fetch("/api/todos/PASTE_ID", { method: "DELETE" });
await r.json();
/api/todos. Your to-dos are
still there. They aren't in your server at all: they're in Atlas.
csc336
database with a todos collection inside it, holding the same documents. You can
even edit or delete them right there.
Follow the Render setup instructions like usual, with
mongo-test as the Root Directory. Two extra things:
.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.
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.
client.db("...") part) for each app instead.
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. |