Search Implementation
Implement search functionality. Learn full-text search and fuzzy matching.
Search Implementation
MongoDB Text Search
```javascript 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
```javascript 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
```javascript 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
```javascript 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.