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.
- Models
- 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
- Pages
- 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
Post a Comment