Hey there! 👋
If you're starting with backend development, one of the first things you’ll hear about is CRUD, which is short for Create, Read, Update, and Delete. These are the basic operations almost every app uses to handle data.
Whether you’re building a to-do app, a blog, or an e-commerce site, you’ll need to store, fetch, update, or delete data at some point. In this post, I’ll walk you through what CRUD means and how to implement it using MongoDB and Node.js.
Getting Started: MongoDB with Node.js (Step-by-Step)
Before we get into CRUD, let’s set up our environment and connect MongoDB with Node.js. I’ll explain every step clearly so you know exactly what each line does.
✅ Step 1: Install MongoDB Driver
First, we need the official MongoDB Node.js driver. Open your terminal and run:
npm install mongodb
This package allows your Node.js app to connect and interact with MongoDB.
✅ Step 2: Import MongoClient
Now, in your JavaScript file (e.g. app.js
), import MongoClient
from the package:
const { MongoClient } = require("mongodb");
This gives us access to the MongoDB client that we’ll use to connect to our database.
✅ Step 3: Set the Connection URI
This URI tells MongoClient where to find your MongoDB server. If you're using MongoDB locally, use:
const uri = "mongodb://localhost:27017";
If you’re using MongoDB Atlas (cloud-based), replace this with your connection string from the Atlas dashboard.
✅ Step 4: Create a MongoClient Instance
Now, set up a new MongoClient instance using the URI:
const client = new MongoClient(uri);
This prepares the connection but doesn’t open it yet.
✅ Step 5: Connect to MongoDB
Let’s connect using an async function:
await client.connect();
After this, we’re officially connected to MongoDB and can start using it.
✅ Step 6: Select a Database
Pick (or create) a database:
const db = client.db("myapp");
If "myapp" doesn’t exist yet, MongoDB will create it the first time you store data.
✅ Step 7: Choose a Collection
A collection is like a table in SQL. Here’s how you select or create a collection:
const users = db.collection("users");
Again, if the "users" collection doesn’t exist yet, MongoDB will create it when you insert your first document.
✅ Step 8: Perform Operations
Now you can insert, find, update, or delete documents in your collection. We'll go through each of those in the next section.
✅ Step 9: Close the Connection
Don’t forget to close the database connection when you’re done:
await client.close();
This helps free up resources and keeps things clean.
🔁 Full Setup Example
const { MongoClient } = require("mongodb");
const uri = "mongodb://localhost:27017";
const client = new MongoClient(uri);
async function run() {
try {
await client.connect(); // Connect to MongoDB
console.log("Connected successfully");
const db = client.db("myapp"); // Select the database
const users = db.collection("users"); // Select the collection
// Example: Insert a new user
await users.insertOne({ name: "Alice", age: 25 });
console.log("User inserted");
} catch (err) {
console.error("Error:", err);
} finally {
await client.close(); // Close the connection
console.log("Connection closed");
}
}
run();
CRUD Explained with MongoDB
Now that we’re connected to MongoDB, let’s look at each of the CRUD operations with real examples.
🟢 C – Create (Insert Data)
Use insertOne()
or insertMany()
to add data to your collection.
await users.insertOne({
name: "Alice",
email: "alice@example.com",
age: 25
});
To insert multiple users:
await users.insertMany([
{ name: "Bob", age: 30 },
{ name: "Charlie", age: 35 }
]);
🔵 R – Read (Fetch Data)
To read or retrieve data, use findOne()
or find()
:
const user = await users.findOne({ name: "Alice" });
console.log(user);
To get all users:
const allUsers = await users.find().toArray();
console.log(allUsers);
You can also filter, sort, or limit results as needed.
🟡 U – Update (Modify Data)
To update data, use updateOne()
or updateMany()
:
await users.updateOne(
{ name: "Alice" }, // filter
{ $set: { age: 26 } } // update
);
Update multiple documents:
await users.updateMany(
{ age: { $lt: 30 } },
{ $set: { status: "young" } }
);
🔴 D – Delete (Remove Data)
Use deleteOne()
or deleteMany()
to remove data:
await users.deleteOne({ name: "Charlie" });
Delete multiple documents:
await users.deleteMany({ age: { $gt: 50 } });
Always be cautious when deleting, double-check your filters!
Wrapping Up
And that’s CRUD in a nutshell! 🎉
Every backend app you build will use Create, Read, Update, and Delete operations in some form. With MongoDB and Node.js, it’s pretty easy to get started once you understand the basics.
Start experimenting, add new users, read them back, update their info, and try deleting some too. The best way to learn is to build things and break them.
Let me know if you want to see CRUD with other databases like PostgreSQL or MySQL, or want help with a small project!
Thanks for reading and happy coding!
Comments
Please login to publish your comment!
By logging in, you agree to our Terms of Service and Privacy Policy.
No comments here!