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.
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.
- Clone the repository.
- Run
npm installto install the required dependencies. - Create a
.envfile in the project root with your MongoDB connection string:MONGODB_URI=mongodb://localhost:27017/your_database_name PORT=3000 - Start the server with
node src/app.jsornpm start.
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.
- 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).