Skip to main content

How to Add Search Functionality to your 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

var mongoose = require('mongoose');    

var bookSchema = new mongoose.Schema({    
    author:{    
        type:String    
    },    
    books:{    
        type:String    
    }    
});    

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
<html lang="en">    
    <head>    
        <meta charset="UTF-8">    
        <meta name="viewport" content="width=device-width, initial-scale=1.0">    
        <meta http-equiv="X-UA-Compatible" content="ie=edge">    
        <title>Searching</title>    
        <link rel="stylesheet" href="https://bootswatch.com/4/pulse/bootstrap.css">    
        <link rel="stylesheet" href="https://bootswatch.com/_assets/css/custom.min.css">    
    </head>    
    <body>    
        <nav class="navbar navbar-expand-lg navbar-dark bg-primary fixed-top">    
            <a class="navbar-brand" href="#">Searching</a>    
            <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarColor01" aria-controls="navbarColor01" aria-expanded="false" aria-label="Toggle navigation">    
              <span class="navbar-toggler-icon"></span>    
            </button>    
             <ul class="navbar-nav mr-auto">    
            <li class="nav-item active">    
              <a class="nav-link" href="#">Home <span class="sr-only">(current)</span></a>    
            </li>    
            <li class="nav-item">    
              <a class="nav-link" href="#">Features</a>    
            </li>    
            <li class="nav-item">    
              <a class="nav-link" href="#">Pricing</a>    
            </li>    
            <li class="nav-item">    
              <a class="nav-link" href="#">About</a>    
            </li>    
          </ul>    
            <div class="collapse navbar-collapse nav justify-content-end" id="navbarColor01">    
              <form class="form-inline my-2 my-lg-0" action="/search" method="get">    
                <input class="form-control mr-sm-2" type="text" name="dsearch" placeholder="Search">    
                <button class="btn btn-secondary my-2 my-sm-0" type="submit">Search</button>    
              </form>    
            </div>    
          </nav>    
  • footer.ejs
<footer class="fixed-bottom bg-primary">        
    <div class="text-center" style="color: whitesmoke;">@copyright2020</div>      
   </footer>        
   <script src="https://code.jquery.com/jquery-3.4.1.slim.min.js" integrity="sha384-J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n" crossorigin="anonymous"></script>      
   <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>      
   <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script>      
   </body>      
   </html>    

Now in pages, add home.ejs file

  • home.ejs
<%-include('../partial/header')-%>    
<div class=" container">    
    <center>    
    <div class="card" style="width: fit-content;">    
        <div class="card-body">    
         <form action="/" method="POST">    
                <div class="row">    
                  <div class="form-group col-md-12">    
                    <input type="text" class="form-control" name="author" placeholder="Auhtor Name" required>    
                  </div>    
                </div>    
                <div class="row">    
                    <div class="form-group col-md-12"">    
                        <input type="text" class="form-control" name="book" placeholder="Book Name" required>    
                      </div>    
                </div>    
                <button type="submit">Submit</button>    
              </form>     
        </div>    
      </div>    
    </center>    
    <br>    
    <%if(data.length>0){%>    
        <center>    
        <div style="width:auto; border-style: solid;border-color: black;">    
        <table class="table table-border table-hover">    
            <thead class="bg-warning">    
                <tr>    
                    <th>    
                        s.no    
                    </th>    
                    <th>    
                        Auhtor    
                    </th>    
                    <th>    
                        Books    
                    </th>    
                </tr>    
            </thead>    
            <tbody>    
                <%for(var i=0;i< data.length;i++){%>    
                <tr>    
                    <td>    
                        <%=i+1%>    
                    </td>    
                    <td>    
                     <%=data[i].author%>    
                    </td>    
                    <td>    
                      <%=data[i].books%>    
                    </td>    
                </tr>    
                <%}%>    
            </tbody>    
        </table>    
    </div>    
    </center>    
    <%}%>    

    </div>    
<%-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.

