Skip to content

knightdev159/nodejs-mongodb-api

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

1 Commit
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Node.js MongoDB API

This project is a simple Node.js Express API that connects to a MongoDB database to retrieve user data. It features a GET endpoint at /users/:id that allows clients to fetch user details by their ID, ensuring that only users older than 21 are returned. The API gracefully handles invalid ObjectId errors and returns a 404 response if the user is not found.

Project Structure

  • src/app.js: Entry point of the application, initializes the Express app and sets up middleware and routes.
  • src/controllers/userController.js: Contains the logic for handling user-related requests.
  • src/models/user.js: Defines the schema for user documents in MongoDB.
  • src/routes/userRoutes.js: Sets up the routes for user-related endpoints.
  • src/routes/index.js: Combines all resource routers (e.g., user, post) for modular routing.
  • src/db/index.js: Manages the connection to the MongoDB database.
  • package.json: Lists project dependencies and scripts.

Getting Started

  1. Clone the repository.
  2. Run npm install to install the required dependencies.
  3. Create a .env file in the project root with your MongoDB connection string:
    MONGODB_URI=mongodb://localhost:27017/your_database_name
    PORT=3000
    
  4. Start the server with node src/app.js or npm start.

Usage

To retrieve a user by ID, send a GET request to /users/:id, replacing :id with the actual user ID.
The response will include the user's details if they exist and are over 21 years old, or a 404 error if not found.

Approach

  • Used Express for routing and middleware.
  • Used Mongoose for MongoDB object modeling.
  • Modularized the code for scalability, allowing easy addition of new resource routers.
  • Implemented error handling for invalid ObjectId and not found cases.
  • Used environment variables for configuration (e.g., MongoDB URI, port).

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published