A simple Node.js Express API that connects to MongoDB and retrieves user data with age filtering.
This API implements a GET endpoint that queries MongoDB for users by ID, with the unique requirement of only returning users over 21 years old. The solution includes proper error handling for invalid ObjectIds and comprehensive validation to ensure data integrity.
- ✅ GET
/users/:idendpoint with age filtering (> 21) - ✅ MongoDB integration with proper connection handling
- ✅ ObjectId validation with graceful error handling
- ✅ 404 responses for non-existent users or users ≤ 21
- ✅ Environment variable configuration
- ✅ Health check endpoint
- Node.js (v14 or higher)
- MongoDB (local or cloud instance)
- npm or yarn
- Clone the repository:
git clone <your-repo-url>
cd user-api- Install dependencies:
npm install- Set up environment variables:
cp env.example .env
# Edit .env with your MongoDB connection details- Start the server:
# Development mode with auto-restart
npm run dev
# Production mode
npm startRetrieves a user by ID, only if they are over 21 years old.
Parameters:
id(string): MongoDB ObjectId of the user
Responses:
200 OK: User found and over 21400 Bad Request: Invalid ObjectId format404 Not Found: User not found or user is 21 or younger500 Internal Server Error: Server error
Example Request:
curl http://localhost:3000/users/507f1f77bcf86cd799439011Example Response:
{
"_id": "507f1f77bcf86cd799439011",
"name": "John Doe",
"email": "johndoe@email.com",
"age": 30
}Health check endpoint to verify server status.
Example Response:
{
"status": "OK",
"message": "Server is running"
}The API expects a users collection with the following schema:
{
"_id": ObjectId,
"name": "John Doe",
"email": "johndoe@email.com",
"age": 30
}You can insert sample data into your MongoDB users collection:
db.users.insertMany([
{
name: "John Doe",
email: "johndoe@email.com",
age: 30
},
{
name: "Jane Smith",
email: "janesmith@email.com",
age: 25
},
{
name: "Bob Johnson",
email: "bobjohnson@email.com",
age: 19
}
]);The API includes comprehensive error handling:
- Invalid ObjectId: Returns 400 with descriptive error message
- User not found: Returns 404 with explanation
- User ≤ 21: Returns 404 (treated as "not found" due to age filter)
- Database errors: Returns 500 with generic error message
| Variable | Description | Default |
|---|---|---|
MONGODB_URI |
MongoDB connection string | mongodb://localhost:27017 |
DB_NAME |
Database name | userdb |
PORT |
Server port | 3000 |
To run in development mode with auto-restart:
npm run devMIT