In Chapter 12: Databases SQL and NoSQL you learned why DevTinder uses MongoDB. Now you'll create a free MongoDB database in the cloud, look at it with a visual tool, and write Node.js code that creates, reads, updates and deletes data. This is the foundation for everything in Season 2.
In this chapter you'll learn
- how to create a free MongoDB Atlas cluster, a database user and network access
- what each part of a connection string means, and how to keep it secret
- how to browse your data with MongoDB Compass
- how to connect from Node.js with the official
mongodbdriver - the four CRUD operations, plus filtering, counting and
ObjectId
Before you start: read Chapter 12: Databases SQL and NoSQL. The example is in Code/db.js.
Part 1: Create a free cluster on MongoDB Atlas
MongoDB Atlas is MongoDB's cloud service: MongoDB runs on their servers, so you don't install anything. A cluster is a group of servers that together run your database (Atlas keeps copies of your data on several of them for safety).
Atlas renames its buttons and menus fairly often. If a label below doesn't match exactly, look for the closest one; the steps stay the same.
- Sign up at mongodb.com/atlas and log in.
- Create a cluster. Choose the free tier (called M0 / Free). Pick a cloud provider (AWS, Google Cloud or Azure) and a region close to you, so requests travel less distance. Creating it takes a few minutes.
- Create a database user. Under Database Access, add a user with a username and a strong password, and the role "Read and write to any database". This user is for your app, not your Atlas login.
- Allow network access. Under Network Access, add the IP addresses allowed to connect: your current IP for development (Atlas has a button for it). Later you'll add your server's IP (Chapter S3 02: Nginx and Backend Node App Development).
"Allow access from anywhere" (0.0.0.0/0) means anyone on the internet who knows or guesses your username and password can reach your database. It's acceptable for a quick experiment, but not for a real project. Allow only the IPs that need access.
Part 2: The connection string
Click Connect → Drivers on your cluster to get a connection string (also called a connection URI). It looks like this:
mongodb+srv://devUser:MyS3cretPass@cluster0.ab1cd.mongodb.net/devTinder?retryWrites=true&w=majoritymongodb+srv://devUser:MyS3cretPass@cluster0.ab1cd.mongodb.net/devTinder?retryWrites=true&w=majority| Part | Meaning |
|---|---|
mongodb+srv:// | the protocol. +srv means "look up the cluster's servers through DNS", so you don't list them yourself |
devUser:MyS3cretPass | the database user you created, and its password |
cluster0.ab1cd.mongodb.net | your cluster's address |
/devTinder | the database name to use (MongoDB creates it on the first write) |
?retryWrites=true&w=majority | options: retry failed writes once; confirm writes only after most servers have them |
If your password contains special characters like @, :, / or #, they break the URL. Either URL-encode them (@ becomes %40) or use a password without special characters.
Keep the connection string secret
The connection string is your database password. Anyone who has it can read and delete your data. Never paste it into code that goes to GitHub. Put it in an environment variable instead:
# .env (add ".env" to your .gitignore!)
MONGODB_URI=mongodb+srv://devUser:MyS3cretPass@cluster0.ab1cd.mongodb.net/devTinder# .env (add ".env" to your .gitignore!)
MONGODB_URI=mongodb+srv://devUser:MyS3cretPass@cluster0.ab1cd.mongodb.net/devTinder// Node.js 20.6+ can load .env itself: node --env-file=.env db.js
const uri = process.env.MONGODB_URI;// Node.js 20.6+ can load .env itself: node --env-file=.env db.js
const uri = process.env.MONGODB_URI;You'll use this pattern for every secret in Season 2 (Chapter S2 06: Database, Schema, Models & Mongoose).
Part 3: Look at your data with MongoDB Compass
MongoDB Compass is a free desktop app for browsing and editing MongoDB data visually.
- Download it from mongodb.com/products/tools/compass and install it.
- Paste your connection string and click Connect.
- Create a database (for example
devTinder) with a first collection (for exampleusers). - Click Add data → Insert document and type a JSON object. Notice that MongoDB adds an
_idautomatically.
Compass is great for checking what your code actually saved. Keep it open while you work.
Part 4: Connect from Node.js
Create a project folder and install the official driver:
npm init -y
npm pkg set type=module # adds "type": "module" to package.json, so .js files are ES Modules
npm install mongodbnpm init -y
npm pkg set type=module # adds "type": "module" to package.json, so .js files are ES Modules
npm install mongodb(npm init and package.json are explained in Chapter S2 03: Creating our Express server.)
// db.js
import { MongoClient, ObjectId } from "mongodb"; // CommonJS: const { MongoClient, ObjectId } = require("mongodb");
const client = new MongoClient(process.env.MONGODB_URI);
const dbName = "devTinder";
async function main() {
await client.connect(); // open the connection
console.log("Connected to MongoDB");
const db = client.db(dbName); // pick the database
const users = db.collection("users"); // pick the collection
// ...CRUD operations go here (Part 5)...
}
main()
.catch(console.error)
.finally(() => client.close()); // close when the script is done// db.js
import { MongoClient, ObjectId } from "mongodb"; // CommonJS: const { MongoClient, ObjectId } = require("mongodb");
const client = new MongoClient(process.env.MONGODB_URI);
const dbName = "devTinder";
async function main() {
await client.connect(); // open the connection
console.log("Connected to MongoDB");
const db = client.db(dbName); // pick the database
const users = db.collection("users"); // pick the collection
// ...CRUD operations go here (Part 5)...
}
main()
.catch(console.error)
.finally(() => client.close()); // close when the script is doneRun it with node --env-file=.env db.js.
- Every database operation is asynchronous (it travels over the network), so each one returns a Promise you
await. client.connect()opens a pool of connections that later operations reuse.- In a script like this, you close the client at the end so Node.js can exit (an open connection keeps the event loop alive: Chapter 09: libuv & event loop). In a server, you connect once at startup and keep the connection open for the app's whole life.
Part 5: CRUD operations
CRUD stands for the four basic things you do with data: Create, Read, Update, Delete. All the code below goes inside main(), so that client.close() in .finally() runs after all of it. (ES Modules also allow top-level await, but keeping the work in main() puts connecting and closing in one place, and it's how you'd write it in CommonJS too.)
Create: insertOne / insertMany
const result = await users.insertOne({
firstName: "Akshad",
lastName: "Jaiswal",
city: "Pune",
age: 25,
});
console.log(result.insertedId); // the new document's _id
await users.insertMany([
{ firstName: "Aditi", city: "Mumbai", age: 23 },
{ firstName: "Rohan", city: "Pune", age: 28 },
]);const result = await users.insertOne({
firstName: "Akshad",
lastName: "Jaiswal",
city: "Pune",
age: 25,
});
console.log(result.insertedId); // the new document's _id
await users.insertMany([
{ firstName: "Aditi", city: "Mumbai", age: 23 },
{ firstName: "Rohan", city: "Pune", age: 28 },
]);Read: find / findOne
// all documents
const all = await users.find({}).toArray();
// with a filter: everyone in Pune
const inPune = await users.find({ city: "Pune" }).toArray();
// comparison operators: age greater than 24
const older = await users.find({ age: { $gt: 24 } }).toArray();
// just one document (or null if none matches)
const rohan = await users.findOne({ firstName: "Rohan" });
// how many?
const count = await users.countDocuments({ city: "Pune" });// all documents
const all = await users.find({}).toArray();
// with a filter: everyone in Pune
const inPune = await users.find({ city: "Pune" }).toArray();
// comparison operators: age greater than 24
const older = await users.find({ age: { $gt: 24 } }).toArray();
// just one document (or null if none matches)
const rohan = await users.findOne({ firstName: "Rohan" });
// how many?
const count = await users.countDocuments({ city: "Pune" });- The object you pass is a filter: it describes which documents you want.
{}means "all". find()returns a cursor, a pointer that fetches results in batches..toArray()collects them all into an array. That's fine for small results; for large ones, you'd loop over the cursor instead.findOne()returns a single document ornull, never an array. (This difference causes a classic bug, shown in Chapter S2 07: Diving into APIs.)- Operators start with
$:$gt(greater than),$lt(less than),$in(in a list),$ne(not equal),$or...
Update: updateOne / updateMany
// ObjectId comes from the import at the top of db.js
await users.updateOne(
{ _id: new ObjectId("67066d6a3be8f41630d5dae4") }, // which document
{ $set: { city: "Bengaluru" } } // what to change
);
await users.updateMany({ city: "Pune" }, { $inc: { age: 1 } }); // add 1 to every Pune user's age// ObjectId comes from the import at the top of db.js
await users.updateOne(
{ _id: new ObjectId("67066d6a3be8f41630d5dae4") }, // which document
{ $set: { city: "Bengaluru" } } // what to change
);
await users.updateMany({ city: "Pune" }, { $inc: { age: 1 } }); // add 1 to every Pune user's age- The first argument is the filter, the second describes the change.
$setchanges only the listed fields. Without$set, you'd be trying to replace the whole document, whichupdateOnerefuses to do._idvalues areObjectIdobjects, not plain strings. To find by ID, wrap the string:new ObjectId("..."). Forgetting torequireObjectIdgivesReferenceError: ObjectId is not defined.
Delete: deleteOne / deleteMany
await users.deleteOne({ _id: new ObjectId("670668562c6bd11e25050c13") });
await users.deleteMany({ city: "Mumbai" }); // careful: {} would delete EVERYTHINGawait users.deleteOne({ _id: new ObjectId("670668562c6bd11e25050c13") });
await users.deleteMany({ city: "Mumbai" }); // careful: {} would delete EVERYTHINGWhat is an ObjectId?
Every document gets a unique _id. By default it's an ObjectId: a 12-byte value usually shown as 24 hex characters, like 67066d6a3be8f41630d5dae4. It's generated by the driver, on your side, before the document is even sent. The first 4 bytes are a timestamp, so you can tell when a document was created:
console.log(new ObjectId("67066d6a3be8f41630d5dae4").getTimestamp());console.log(new ObjectId("67066d6a3be8f41630d5dae4").getTimestamp());CRUD at a glance
| Operation | Methods | Returns |
|---|---|---|
| Create | insertOne(doc), insertMany([docs]) | { acknowledged, insertedId(s) } |
| Read | find(filter) → cursor, findOne(filter) → doc or null, countDocuments(filter) | documents or a number |
| Update | updateOne(filter, update), updateMany(...) | { matchedCount, modifiedCount } |
| Delete | deleteOne(filter), deleteMany(filter) | { deletedCount } |
From the raw driver to Mongoose
The mongodb driver is flexible but gives you no rules: nothing stops you from saving a user with age: "banana". In Season 2, DevTinder uses Mongoose, a library built on top of this driver that adds schemas, validation and handy helpers. You'll start with it in Chapter S2 06: Database, Schema, Models & Mongoose.
Common mistakes
- Hardcoding the connection string in code that gets pushed to GitHub. Use environment variables.
- IP not allowed in Atlas Network Access: the connection times out with
MongoServerSelectionError. - Wrong user credentials:
bad auth : authentication failed. Remember it's the database user, not your Atlas login. - Using
awaitoutside anasyncfunction in a CommonJS file:SyntaxError. - Comparing
_idwith a string:{ _id: "6706..." }matches nothing; usenew ObjectId("6706..."). - Forgetting
.toArray()afterfind(): you get a cursor object, not your documents.
Key takeaways
- Atlas runs MongoDB for you: create a free M0 cluster, a database user, and allow only the IPs that need access.
- The connection string contains your credentials. Keep it in an environment variable, never in Git.
- Compass lets you see and edit your data visually.
- Connect with
MongoClient, thenclient.db(name).collection(name). Every operation returns a Promise. - CRUD:
insertOne/insertMany,find/findOne/countDocuments,updateOne/updateManywith$set,deleteOne/deleteMany. _idis an ObjectId: search withnew ObjectId("...").
Interview questions
Q1. What is the difference between find() and findOne()?
find(filter) returns a cursor over all matching documents (use .toArray() or iterate it). findOne(filter) returns the first matching document, or null if nothing matches. It never returns an array.
Q2. What is an ObjectId?
It's MongoDB's default type for _id: a 12-byte unique identifier, usually shown as 24 hexadecimal characters. It contains a 4-byte timestamp, a random value and a counter, so it can be generated on the client without asking the server, and it roughly sorts by creation time. getTimestamp() returns its creation date.
Q3. What's the difference between updateOne with $set and replacing a document?
updateOne(filter, { $set: { city: "Pune" } }) changes only the listed fields and keeps the rest. replaceOne(filter, newDoc) replaces the entire document (except _id) with newDoc, so any fields you don't include are lost. updateOne requires update operators like $set, $inc or $push.
Q4. What is a cursor in MongoDB?
A cursor is a pointer to the result set of a query. Instead of loading every result at once, the driver fetches documents in batches as you iterate. This keeps memory use low for large results. .toArray() reads the whole cursor into an array.
Q5. How should you store database credentials in a Node.js app?
In environment variables (process.env.MONGODB_URI), loaded from a .env file in development (node --env-file=.env or the dotenv package) and from the hosting platform's settings or a secret manager in production. The .env file must be in .gitignore. Credentials should never be committed to source control.
Q6. Should you open a new database connection for every request?
No. Connecting is slow (network, TLS, authentication). Create one client when the app starts and reuse it; the driver keeps a connection pool and shares connections between requests automatically.
Q7. What are some common MongoDB query operators?
Comparison: $eq, $ne, $gt, $gte, $lt, $lte, $in, $nin. Logical: $and, $or, $not. Update: $set, $unset, $inc, $push, $pull. For example, { age: { $gte: 18 }, city: { $in: ["Pune", "Mumbai"] } }.
What's next
That's the end of Season 1. You understand how Node.js works and how to store data. In Season 2 you'll build DevTinder, a real app, starting with how software projects are planned in companies: Chapter S2 01: Microservices vs Monolith - How to build a project.