Day 67 of my #100DaysOfCodechallenge Today I focused on improving my Node.js REST API by implementing sorting and field limiting using Mongoose. These features allow API users to control how data is returned from the database. Key things I learned: • How to sort results dynamically using query parameters Example: GET /api/v1/movies?sort=price • How to return only specific fields from the database to reduce payload size Example: GET /api/v1/movies?fields=name,price,ratings • Using JavaScript string manipulation to transform query parameters into MongoDB-compatible queries. This makes the API more flexible, efficient, and closer to production-level design. Next, I plan to implement pagination so users can control how many results are returned per request. #100DaysOfCode #NodeJS #MongoDB #BackendDevelopment #WebDevelopment #LearningInPublic
Improving Node.js REST API with Mongoose Sorting and Limiting
More Relevant Posts
-
🚀 Learning System Design by Building a URL Shortener Today I worked on building a full-stack URL Shortener to understand how real-world systems are designed and scaled. What the backend is doing: Accepts a long URL and generates a unique short code Stores the mapping in MongoDB Redirects users from short URL → original URL Tracks total clicks for each shortened link Exposes a simple analytics endpoint for URL stats Handles duplicate URLs and validates input properly Tech Stack: Frontend: Next.js, Tailwind CSS Backend: Node.js, Express.js Database: MongoDB Atlas Deployment: Vercel + Render This project helped me understand concepts like: API design Routing and controllers Database schema design URL mapping logic Analytics tracking Deployment and production debugging 🔗 Live Demo: https://lnkd.in/g_qd-WB7 💻 Source Code: https://lnkd.in/g7Kp865n Still learning and improving it step by step ⚡ Would love to hear what features you’d add next! #SystemDesign #FullStackDevelopment #WebDevelopment #Nodejs #Nextjs #MongoDB #SoftwareEngineer #BuildInPublic #BackendDevelopment #100DaysOfCode
To view or add a comment, sign in
-
-
Most Mongoose developers are wasting performance… without realizing it. If you're building APIs and NOT using .lean(), you're returning heavy Mongoose documents every time. 👉 But in 90% of GET APIs, you don’t need them. Here’s the fix: const users = await User.find().lean(); 💡 What changes? • No Mongoose overhead • Faster query response • Lower memory usage • Cleaner API output ⚠️ Important: Don’t use .lean() when you need document methods like .save() or .populate(). 🧠 Rule: Use .lean() for read operations, skip it for write/update logic. Small optimization. Huge impact. Are you using .lean() in your APIs? #NodeJS #MongoDB #Mongoose #BackendDevelopment #WebPerformance #JavaScript #APIDesign #100DaysOfCode
To view or add a comment, sign in
-
-
🚀 **Day Progress: Building a Full-Stack Blog API (Node.js + MongoDB)** Today was all about strengthening my backend skills by working on a **Comment System** with real-world logic and security 🔐 💡 Here’s what I built & learned: ✅ Created **Comment API** (Add Comment to a Post) ✅ Understood how to link data using **MongoDB ObjectId (post ↔ comment ↔ user)** ✅ Implemented **JWT Authentication** (secure user identity) ✅ Learned why **userId should never come from frontend** (security best practice) ✅ Debugged real errors like: * `Comment.create is not a function` * `Cannot access 'post' before initialization` * `commentId undefined` 🔥 Built **Delete Comment API** with proper logic: * Check if comment exists * Verify logged-in user * Allow delete **only by owner** 🧠 Key Concepts I Mastered: * req.params vs req.body * Middleware vs Controller responsibilities * Authentication flow (JWT → req.user) * Database relationships using Mongoose * Debugging like a developer 💪 🚀 Feeling more confident in backend development and API design! Next Step 👉 Building: ➡️ Get Comments API with populate (username + profile) ➡️ Frontend integration #NodeJS #MongoDB #BackendDevelopment #WebDevelopment #JWT #API #CodingJourney #LearningInPublic
To view or add a comment, sign in
-
-
🚀 Built a RESTful Photo Upload API using Node.js A clean backend project that handles image uploading and retrieval with: Express.js for routing Multer for file handling with type validation (images only) MongoDB + Mongoose for data persistence Middleware to auto-generate full image URLs on fetch GitHub: ( https://lnkd.in/dbeKcETH ) #NodeJS #ExpressJS #MongoDB #Multer #BackendDevelopment #REST_API
To view or add a comment, sign in
-
-
Building a robust MERN application is often less about the code you write and more about the "silent killers" you ignore. If you’ve ever had a production build crash because of a "simple" schema change or a stray environment variable, this is for you. The Hidden Cost of "It Works on My Machine" In the MERN ecosystem (MongoDB, Express, React, Node.js), we move fast. We love the flexibility of JSON-like documents and the speed of JavaScript across the whole stack. But that flexibility is a double-edged sword. Following are three structural traps most developers fall into and how to bridge the gap: 1. The "Schemaless" MongoDB Myth Just because MongoDB doesn't force a schema doesn't mean you shouldn't have one. Relying solely on application-level validation (like Mongoose) without considering database indexing or document versioning is a recipe for technical debt. The Fix: Implement strict JavaScript interfaces that mirror your Mongoose schemas to ensure type safety from the query to the UI. 2. The State Management Overkill React developers often jump to Redux or complex Context providers for data that could be handled by simple URL params or a localized hook. The Fix: Ask yourself: "Does this state need to persist across a refresh?" If not, keep it local. If it’s server data, use something like TanStack Query to handle caching and synchronization automatically. 3. The 'Heavy' Node Backend Node.js is incredible for I/O, but it’s single-threaded. If you’re performing heavy data processing or image manipulation directly in your Express routes, you’re blocking the event loop for every other user. The Fix: Offload CPU-intensive tasks to Worker Threads or a dedicated microservice. #MERNStack #MongoDB #NodeJS ##WorkerThread #MicroServices #ReduxToolkit #ReactQuery #SoftwareEngineer Haroon Rasheed
To view or add a comment, sign in
-
-
Day 65-71 of My MERN Stack Journey at DevGnan Under the guidance of Siva Kumar Sir Today Class is Complete Signup Flow: Frontend → Backend → Database (MongoDB) Ever wondered how real applications store user data from frontend forms into a database? This week, I built a complete backend integration flow using MERN Stack What I Implemented 1️⃣ Setup Express Server & CORS Enabled smooth communication between frontend and backend 2️⃣ Connected MongoDB using Mongoose Ensured database connection is successful before handling requests 3️⃣ Created .env Configuration Stored sensitive data like PORT & MONGO_URI securely using dotenv 4️⃣ Designed User Schema & Model Defined required fields and validation rules 5️⃣ Built Database Config (db.js) Centralized MongoDB connection logic 6️⃣ Created Signup API (POST) Handled user registration using req.body 7️⃣ Connected Frontend using Axios Sent form data from React to backend 8️⃣ Stored Data in MongoDB Successfully created my first user document 🔄 Flow Summary User fills form ➡️ Axios POST request ➡️ Express API ➡️ Mongoose Model ➡️ MongoDB Storage Key Learnings Backend is the backbone of real-world apps Environment variables are crucial for security Understanding full flow > just writing code API integration builds real developer confidence Result 👉 My first end-to-end working MERN feature is live ✅ ReadMe File: https://lnkd.in/ggmf8hA6 #MERNStack #MongoDB #ExpressJS #ReactJS #NodeJS #BackendDevelopment #WebDevelopment #LearningJourney #SoftwareEngineer
To view or add a comment, sign in
-
Leaving Node.js behind: Building a raw HTTP server in Go. After spending the week locking down my PostgreSQL database, it is finally time to build the API server. But moving from Node.js to Go requires a complete mental reset. In Node, you reach for Express.js immediately. You write app.get("/", (req, res) => {}) and you're good to go. In Go? There is no Express by default. You build it raw using the standard library (net/http). This simple block of code completely flips the script on how you handle data. package main import ( "log" "net/http" ) // The mental shift happens HERE: (w, r) func handler(w http.ResponseWriter, r *http.Request) { w.Write([]byte("hello world")) } func main() { http.HandleFunc("/", handler) if err := http.ListenAndServe(":8080", nil); err != nil { log.Fatal(err) } } In Node, it’s always (req, res) - Request first, Response second. In Go, the handler looks like this: (w http.ResponseWriter, r *http.Request). Response first, Request second. Why? Because Go treats the ResponseWriter (w) as a literal tool you are handed to execute your job. The server effectively says: "Here is your pen (w). Now look at the paperwork (r) and write your response back immediately." I'm officially writing my first route to start the Auth sequence. It’s raw, it’s fast, and there’s no framework magic hiding the fundamentals from me. We move! 💪🏾 To the devs who made the switch from JavaScript/Node.js to Go: What was the hardest habit you had to break? Let’s gist in the comments 👇🏾 #Golang #NodeJS #BackendEngineering #API #SoftwareDevelopment #TechBro #TechInNigeria #WeMove
To view or add a comment, sign in
-
-
🚀 Built a Full-Stack Photo Sharing REST API with Node.js Excited to share a backend project I've been working on — a photo sharing app built from scratch using modern Node.js practices. 🛠️ Tech Stack: Node.js + Express.js — REST API with clean layered architecture (APIs → Services → Models) MongoDB + Mongoose — NoSQL database with populate() for relational-style queries Multer + UUID — Secure file upload with unique filenames stored in /uploads dotenv — Environment-based configuration ⚙️ Key Features: User signup system with a structured User model Photo upload with image-type validation (images only) Up & Down voting system — users can upvote or downvote photos, but not both at the same time. Upvoting a photo automatically removes any existing downvote, and vice versa — handled atomically in a single MongoDB query using $push, $pull, and $inc together Toggle behavior — clicking the same vote again removes it Pagination — efficient data fetching with .skip() and .limit() Photos sorted by popularity (count descending) Populated responses returning user info with each photo 📐 Architecture: Clean separation of concerns across 3 layers — routing, business logic, and data — making the codebase scalable and easy to maintain. This project helped me go deeper into Mongoose atomic update operators, middleware chaining, and RESTful design patterns. Github:(https://lnkd.in/dQHNJ-et) #NodeJS #ExpressJS #MongoDB #Mongoose #RestAPI #BackendDevelopment #JavaScript #WebDevelopment #100DaysOfCode
To view or add a comment, sign in
-
-
🚀 Learning Backend Development with Node.js, Express & MongoDB I recently built a Simple Chat CRUD Application to practice backend development concepts. In this project, I implemented basic CRUD operations using Node.js, Express.js, and MongoDB. 🔧 Tech Stack: • Node.js • Express.js • MongoDB • Mongoose • EJS ✨ Features: ✔ View all chat messages ✔ Add a new chat message ✔ Edit existing messages ✔ Delete messages ✔ Data stored in MongoDB database This project helped me understand: • Express routing • CRUD operations with MongoDB • Mongoose schemas & models • Connecting Node.js with a database #NodeJS #ExpressJS #MongoDB #BackendDevelopment #WebDevelopment
To view or add a comment, sign in
-
💡 **A Lesser-Known Reality About MEAN Stack Performance** Many developers assume application slowness always comes from the database or backend logic. But while working on a large-scale MEAN application, I learned something surprising… 👉 The real bottleneck was *data over-fetching*, not server capacity. We were sending large payloads that the UI didn’t even need. This created: • Higher network latency • Increased memory usage in browsers • Slower rendering despite fast APIs Here’s what made the difference: ✔ Implemented response shaping & selective fields in MongoDB queries ✔ Added lightweight middleware layers in Express.js to compress and streamline API responses ✔ Used lazy loading and smarter state management in Angular ✔ Leveraged async, event-driven processing in Node.js to keep the system responsive under load 📊 **Interesting Comparison:** Optimizing payload size improved performance more than upgrading server hardware. ⚡ Lesson learned: Scalability isn’t just about handling more requests — it’s about sending *less unnecessary data*. Sometimes, efficiency beats infrastructure. #MEANStack #WebPerformance #FullStackDevelopment #Angular #NodeJS #MongoDB #ExpressJS #SoftwareArchitecture #Debugging
To view or add a comment, sign in
Explore content categories
- Career
- Productivity
- Finance
- Soft Skills & Emotional Intelligence
- Project Management
- Education
- Technology
- Leadership
- Ecommerce
- User Experience
- Recruitment & HR
- Customer Experience
- Real Estate
- Marketing
- Sales
- Retail & Merchandising
- Science
- Supply Chain Management
- Future Of Work
- Consulting
- Writing
- Economics
- Artificial Intelligence
- Employee Experience
- Workplace Trends
- Fundraising
- Networking
- Corporate Social Responsibility
- Negotiation
- Communication
- Engineering
- Hospitality & Tourism
- Business Strategy
- Change Management
- Organizational Culture
- Design
- Innovation
- Event Planning
- Training & Development