Learn how to connect Node.js with MongoDB, create collections, insert documents, retrieve data, update records, delete records, and build a simple REST API.
Node.js handles application logic and HTTP requests, while MongoDB stores the application's data.
| MongoDB | MySQL |
|---|---|
| Document-oriented NoSQL database. | Relational SQL database. |
| Stores documents in BSON format. | Stores data in tables and rows. |
| Uses collections and documents. | Uses tables and records. |
Uses queries such as find(). |
Uses SQL statements such as SELECT. |
| Supports flexible document structures. | Uses defined table schemas. |
You can use either a local MongoDB installation or MongoDB Atlas.
Official download: MongoDB Community Server
Official website: MongoDB Atlas
Create a folder named node-mongodb-app.
mkdir node-mongodb-app
cd node-mongodb-app
npm init -y
The npm init -y command creates a default
package.json file.
Install the official MongoDB driver and Express:
npm install mongodb express
mongodb package is the official Node.js driver.
It lets your Node.js application communicate directly with MongoDB.
MongoDB organizes data using three important concepts:
| Concept | Meaning | Example |
|---|---|---|
| Database | Contains collections. | school_db |
| Collection | Contains related documents. | students |
| Document | Stores individual data. | A student's name and course. |
{
"name": "Rahul Kumar",
"email": "rahul@example.com",
"course": "Node.js",
"age": 20
}
MongoDB stores documents in BSON, a binary representation of JSON-like data. The driver converts documents to and from JavaScript objects.
Create a file named db.js.
const { MongoClient } = require("mongodb");
const uri = process.env.MONGODB_URI ||
"mongodb://127.0.0.1:27017";
const client = new MongoClient(uri);
let db;
async function connectDB() {
if (!db) {
await client.connect();
db = client.db("school_db");
console.log("MongoDB connected successfully!");
}
return db;
}
module.exports = {
connectDB,
client
};
MongoClient is used to connect to MongoDB.uri contains the database connection string.client.connect() establishes the connection.client.db("school_db") selects the database.connectDB() returns the database object.MONGODB_URI environment variable to your
actual connection string. Keep passwords and credentials private.
Create a file named test-db.js.
const { connectDB, client } = require("./db");
async function testConnection() {
try {
const db = await connectDB();
await db.command({ ping: 1 });
console.log("Database is ready!");
} catch (error) {
console.error("MongoDB connection failed:", error.message);
} finally {
await client.close();
}
}
testConnection();
Run the file:
node test-db.js
MongoDB connected successfully!
Database is ready!
Use insertOne() to add one student document
to the collection.
const { connectDB, client } = require("./db");
async function addStudent() {
try {
const db = await connectDB();
const result = await db.collection("students").insertOne({
name: "Rahul Kumar",
email: "rahul@example.com",
course: "Node.js",
age: 20
});
console.log("Student added successfully!");
console.log("Inserted ID:", result.insertedId);
} catch (error) {
console.error("Error:", error.message);
} finally {
await client.close();
}
}
addStudent();
db.collection("students") selects a collection.insertOne() inserts one document.result.insertedId returns the new document's ID.
Use find() and toArray() to retrieve
the documents from a collection.
const { connectDB, client } = require("./db");
async function getStudents() {
try {
const db = await connectDB();
const students = await db
.collection("students")
.find({})
.toArray();
console.log(students);
} catch (error) {
console.error("Error:", error.message);
} finally {
await client.close();
}
}
getStudents();
[
{
_id: ObjectId("..."),
name: "Rahul Kumar",
email: "rahul@example.com",
course: "Node.js",
age: 20
}
]
MongoDB automatically assigns an _id field to a
document when you do not provide one.
Use findOne() to retrieve the first document
matching a condition.
const { connectDB, client } = require("./db");
async function findStudent() {
try {
const db = await connectDB();
const student = await db.collection("students").findOne({
name: "Rahul Kumar"
});
if (!student) {
console.log("Student not found");
} else {
console.log(student);
}
} catch (error) {
console.error("Error:", error.message);
} finally {
await client.close();
}
}
findStudent();
findOne() returns one
matching document or null if no matching document exists.
Use updateOne() with $set to change
selected fields in an existing document.
const { connectDB, client } = require("./db");
async function updateStudent() {
try {
const db = await connectDB();
const result = await db.collection("students").updateOne(
{ email: "rahul@example.com" },
{
$set: {
course: "Full Stack Development"
}
}
);
if (result.matchedCount === 0) {
console.log("Student not found");
} else {
console.log("Matched:", result.matchedCount);
console.log("Modified:", result.modifiedCount);
}
} catch (error) {
console.error("Error:", error.message);
} finally {
await client.close();
}
}
updateStudent();
The first argument identifies the document. The second argument contains the update operation.
Use deleteOne() to remove one matching document.
const { connectDB, client } = require("./db");
async function deleteStudent() {
try {
const db = await connectDB();
const result = await db.collection("students").deleteOne({
email: "rahul@example.com"
});
if (result.deletedCount === 0) {
console.log("Student not found");
} else {
console.log("Student deleted successfully!");
}
} catch (error) {
console.error("Error:", error.message);
} finally {
await client.close();
}
}
deleteStudent();
Now let's create an Express API that connects to MongoDB and provides endpoints for student records.
Create a file named server.js.
const express = require("express");
const { connectDB, client } = require("./db");
const app = express();
app.use(express.json());
// GET all students
app.get("/students", async (req, res) => {
try {
const db = await connectDB();
const students = await db
.collection("students")
.find({})
.toArray();
res.json(students);
} catch (error) {
console.error(error);
res.status(500).json({
message: "Unable to retrieve students"
});
}
});
// POST a new student
app.post("/students", async (req, res) => {
try {
const { name, email, course } = req.body;
if (
typeof name !== "string" || !name.trim() ||
typeof email !== "string" || !email.trim() ||
typeof course !== "string" || !course.trim()
) {
return res.status(400).json({
message: "Name, email, and course are required"
});
}
const db = await connectDB();
const result = await db.collection("students").insertOne({
name: name.trim(),
email: email.trim(),
course: course.trim()
});
res.status(201).json({
message: "Student added successfully",
id: result.insertedId
});
} catch (error) {
console.error(error);
res.status(500).json({
message: "Unable to add student"
});
}
});
// Start the server after connecting to MongoDB
async function startServer() {
try {
await connectDB();
const PORT = process.env.PORT || 5000;
app.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
});
} catch (error) {
console.error("Unable to start server:", error.message);
process.exitCode = 1;
}
}
startServer();
Run the server:
node server.js
| Method | URL | Purpose |
|---|---|---|
| GET | http://localhost:5000/students |
Retrieve all students. |
| POST | http://localhost:5000/students |
Add a student. |
For a POST request, select Body → raw → JSON and enter:
{
"name": "Priya Sharma",
"email": "priya@example.com",
"course": "React"
}
Click Send. A successful insertion should return
HTTP status code 201 Created.
| Method | Purpose |
|---|---|
insertOne() |
Insert one document. |
insertMany() |
Insert multiple documents. |
find() |
Retrieve matching documents using a cursor. |
findOne() |
Retrieve one matching document. |
updateOne() |
Update one matching document. |
updateMany() |
Update multiple matching documents. |
deleteOne() |
Delete one matching document. |
deleteMany() |
Delete multiple matching documents. |
| Error | Possible Solution |
|---|---|
| ECONNREFUSED | Check that the local MongoDB server is running. |
| Authentication failed | Check the database username, password, and authentication settings. |
| Server selection timeout | Check the connection string, network access, and server availability. |
| Cannot find module 'mongodb' | Run npm install mongodb in the project folder. |
| Invalid connection string | Verify the URI format and encode special characters in credentials where required. |
Create a student management application using Node.js, Express, and MongoDB.
school_db.students.{
"name": "Aman Kumar",
"email": "aman@example.com",
"course": "Node.js"
}
Bonus Task: Add update and delete endpoints to complete the CRUD operations.
Select the correct answer for each question.