Currently, I am working on integrating a search feature into a MERN stack application. The idea is to utilize the searchWord extracted from req.params.searchWord
and fetch results containing that specific searchWord.
Although my existing code serves its purpose effectively, I'm curious to know if it's feasible to leverage the functionality of filteredData
using mongoose's aggregate
function.
const getQuoteAuthorSearchedResult = async (req, res) => {
try {
const searchWord = req.params.searchWord
const uniqueQuoteAuthors = await QuoteModel.aggregate().group({
_id: "$author",
count: { $sum: 1 },
});
const filteredData = await uniqueQuoteAuthors.filter((value) => {
return value._id.toLowerCase().includes(searchWord.toLowerCase());
});
res.status(200).json({
results: filteredData
})
} catch (error) {
res.status(401).json({ success: false });
}
};
This is how my data appears:
[
{
"_id": "Martin Luther King Jr",
"count": 1
},
{
"_id": "Friedrich Nietzsche",
"count": 1
},
{
"_id": "Marcus Tullius Cicero",
"count": 1
},
{
"_id": "Andre Gide",
"count": 1
},
...
]