API Pagination + Search + Filter
API Pagination + Search + Filter in Express.js (Full Guide)
বড় ডাটা লিস্ট API তে একবারে রেসপন্স করা ঠিক না — এটি স্লো করে দেয় এবং ইউজারের জন্য অস্বস্তিকর হয়। তাই Pagination + Search + Filter ব্যবহার করা হয়। এই গাইডে আমরা Express.js দিয়ে একটি প্রফেশনাল API বানাবো যেখানে:
- Pagination → ডাটা অংশে অংশে পাঠানো
- Search → নাম বা টাইটেল দিয়ে সার্চ করা
- Filter → category, price ইত্যাদি দিয়ে ডাটা ফিল্টার করা
📌 Pagination কী?
Pagination মানে হলো ডাটাকে পেজ আকারে সার্ভ করা।
যেমন:
?page=1&limit=10
মানে প্রথম পেজে ১০টি ডাটা।
➡️ কেন Pagination দরকার?
- Fast API Response
- Server load কমে
- User experience উন্নত হয়
📌 Search কীভাবে কাজ করে?
Query দিয়ে সার্চ করা হয় যেমন:
?search=phone
MongoDB Text Search বা Regex দিয়ে matching করা হয়।
📌 Filter কী?
Filter মানে হলো category, price range, rating ইত্যাদি দিয়ে নির্দিষ্ট ডাটা আনা। Example:
?category=mobile&minPrice=5000&maxPrice=20000
📌 Full Working Example (Pagination + Search + Filter)
// productRoute.js
router.get("/products", async (req, res) => {
try {
const { page = 1, limit = 10, search, category, minPrice, maxPrice } = req.query;
// Base query
let query = {};
// Search
if (search) {
query.name = { $regex: search, $options: "i" };
}
// Filter by category
if (category) {
query.category = category;
}
// Filter by price range
if (minPrice || maxPrice) {
query.price = {};
if (minPrice) query.price.$gte = Number(minPrice);
if (maxPrice) query.price.$lte = Number(maxPrice);
}
// Pagination data
const skip = (page - 1) * limit;
const products = await Product.find(query)
.skip(skip)
.limit(Number(limit));
const total = await Product.countDocuments(query);
res.json({
success: true,
total,
page: Number(page),
totalPages: Math.ceil(total / limit),
products,
});
} catch (error) {
res.status(500).json({ message: "Server Error", error });
}
});
🔗 API Query Example URLs
- Pagination →
/products?page=2&limit=5 - Search →
/products?search=iphone - Filter →
/products?category=laptop - Price Filter →
/products?minPrice=10000&maxPrice=50000 - All in One →
/products?page=1&limit=10&search=apple&category=mobile&minPrice=5000
⭐ Best Practices
- Pagination limit 10–50 রাখা ভালো
- Search এর জন্য index ব্যবহার করুন
- Filter এর জন্য dynamic query ব্যবহার করুন
- Total count সবসময় API তে পাঠান
✅ Summary
Express.js এ Pagination + Search + Filter API খুব দরকারি এবং professional API তৈরির base skill। এই সিস্টেমের মাধ্যমে user experience অনেক ভাল হয়।
👼 Quiz
/