A Node.js Express API that connects to MongoDB and retrieves user data with age-based filtering.
This solution implements a RESTful API using Express.js with MongoDB integration. The /users/:id endpoint validates ObjectId format, queries the database for users over 21 years old, and returns appropriate HTTP status codes. The API includes error handling for invalid ObjectIds and gracefully manages database connection failures.
- ✅ GET endpoint at
/users/:idthat accepts user ID as route parameter - ✅ Queries MongoDB "users" collection for matching
_id - ✅ Returns user details in JSON format
- ✅ Returns 404 Not Found for non-existent users
- ✅ Gracefully handles invalid ObjectId errors (400 Bad Request)
- ✅ Unique twist: Only returns users where age > 21
- ✅ Health check endpoint at
/health - ✅ CORS enabled for cross-origin requests
- ✅ Environment variable configuration
-
Install dependencies:
npm install
-
Configure environment variables:
cp env.example .env # Edit .env with your MongoDB connection details -
Start MongoDB: Make sure MongoDB is running on your system or use a cloud MongoDB instance.
-
Run the application:
# Development mode with auto-restart npm run dev # Production mode npm start
Retrieves a user by ID (only if age > 21)
Parameters:
id(string): MongoDB ObjectId of the user
Responses:
200 OK: User found and returned400 Bad Request: Invalid ObjectId format404 Not Found: User not found or user is 21 or younger500 Internal Server Error: Server error
Example Response:
{
"_id": "507f1f77bcf86cd799439011",
"name": "John Doe",
"email": "johndoe@email.com",
"age": 30
}Health check endpoint
Response:
{
"status": "OK",
"message": "Server is running"
}To test the API, you can insert sample data into your MongoDB collection:
// In MongoDB shell or MongoDB Compass
use centivo_db
db.users.insertMany([
{
"_id": ObjectId("507f1f77bcf86cd799439011"),
"name": "John Doe",
"email": "johndoe@email.com",
"age": 30
},
{
"_id": ObjectId("507f1f77bcf86cd799439012"),
"name": "Jane Smith",
"email": "janesmith@email.com",
"age": 25
},
{
"_id": ObjectId("507f1f77bcf86cd799439013"),
"name": "Bob Wilson",
"email": "bobwilson@email.com",
"age": 19
}
])Test the API with curl or any HTTP client:
# Test with valid user ID (age > 21)
curl http://localhost:3000/users/507f1f77bcf86cd799439011
# Test with valid user ID (age <= 21) - should return 404
curl http://localhost:3000/users/507f1f77bcf86cd799439013
# Test with invalid ObjectId - should return 400
curl http://localhost:3000/users/invalid-id
# Test health endpoint
curl http://localhost:3000/health