Node.js7 min read
Search Implementation
Implement search functionality. Learn full-text search and fuzzy matching.
Michael Torres
December 19, 2025
0.0k0
Search Implementation
MongoDB Text Search
const productSchema = new mongoose.Schema({
name: String,
description: String
});
productSchema.index({ name: 'text', description: 'text' });
const Product = mongoose.model('Product', productSchema);
app.get('/search', async (req, res) => {
const query = req.query.q;
const products = await Product.find(
{ $text: { $search: query } },
{ score: { $meta: 'textScore' } }
).sort({ score: { $meta: 'textScore' } });
res.json(products);
});
Regex Search
app.get('/search', async (req, res) => {
const query = req.query.q;
const products = await Product.find({
$or: [
{ name: { $regex: query, $options: 'i' } },
{ description: { $regex: query, $options: 'i' } }
]
});
res.json(products);
});
With Filters
app.get('/search', async (req, res) => {
const { q, category, minPrice, maxPrice } = req.query;
const query = {};
if (q) {
query.$text = { $search: q };
}
if (category) {
query.category = category;
}
if (minPrice || maxPrice) {
query.price = {};
if (minPrice) query.price.$gte = parseInt(minPrice);
if (maxPrice) query.price.$lte = parseInt(maxPrice);
}
const products = await Product.find(query);
res.json(products);
});
Autocomplete
app.get('/autocomplete', async (req, res) => {
const query = req.query.q;
const suggestions = await Product.find({
name: { $regex: `^${query}`, $options: 'i' }
})
.limit(10)
.select('name');
res.json(suggestions.map(p => p.name));
});
Key Takeaway
Use MongoDB text index for full-text search. Regex for simple searches. Combine search with filters. Add autocomplete for better UX.
#Node.js#Search#MongoDB#Full-text