NodeJs

Build a Node.js + MongoDB REST API in One File (For Absolute Beginners)

🚀 Build a Node.js + MongoDB REST API in One File (For Absolute Beginners)

Learn Node.js REST API development in the simplest way possible!
In this step-by-step tutorial, you’ll create a complete CRUD (Create, Read, Update, Delete) REST API using Node.js, Express, and MongoDB — all inside one file.
No extra folders, no complex setup — just clean and easy code for beginners.

✅ Step 1: Install Node.js and MongoDB

First, make sure you have Node.js and MongoDB installed. You can verify using:


node -v
mongo --version

✅ Step 2: Create Project Folder


mkdir simple-node-api
cd simple-node-api
npm init -y
npm install express mongoose body-parser cors

✅ Step 3: Create server.js

Now create a file named server.js and paste the following code:


// server.js
const express = require("express");
const mongoose = require("mongoose");
const bodyParser = require("body-parser");
const cors = require("cors");

const app = express();
app.use(cors());
app.use(bodyParser.json());

// ✅ Connect to MongoDB
mongoose.connect("mongodb://localhost:27017/simplecrudDB")
  .then(() => console.log("✅ Connected to MongoDB"))
  .catch(err => console.error("❌ MongoDB Connection Error:", err));

// ✅ Define Schema and Model
const userSchema = new mongoose.Schema({
  firstName: String,
  lastName: String,
  email: String,
  password: String
});

const User = mongoose.model("User", userSchema);

// ✅ CRUD Endpoints

// ➕ Create (POST)
app.post("/api/users", async (req, res) => {
  try {
    const user = new User(req.body);
    await user.save();
    res.status(201).json({ message: "User created", user });
  } catch (err) {
    res.status(400).json({ message: err.message });
  }
});

// 📋 Read All (GET)
app.get("/api/users", async (req, res) => {
  try {
    const users = await User.find();
    res.json(users);
  } catch (err) {
    res.status(500).json({ message: err.message });
  }
});

// 🔍 Read One (GET)
app.get("/api/users/: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({ message: err.message });
  }
});

// ✏️ Update (PUT)
app.put("/api/users/:id", async (req, res) => {
  try {
    const user = await User.findByIdAndUpdate(req.params.id, req.body, { new: true });
    if (!user) return res.status(404).json({ message: "User not found" });
    res.json({ message: "User updated", user });
  } catch (err) {
    res.status(400).json({ message: err.message });
  }
});

// 🗑️ Delete (DELETE)
app.delete("/api/users/:id", async (req, res) => {
  try {
    const result = await User.findByIdAndDelete(req.params.id);
    if (!result) return res.status(404).json({ message: "User not found" });
    res.json({ message: "User deleted" });
  } catch (err) {
    res.status(500).json({ message: err.message });
  }
});

// ✅ Start Server
const PORT = 5000;
app.listen(PORT, () => console.log(`🚀 Server running on http://localhost:${PORT}`));

✅ Step 4: Run Your API

Start your server by running the following command:


node server.js

Your REST API will be available at http://localhost:5000/api/users

✅ Step 5: Test with Postman

Use Postman to test each endpoint:

Method Endpoint Description
POST /api/users Create a new user
GET /api/users Get all users
GET /api/users/:id Get user by ID
PUT /api/users/:id Update user details
DELETE /api/users/:id Delete a user

✅ Example JSON (for POST)


{
  "firstName": "Umar",
  "lastName": "Rahman",
  "email": "umar@example.com",
  "password": "123456"
}

🎯 You Did It!

That’s it! 🎉 You’ve built a complete Node.js + MongoDB REST API in a single file.
This simple example helps you understand the full cycle of connecting MongoDB, defining a model, and performing CRUD operations.

💡 Next Steps

  • Add password encryption using bcryptjs.
  • Add login & JWT authentication.
  • Deploy your API to Render or Vercel.

Keep experimenting — and soon you’ll be building professional full-stack applications!


📚 Route Path Summary

  • POST/api/users — Create a new user
  • GET/api/users — Fetch all users
  • GET/api/users/:id — Fetch single user by ID
  • PUT/api/users/:id — Update user details
  • DELETE/api/users/:id — Delete a user

📍Base URL: http://localhost:5000

Leave a Reply

Your email address will not be published. Required fields are marked *