Posted by Masis on Wed Feb 15 2023
Added new search feature on my blog site and pushed the changes in my git repository:
https://github.com/1983blackmesa/blog-dev
1) In my mongodb schema I had to index the postSchema:
postSchema.index({ title: 'text', content: 'text', author: 'text'});
searchBlog: async (req, res) => {
try {
const searchTerm = req.body.searchTerm;
const blog = await Post.find( { $text: { $search: searchTerm, $diacriticSensitive: true }} )
res.render('search', { title: 'Blog - Search', blog } );
} catch (err) {
res.satus(500).send({message: err.message || "Error" });
}
}
router.post('/search', userCtrl.searchBlog);
<% if(blog != '') { %>
<% blog.forEach(function(blog, index){ %>
<a href="/posts/<%- blog._id %>" class="col text-center category__link">
<div class="pt-1"><%- blog.title %></div>
<div class="pt-1"><%- blog.content %></div>
<div class="pt-1"><%- blog.author %></div>
</a>
<% }) %>
<% } else { %>
<p>No items found.</p>
<% } %>