var mongoose = require('mongoose');  
var bodyParser = require('body-parser');  
var express = require('express');  
var bookModel = require('./models/data');  
//connect to db  
mongoose.connect('mongodb://localhost:27017/searchingg',{useNewUrlParser:true})  
.then(()=>console.log('connectd to db'))  
.catch((err)=>console.log('error ',err))  
//init app  
var app = express();  
//set view engine  
app.set('view engine','ejs');  
///fetch the data from request  
app.use(bodyParser.urlencoded({extended:false}));  
//default page load  
app.get('/',(req,res)=>{  
try {  
bookModel.find((err,data)=>{  
if(err){  
console.log(err)  
}else{  
res.render('pages/home',{data:data});  
}  
});  
} catch (error) {  
console.log(error);  
}  
});  
//search  
app.get('/search',(req,res)=>{  
try {  
bookModel.find({$or:[{author:{'$regex':req.query.dsearch}},{books:{'$regex':req.query.dsearch}}]},(err,data)=>{  
if(err){  
console.log(err);  
}else{  
res.render('pages/home',{data:data});  
}  
})  
} catch (error) {  
console.log(error);  
}  
});  
app.post('/',(req,res)=>{  
try {  
var books = new bookModel({  
author:req.body.author,  
books:req.body.book  
});  
books.save((err,data)=>{  
if(err){  
console.log(err)  
}else{  
res.redirect('/');  
}  
})  
} catch (error) {  
console.log(error);  
}  
});  
var port = process.env.PORT || 3000;  
app.listen(port,()=>console.log('server run at '+port));  

Comments

Popular posts from this blog

How to use Ngx-Charts in Angular ?

Charts helps us to visualize large amount of data in an easy to understand and interactive way. This helps businesses to grow more by taking important decisions from the data. For example, e-commerce can have charts or reports for product sales, with various categories like product type, year, etc. In angular, we have various charting libraries to create charts.  Ngx-charts  is one of them. Check out the list of  best angular chart libraries .  In this article, we will see data visualization with ngx-charts and how to use ngx-charts in angular application ? We will see, How to install ngx-charts in angular ? Create a vertical bar chart Create a pie chart, advanced pie chart and pie chart grid Introduction ngx-charts  is an open-source and declarative charting framework for angular2+. It is maintained by  Swimlane . It is using Angular to render and animate the SVG elements with all of its binding and speed goodness and uses d3 for the excellent math functio...

Understand Angular’s forRoot and forChild

  forRoot   /   forChild   is a pattern for singleton services that most of us know from routing. Routing is actually the main use case for it and as it is not commonly used outside of it, I wouldn’t be surprised if most Angular developers haven’t given it a second thought. However, as the official Angular documentation puts it: “Understanding how  forRoot()  works to make sure a service is a singleton will inform your development at a deeper level.” So let’s go. Providers & Injectors Angular comes with a dependency injection (DI) mechanism. When a component depends on a service, you don’t manually create an instance of the service. You  inject  the service and the dependency injection system takes care of providing an instance. import { Component, OnInit } from '@angular/core'; import { TestService } from 'src/app/services/test.service'; @Component({ selector: 'app-test', templateUrl: './test.component.html', styleUrls: ['./test.compon...

How to solve Puppeteer TimeoutError: Navigation timeout of 30000 ms exceeded

During the automation of multiple tasks on my job and personal projects, i decided to move on  Puppeteer  instead of the old school PhantomJS. One of the most usual problems with pages that contain a lot of content, because of the ads, images etc. is the load time, an exception is thrown (specifically the TimeoutError) after a page takes more than 30000ms (30 seconds) to load totally. To solve this problem, you will have 2 options, either to increase this timeout in the configuration or remove it at all. Personally, i prefer to remove the limit as i know that the pages that i work with will end up loading someday. In this article, i'll explain you briefly 2 ways to bypass this limitation. A. Globally on the tab The option that i prefer, as i browse multiple pages in the same tab, is to remove the timeout limit on the tab that i use to browse. For example, to remove the limit you should add: await page . setDefaultNavigationTimeout ( 0 ) ;  COPY SNIPPET The setDefaultNav...