Skip to content

Backend-node/nodeWebServer

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

12 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

Node.js Express MongoDB Backend API

Node.js Express.js MongoDB JavaScript

A complete RESTful backend API built using Node.js, Express.js, and MongoDB (Mongoose). This project demonstrates a full transition from file-based storage (JSON) to a MongoDB database, including CRUD operations, middleware, and logging.

Perfect for beginners learning backend development! πŸš€

πŸ“Œ Features

  • βœ… Express.js REST API
  • βœ… MongoDB integration using Mongoose
  • βœ… User CRUD operations (Create, Read, Update, Delete)
  • βœ… Request logging using middleware
  • βœ… HTML rendering for users list
  • βœ… JSON API endpoints
  • βœ… Schema validation with Mongoose
  • βœ… Timestamps enabled (createdAt, updatedAt)

πŸ› οΈ Tech Stack

Technology Purpose
Node.js JavaScript runtime environment
Express.js Web application framework
MongoDB NoSQL database
Mongoose MongoDB object modeling tool
fs (File System) Request logging

πŸ“‚ Project Structure

node-web-server/
β”‚
β”œβ”€β”€ access.log              # Request logs
β”œβ”€β”€ index.js                # Main application file
β”œβ”€β”€ package.json            # Project dependencies
β”œβ”€β”€ package-lock.json       # Locked dependencies
└── README.md              # Documentation

βš™οΈ Installation & Setup

Prerequisites

Before you begin, ensure you have the following installed:

  • Node.js (v14 or higher)
  • MongoDB (local installation or MongoDB Atlas account)
  • npm or yarn

1️⃣ Clone the repository

git clone https://github.com/mirbasit01/nodeWebServer.git
cd nodeWebServer

2️⃣ Install dependencies

npm install

3️⃣ Start MongoDB

Make sure MongoDB is running locally:

Windows:

  • Check if MongoDB Service is running in Services

Mac/Linux:

mongod

Or use MongoDB Atlas:

  • Update the connection string in index.js to your MongoDB Atlas URI

4️⃣ Start the server

node index.js

Server will run on: http://localhost:3000

You should see:

MongoDB Connected
Server running on http://localhost:3000

πŸ”Œ MongoDB Connection

mongoose.connect('mongodb://127.0.0.1:27017/nodeWebServer')

Database Name: nodeWebServer

🧩 User Schema (Mongoose)

{
  firstName: String,      // Required
  lastName: String,
  email: String,         // Required, Unique
  jobTitle: String,
  gender: String,
  createdAt: Date,       // Auto-generated
  updatedAt: Date        // Auto-generated
}

πŸ“‘ API Endpoints

πŸ”Ή Get All Users (HTML)

GET /users

Returns an HTML list of all users

πŸ”Ή Get All Users (JSON)

GET /api/users

Returns JSON array of all users

πŸ”Ή Get User by ID

GET /api/users/:id

Example:

GET /api/users/507f1f77bcf86cd799439011

πŸ”Ή Create User

POST /api/users
Content-Type: application/json

Request Body:

{
  "first_name": "John",
  "last_name": "Doe",
  "email": "john@example.com",
  "gender": "Male",
  "job_title": "Developer"
}

Response (201 Created):

{
  "message": "Success",
  "user": {
    "_id": "507f1f77bcf86cd799439011",
    "firstName": "John",
    "lastName": "Doe",
    "email": "john@example.com",
    "gender": "Male",
    "jobTitle": "Developer",
    "createdAt": "2025-01-02T10:30:00.000Z",
    "updatedAt": "2025-01-02T10:30:00.000Z"
  }
}

πŸ”Ή Update User

PATCH /api/users/:id
Content-Type: application/json

Request Body:

{
  "jobTitle": "Senior Developer"
}

πŸ”Ή Delete User

DELETE /api/users/:id

🧾 Middleware (Logging)

All requests are logged into access.log:

2025-01-02T12:00:00.000Z - ::1 GET - /api/users
2025-01-02T12:01:15.000Z - ::1 POST - /api/users
2025-01-02T12:02:30.000Z - ::1 PATCH - /api/users/507f1f77bcf86cd799439011

πŸ§ͺ Testing

You can test APIs using:

Using cURL

# Get all users
curl http://localhost:3000/api/users

# Create a user
curl -X POST http://localhost:3000/api/users \
  -H "Content-Type: application/json" \
  -d '{"first_name":"Jane","last_name":"Smith","email":"jane@example.com","gender":"Female","job_title":"Designer"}'

# Get user by ID
curl http://localhost:3000/api/users/507f1f77bcf86cd799439011

# Update user
curl -X PATCH http://localhost:3000/api/users/507f1f77bcf86cd799439011 \
  -H "Content-Type: application/json" \
  -d '{"jobTitle":"Lead Designer"}'

# Delete user
curl -X DELETE http://localhost:3000/api/users/507f1f77bcf86cd799439011

Using Postman or Thunder Client

  1. Import the API endpoints
  2. Set the Content-Type header to application/json
  3. Send requests with appropriate JSON bodies

πŸ” Key Concepts Explained

Async/Await Pattern

We use async/await for handling asynchronous database operations, making code more readable:

app.get('/api/users', async (req, res) => {
  const users = await User.find({});
  res.json(users);
});

Mongoose Methods

  • find({}) - Retrieves all documents
  • findById(id) - Retrieves a single document by ID
  • create(data) - Creates a new document
  • findByIdAndUpdate(id, data) - Updates a document
  • findByIdAndDelete(id) - Deletes a document

⚠️ Common Errors & Solutions

Error: Cannot connect to MongoDB

Solution: Ensure MongoDB service is running. Check the connection string.

Error: E11000 duplicate key error

Solution: You're trying to create a user with an email that already exists. Email must be unique.

Error: ValidationError

Solution: Check that you're providing all required fields (firstName and email) in your request.

βœ… Best Practices

  1. Error Handling: Always wrap async operations in try-catch blocks
  2. Environment Variables: Use dotenv for sensitive data
  3. Input Validation: Validate and sanitize user input
  4. Status Codes: Use appropriate HTTP status codes
    • 200 OK
    • 201 Created
    • 400 Bad Request
    • 404 Not Found
    • 500 Internal Server Error

🚧 Future Improvements

  • Authentication (JWT)
  • Password hashing (bcrypt)
  • Environment variables (dotenv)
  • Pagination & filtering
  • Role-based access control
  • Error handling middleware
  • API rate limiting
  • Input validation with Joi/express-validator
  • Unit and integration tests
  • API documentation with Swagger

πŸ“š Resources

🀝 Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

  1. Fork the project
  2. Create your feature branch (git checkout -b feature/AmazingFeature)
  3. Commit your changes (git commit -m 'Add some AmazingFeature')
  4. Push to the branch (git push origin feature/AmazingFeature)
  5. Open a Pull Request

πŸ‘¨β€πŸ’» Author

Mir Basit

⭐ Show your support

Give a ⭐️ if this project helped you learn something new!


Happy Coding! πŸš€

About

This project is a RESTful backend API built using Node.js, Express.js, and MongoDB (Mongoose). It demonstrates a complete transition from file-based storage (JSON) to a MongoDB database, including CRUD operations, middleware, and logging.

Topics

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors