Skip to content

Repository files navigation

Node.js RESTful API with MongoDB

A robust backend solution built with Node.js, Express.js, and MongoDB. This RESTful API provides a solid foundation for web and mobile applications.

Features

  • RESTful Architecture: Follows REST principles with proper HTTP methods and status codes
  • MongoDB Integration: Uses Mongoose ODM for data modeling and database operations
  • Authentication System: JWT-based authentication with secure password storage
  • Input Validation: Request validation for data integrity
  • Error Handling: Comprehensive error handling with appropriate HTTP status codes
  • Pagination: Built-in pagination for data-heavy endpoints
  • Modular Design: Clean code organization following the MVC pattern

API Endpoints

Users

  • POST /api/users - Register a new user
  • POST /api/users/login - Authenticate user & get token
  • GET /api/users/profile - Get user profile (Protected)
  • PUT /api/users/profile - Update user profile (Protected)
  • GET /api/users - Get all users (Admin only)

Products

  • GET /api/products - Fetch all products
  • GET /api/products/:id - Fetch single product
  • POST /api/products - Create a product (Admin only)
  • PUT /api/products/:id - Update a product (Admin only)
  • DELETE /api/products/:id - Delete a product (Admin only)
  • POST /api/products/:id/reviews - Create product review (Protected)

Getting Started

Prerequisites

  • Node.js (v14 or higher)
  • MongoDB (local or Atlas)

Installation

  1. Clone the repository
git clone https://github.com/yourusername/node-mongodb-rest-api.git
  1. Install dependencies
npm install
  1. Set up environment variables Create a .env file in the root directory with the following variables:
NODE_ENV=development
PORT=5000
MONGO_URI=your_mongodb_connection_string
JWT_SECRET=your_jwt_secret
  1. Run the server
npm run dev

Usage

Authentication

Most endpoints require authentication. To authenticate, obtain a token by logging in:

POST /api/users/login
{
  "email": "user@example.com",
  "password": "123456"
}

Then use the token in subsequent requests:

Authorization: Bearer your_token_here

Directory Structure

backend/
├── config/         # Database configuration
├── controllers/    # Route controllers
├── middleware/     # Custom middleware
├── models/         # Database models
├── routes/         # API routes
├── utils/          # Utility functions
└── server.js       # Entry point

License

This project is licensed under the MIT License - see the LICENSE file for details.

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Used by

Contributors

Languages