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

4 Ways to Communicate Across Browser Tabs in Realtime

1. Local Storage Events You might have already used LocalStorage, which is accessible across Tabs within the same application origin. But do you know that it also supports events? You can use this feature to communicate across Browser Tabs, where other Tabs will receive the event once the storage is updated. For example, let’s say in one Tab, we execute the following JavaScript code. window.localStorage.setItem("loggedIn", "true"); The other Tabs which listen to the event will receive it, as shown below. window.addEventListener('storage', (event) => { if (event.storageArea != localStorage) return; if (event.key === 'loggedIn') { // Do something with event.newValue } }); 2. Broadcast Channel API The Broadcast Channel API allows communication between Tabs, Windows, Frames, Iframes, and  Web Workers . One Tab can create and post to a channel as follows. const channel = new BroadcastChannel('app-data'); channel.postMessage(data); And oth...

Certbot SSL configuration in ubuntu

  Introduction Let’s Encrypt is a Certificate Authority (CA) that provides an easy way to obtain and install free  TLS/SSL certificates , thereby enabling encrypted HTTPS on web servers. It simplifies the process by providing a software client, Certbot, that attempts to automate most (if not all) of the required steps. Currently, the entire process of obtaining and installing a certificate is fully automated on both Apache and Nginx. In this tutorial, you will use Certbot to obtain a free SSL certificate for Apache on Ubuntu 18.04 and set up your certificate to renew automatically. This tutorial will use a separate Apache virtual host file instead of the default configuration file.  We recommend  creating new Apache virtual host files for each domain because it helps to avoid common mistakes and maintains the default files as a fallback configuration. Prerequisites To follow this tutorial, you will need: One Ubuntu 18.04 server set up by following this  initial ...

Working with Node.js streams

  Introduction Streams are one of the major features that most Node.js applications rely on, especially when handling HTTP requests, reading/writing files, and making socket communications. Streams are very predictable since we can always expect data, error, and end events when using streams. This article will teach Node developers how to use streams to efficiently handle large amounts of data. This is a typical real-world challenge faced by Node developers when they have to deal with a large data source, and it may not be feasible to process this data all at once. This article will cover the following topics: Types of streams When to adopt Node.js streams Batching Composing streams in Node.js Transforming data with transform streams Piping streams Error handling Node.js streams Types of streams The following are four main types of streams in Node.js: Readable streams: The readable stream is responsible for reading data from a source file Writable streams: The writable stream is re...