Simple backend API built with Node.js, Express and MongoDB for an assignment demo. The project includes JWT authentication, class-based error handling, pagination, aggregation with $lookup, search, and a clean folder structure.
- Node.js
- Express.js
- MongoDB + Mongoose
- JWT
- 4 collections: Users, Posts, Comments, Categories
- Required 10+ APIs
- Pagination in all list APIs
- Aggregation with
$lookup - Search posts by title or content
- Class-based custom error handling
- JWT auth for protected routes
- Bonus: top 3 users with most posts
- Bonus: latest posts first sorting
- Bonus:
$groupand$facetaggregation usage
src/
config/
controllers/
middlewares/
models/
routes/
utils/
app.js
server.js- Install dependencies:
npm install- Create
.envfrom.env.example
PORT=5000
MONGODB_URI=mongodb://127.0.0.1:27017/assignment_db
JWT_SECRET=your_super_secret_key
JWT_EXPIRES_IN=7d
NODE_ENV=development- Start the server:
npm run devnpm run dev- start server with watch modenpm start- start server normally
POST /api/auth/register- Register user and get tokenPOST /api/auth/login- Login and get tokenGET /api/auth/me- Get logged in user profile
POST /api/users- Create UserGET /api/users?page=1&limit=10- Get All UsersGET /api/users/:id- Get Single UserDELETE /api/users/:id- Delete UserGET /api/users/top-posters- Top 3 users with most posts
POST /api/categories- Create CategoryGET /api/categories?page=1&limit=10- Get All Categories
POST /api/posts- Create PostGET /api/posts?page=1&limit=10- Get All PostsGET /api/posts/:id- Get Post by ID with user, category and commentsPATCH /api/posts/:id- Update PostGET /api/posts/search?query=node&page=1&limit=10- Search posts
POST /api/comments- Add CommentGET /api/comments/post/:postId?page=1&limit=10- Get Comments by Post
Use JWT token in header:
Authorization: Bearer your_token_hereProtected routes:
GET /api/auth/mePOST /api/categoriesPOST /api/postsPATCH /api/posts/:idPOST /api/comments
{
"name": "Arpit",
"email": "arpit@example.com",
"password": "123456"
}{
"name": "Technology",
"description": "Tech related posts"
}{
"title": "Node Assignment",
"content": "This is a sample post content",
"category": "category_object_id_here"
}{
"content": "Nice post",
"postId": "post_object_id_here"
}- User APIs: done
- Post APIs: done
- Comment APIs: done
- Search API: done
- Pagination: done
- Error handling: done
- JWT: added
- Bonus features: done