Adding Search Functionality to a Node Application

Introduction 
 
In this article, we see how to add a search option to our node application. We will be using '$regex' to search for data in Mongo. 
 
Structure Of The Project 
 
          |--------models 
          |                  |-------data.js
          | 
          |---------views
          |                  |-----pages
          |                  |          |-----home.ejs
          |                  | 
          |                  |-----partial
          |                             |-------header.ejs
          |                             |------footer.ejs 
          |---------app.js 
 
Setup The Folder
 
a) Make a new folder using the command prompt. Type the following command followed by the folder name.
  • mkdir search
b) Switch to the new folder
  • cd search
Setup Node In Folder 
 
Now setup node in folder
  • npm init -y
And Its execution we will see package.json file which means node is initialised in the folder.
 
Install Packages
 
Now install the packages which are required for building the application.
  • npm install express ejs mongoose body-parser

Add New Folder
 
After installing the package, add two new folders.
  1. Models
  2. Views
  • The models folder will contain the collections(table) schema.
  • Views folder will contain the ejs pages.
Model
 
In the model folder, add file data.js
  1. var mongoose = require('mongoose');    
  2.     
  3. var bookSchema = new mongoose.Schema({    
  4.     author:{    
  5.         type:String    
  6.     },    
  7.     books:{    
  8.         type:String    
  9.     }    
  10. });    
  11.     
  12. module.exports =  mongoose.model('books',bookSchema);    
Views
 
In the Views folder, add two new folder
  1. Pages
  2. Partial
Partial Folder, add 2 new files
  • header.ejs
  1. <html lang="en">    
  2.     <head>    
  3.         <meta charset="UTF-8">    
  4.         <meta name="viewport" content="width=device-width, initial-scale=1.0">    
  5.         <meta http-equiv="X-UA-Compatible" content="ie=edge">    
  6.         <title>Searching</title>    
  7.         <link rel="stylesheet" href="https://bootswatch.com/4/pulse/bootstrap.css">    
  8.         <link rel="stylesheet" href="https://bootswatch.com/_assets/css/custom.min.css">    
  9.     </head>    
  10.     <body>    
  11.         <nav class="navbar navbar-expand-lg navbar-dark bg-primary fixed-top">    
  12.             <a class="navbar-brand" href="#">Searching</a>    
  13.             <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarColor01" aria-controls="navbarColor01" aria-expanded="false" aria-label="Toggle navigation">    
  14.               <span class="navbar-toggler-icon"></span>    
  15.             </button>    
  16.              <ul class="navbar-nav mr-auto">    
  17.             <li class="nav-item active">    
  18.               <a class="nav-link" href="#">Home <span class="sr-only">(current)</span></a>    
  19.             </li>    
  20.             <li class="nav-item">    
  21.               <a class="nav-link" href="#">Features</a>    
  22.             </li>    
  23.             <li class="nav-item">    
  24.               <a class="nav-link" href="#">Pricing</a>    
  25.             </li>    
  26.             <li class="nav-item">    
  27.               <a class="nav-link" href="#">About</a>    
  28.             </li>    
  29.           </ul>    
  30.             <div class="collapse navbar-collapse nav justify-content-end" id="navbarColor01">    
  31.               <form class="form-inline my-2 my-lg-0" action="/search" method="get">    
  32.                 <input class="form-control mr-sm-2" type="text" name="dsearch" placeholder="Search">    
  33.                 <button class="btn btn-secondary my-2 my-sm-0" type="submit">Search</button>    
  34.               </form>    
  35.             </div>    
  36.           </nav>    
  • footer.ejs
  1. <footer class="fixed-bottom bg-primary">        
  2.     <div class="text-center" style="color: whitesmoke;">@copyright2020</div>      
  3.    </footer>        
  4.    <script src="https://code.jquery.com/jquery-3.4.1.slim.min.js" integrity="sha384-J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n" crossorigin="anonymous"></script>      
  5.    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>      
  6.    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script>      
  7.    </body>      
  8.    </html>    
