Node Express Part2
by Kuligaposten 2026-02-16
A guide in Node Express backend.
Part 2: Connecting Express to MongoDB and Building a REST API
Now that you have a working Express app, the next step is making it dynamic by connecting it to a database. MongoDB is a popular NoSQL database that works seamlessly with Node.js.
1. Prerequisites
Make sure you have:
- Node.js + Express app (from Part 1)
- MongoDB installed locally or a free cloud instance on MongoDB Atlas
- A code editor like VS Code
2. Install MongoDB Dependencies
We'll use Mongoose, an ODM (Object Data Modeling) library that makes interacting with MongoDB easier.
npm install mongoose
3. Connect to MongoDB
Create a new file db.js to handle the connection:
// db.js
const mongoose = require("mongoose");
const MONGO_URI = "mongodb://127.0.0.1:27017/mydatabase"; // local MongoDB
// For MongoDB Atlas use: 'mongodb+srv://<username>:<password>@cluster0.mongodb.net/mydatabase?retryWrites=true&w=majority'
const connectDB = async () => {
try {
await mongoose.connect(MONGO_URI, {
useNewUrlParser: true,
useUnifiedTopology: true,
});
console.log("MongoDB connected");
} catch (error) {
console.error("MongoDB connection error:", error);
process.exit(1);
}
};
module.exports = connectDB;
Then, in index.js:
const connectDB = require("./db");
connectDB();
Now your app will connect to MongoDB when it starts.
4. Create a Model
Models define the structure of your data. Let’s create a simple User model.
Create models/User.js:
const mongoose = require("mongoose");
const userSchema = new mongoose.Schema({
name: {
type: String,
required: true,
},
email: {
type: String,
required: true,
unique: true,
},
createdAt: {
type: Date,
default: Date.now,
},
});
const User = mongoose.model("User", userSchema);
module.exports = User;
5. Create Routes
We’ll make a simple REST API with CRUD operations.
Create routes/users.js:
const express = require("express");
const router = express.Router();
const User = require("../models/User");
// GET all users
router.get("/", async (req, res) => {
try {
const users = await User.find();
res.json(users);
} catch (err) {
res.status(500).json({ error: err.message });
}
});
// GET user by ID
router.get("/:id", async (req, res) => {
try {
const user = await User.findById(req.params.id);
if (!user) return res.status(404).json({ message: "User not found" });
res.json(user);
} catch (err) {
res.status(500).json({ error: err.message });
}
});
// POST new user
router.post("/", async (req, res) => {
try {
const { name, email } = req.body;
const user = new User({ name, email });
await user.save();
res.status(201).json(user);
} catch (err) {
res.status(400).json({ error: err.message });
}
});
// PUT update user
router.put("/:id", async (req, res) => {
try {
const { name, email } = req.body;
const user = await User.findByIdAndUpdate(
req.params.id,
{ name, email },
{ new: true, runValidators: true },
);
if (!user) return res.status(404).json({ message: "User not found" });
res.json(user);
} catch (err) {
res.status(400).json({ error: err.message });
}
});
// DELETE user
router.delete("/:id", async (req, res) => {
try {
const user = await User.findByIdAndDelete(req.params.id);
if (!user) return res.status(404).json({ message: "User not found" });
res.json({ message: "User deleted" });
} catch (err) {
res.status(500).json({ error: err.message });
}
});
module.exports = router;
6. Connect Routes in index.js
const usersRouter = require("./routes/users");
app.use("/api/users", usersRouter);
Now your API endpoints are:
GET /api/users→ List all usersGET /api/users/:id→ Get a single userPOST /api/users→ Create a userPUT /api/users/:id→ Update a userDELETE /api/users/:id→ Delete a user
7. Test the API
Use Postman, Insomnia, or curl to test your endpoints.
Example using curl to create a user:
curl -X POST http://localhost:3000/api/users \
-H "Content-Type: application/json" \
-d '{"name":"Alice","email":"alice@example.com"}'
8. Optional: Environment Variables
Store sensitive info like MongoDB URI in .env:
MONGO_URI=mongodb://127.0.0.1:27017/mydatabase
PORT=3000
Install dotenv:
npm install dotenv
And load it in index.js:
require("dotenv").config();
const PORT = process.env.PORT || 3000;
const MONGO_URI = process.env.MONGO_URI;
Conclusion
You now have a full Node.js + Express + MongoDB REST API. This is a solid foundation for any web application. Next, you can:
- Add authentication with JWT
- Implement pagination and search
- Connect a frontend (React, Vue, Angular)
- Deploy your API to Heroku or Vercel