Added New search feature on my blog site!

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'});
 
2) In my userCtrl I added new controller to handle the search function:
 
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" });
  }
}
 
3) Added /search router in my userRouter.js file:
 
router.post('/search', userCtrl.searchBlog);
 
4) Finally created search.ejs to render the results based on the search term in search field:
 
<% 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>
  <% } %>