Now in pages, add home.ejs file
  • home.ejs
  1. <%-include('../partial/header')-%>    
  2. <div class=" container">    
  3.     <center>    
  4.     <div class="card" style="width: fit-content;">    
  5.         <div class="card-body">    
  6.          <form action="/" method="POST">    
  7.                 <div class="row">    
  8.                   <div class="form-group col-md-12">    
  9.                     <input type="text" class="form-control" name="author" placeholder="Auhtor Name" required>    
  10.                   </div>    
  11.                 </div>    
  12.                 <div class="row">    
  13.                     <div class="form-group col-md-12"">    
  14.                         <input type="text" class="form-control" name="book" placeholder="Book Name" required>    
  15.                       </div>    
  16.                 </div>    
  17.                 <button type="submit">Submit</button>    
  18.               </form>     
  19.         </div>    
  20.       </div>    
  21.     </center>    
  22.     <br>    
  23.     <%if(data.length>0){%>    
  24.         <center>    
  25.         <div style="width:auto; border-style: solid;border-color: black;">    
  26.         <table class="table table-border table-hover">    
  27.             <thead class="bg-warning">    
  28.                 <tr>    
  29.                     <th>    
  30.                         s.no    
  31.                     </th>    
  32.                     <th>    
  33.                         Auhtor    
  34.                     </th>    
  35.                     <th>    
  36.                         Books    
  37.                     </th>    
  38.                 </tr>    
  39.             </thead>    
  40.             <tbody>    
  41.                 <%for(var i=0;i< data.length;i++){%>    
  42.                 <tr>    
  43.                     <td>    
  44.                         <%=i+1%>    
  45.                     </td>    
  46.                     <td>    
  47.                      <%=data[i].author%>    
  48.                     </td>    
  49.                     <td>    
  50.                       <%=data[i].books%>    
  51.                     </td>    
  52.                 </tr>    
  53.                 <%}%>    
  54.             </tbody>    
  55.         </table>    
  56.     </div>    
  57.     </center>    
  58.     <%}%>    
  59.              
  60.     </div>    
  61. <%-include('../partial/footer')-%>    
Add New File
 
Add a new file to the project folder.
  • app.js
This will be the entry point of our application.
  1. var mongoose = require('mongoose');  
  2. var bodyParser = require('body-parser');  
  3. var express = require('express');  
  4. var bookModel = require('./models/data');  
  5. //connect to db  
  6. mongoose.connect('mongodb://localhost:27017/searchingg',{useNewUrlParser:true})  
  7. .then(()=>console.log('connectd to db'))  
  8. .catch((err)=>console.log('error ',err))  
  9. //init app  
  10. var app = express();  
  11. //set view engine  
  12. app.set('view engine','ejs');  
  13. ///fetch the data from request  
  14. app.use(bodyParser.urlencoded({extended:false}));  
  15. //default page load  
  16. app.get('/',(req,res)=>{  
  17. try {  
  18. bookModel.find((err,data)=>{  
  19. if(err){  
  20. console.log(err)  
  21. }else{  
  22. res.render('pages/home',{data:data});  
  23. }  
  24. });  
  25. catch (error) {  
  26. console.log(error);  
  27. }  
  28. });  
  29. //search  
  30. app.get('/search',(req,res)=>{  
  31. try {  
  32. bookModel.find({$or:[{author:{'$regex':req.query.dsearch}},{books:{'$regex':req.query.dsearch}}]},(err,data)=>{  
  33. if(err){  
  34. console.log(err);  
  35. }else{  
  36. res.render('pages/home',{data:data});  
  37. }  
  38. })  
  39. catch (error) {  
  40. console.log(error);  
  41. }  
  42. });  
  43. app.post('/',(req,res)=>{  
  44. try {  
  45. var books = new bookModel({  
  46. author:req.body.author,  
  47. books:req.body.book  
  48. });  
  49. books.save((err,data)=>{  
  50. if(err){  
  51. console.log(err)  
  52. }else{  
  53. res.redirect('/');  
  54. }  
  55. })  
  56. catch (error) {  
  57. console.log(error);  
  58. }  
  59. });  
  60. var port = process.env.PORT || 3000;  
  61. app.listen(port,()=>console.log('server run at '+port));   
References
 
 
Download the code from here.