Open mahendra785 opened 2 months ago
Implement a search feature that allows users to search for specific values in the responses
collection. When a user clicks the search button or presses enter, the app should search the database for the value entered and return matching documents.
Express Route Handler Example:
const express = require('express');
const router = express.Router();
const Response = require('../models/responseModel'); // Assuming the schema is in `models/responseModel.js`
// GET route to handle search queries
router.get('/search', async (req, res) => {
try {
// 1. Capture the search query from the request query parameters.
const searchQuery = req.query.q;
// 2. If no search query is provided, return an error response.
if (!searchQuery) {
return res.status(400).json({ error: "Search query is required." });
}
// 3. Search the 'responses' collection for matching documents.
// This example uses a case-insensitive partial match on the 'name', 'email', or 'message' fields.
const searchResults = await Response.find({
$or: [
{ name: { $regex: searchQuery, $options: 'i' } },
{ email: { $regex: searchQuery, $options: 'i' } },
{ message: { $regex: searchQuery, $options: 'i' } }
]
});
// 4. Return the search results.
res.status(200).json(searchResults);
} catch (error) {
// 5. Handle any errors.
res.status(500).json({ error: "Server error. Please try again later." });
}
});
module.exports = router;
Implement a search feature that allows users to search for specific values in the responses table. When a user clicks the search button or presses enter, the app should search the database for the value entered. Create a search button that triggers this functionality.