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! π
- β 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)
| 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 |
node-web-server/
β
βββ access.log # Request logs
βββ index.js # Main application file
βββ package.json # Project dependencies
βββ package-lock.json # Locked dependencies
βββ README.md # Documentation
Before you begin, ensure you have the following installed:
- Node.js (v14 or higher)
- MongoDB (local installation or MongoDB Atlas account)
- npm or yarn
git clone https://github.com/mirbasit01/nodeWebServer.git
cd nodeWebServernpm installMake sure MongoDB is running locally:
Windows:
- Check if MongoDB Service is running in Services
Mac/Linux:
mongodOr use MongoDB Atlas:
- Update the connection string in
index.jsto your MongoDB Atlas URI
node index.jsServer will run on: http://localhost:3000
You should see:
MongoDB Connected
Server running on http://localhost:3000
mongoose.connect('mongodb://127.0.0.1:27017/nodeWebServer')Database Name: nodeWebServer
{
firstName: String, // Required
lastName: String,
email: String, // Required, Unique
jobTitle: String,
gender: String,
createdAt: Date, // Auto-generated
updatedAt: Date // Auto-generated
}GET /usersReturns an HTML list of all users
GET /api/usersReturns JSON array of all users
GET /api/users/:idExample:
GET /api/users/507f1f77bcf86cd799439011POST /api/users
Content-Type: application/jsonRequest 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"
}
}PATCH /api/users/:id
Content-Type: application/jsonRequest Body:
{
"jobTitle": "Senior Developer"
}DELETE /api/users/:idAll 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
You can test APIs using:
# 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- Import the API endpoints
- Set the Content-Type header to
application/json - Send requests with appropriate JSON bodies
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);
});find({})- Retrieves all documentsfindById(id)- Retrieves a single document by IDcreate(data)- Creates a new documentfindByIdAndUpdate(id, data)- Updates a documentfindByIdAndDelete(id)- Deletes a document
Solution: Ensure MongoDB service is running. Check the connection string.
Solution: You're trying to create a user with an email that already exists. Email must be unique.
Solution: Check that you're providing all required fields (firstName and email) in your request.
- Error Handling: Always wrap async operations in try-catch blocks
- Environment Variables: Use
dotenvfor sensitive data - Input Validation: Validate and sanitize user input
- Status Codes: Use appropriate HTTP status codes
- 200 OK
- 201 Created
- 400 Bad Request
- 404 Not Found
- 500 Internal Server Error
- 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
Contributions are welcome! Please feel free to submit a Pull Request.
- Fork the project
- Create your feature branch (
git checkout -b feature/AmazingFeature) - Commit your changes (
git commit -m 'Add some AmazingFeature') - Push to the branch (
git push origin feature/AmazingFeature) - Open a Pull Request
Mir Basit
- GitHub: @mirbasit01
Give a βοΈ if this project helped you learn something new!
Happy Coding! π