You are on page 1of 24

Name: Vineet jain Reg. No.

: 20BIT0342

Assessment-4

Using Node JS, Express JS, Mongo DB

1. Consider a client requests the server to view his profile, which is available in “19BIT0--
info.html”. Implement it using the Node.js file system module.

Ex1_20BIT0342.html:
<html>
<head>
<title>Vineet jain 20BIT0342</title>
</head>
<body>
<h1>Profile</h1>
<p>Name: VINEET JAIN</p>
<p>Reg. no.: 20BIT0342</p>
<p>Branch: Information Technology</p>
<p>Age: 20</p>
<p>Semester: 3rd</p>
<p>Subject: Web technologies</p>
</body>
</html>

Ex1_20BIT0342.js:
var http =
require('http'); var fs =
require('fs');
http.createServer(function (req, res) {
fs.readFile('Ex1_20BIT0342.html', function(err, data)
{ res.writeHead(200, {'Content-Type': 'text/html'});
res.write(data);
return res.end();
});
}).listen(8080);
2. Develop a small application for the Basketball scoreboard using Node.js event handling.
Here, we have a scoreKeeper.on() event-listener listening for an event that would
indicate a basket being made. Each scoring attempt is a call of
the shoot_a_basket function. If the ball goes in the net (indicated by a true value for the
shot), scoreKeeper.emit() is called, which alerts all event-listeners
event listeners listening for the
make_basket event announcement to run their callback function, and passes the value of
the basket made. Display the scores of each team.
Ex2_20BIT3042.js:
const events = require('events');
const scoreKeeper = new events.EventEmitter();
var score1 = 0;
var score2 = 0;
function
make_basket(team){
if(team==="A"){
score1 += 1;
}else{
score2 += 1;
}
console.log("Score of team A is" + score1);
console.log("Score of team B is" + score2);
console.log(" ");
}
scoreKeeper.on('make_basket',make_basket);
,make_basket);
function scored(team){
scoreKeeper.emit('make_basket',team);
,team);
}
scored("B");
scored("A");
scored("A");
scored("B");
scored("A");

3. Create a MongoDB “Student” database and do the following operations:


1. Insert a new student with a name: Dora

2. Insert a new student with a name: Sinchan and id=2 (integer)

3. Insert a new student with a name: Angush, the midterm score of 80, and a final
score of 100. Scores should be embedded in a sub-document like this:
scores:{midterm:0,final:0}.

4. Display the list of students who scored between greater than 50 in the midterm.

5. Search for students that have scored between [50,80] in midterm AND [80,100] in
the final exam.

6. Update the student Sinchan that you created back in exercise 2 to have a midterm
score of 50 and a final score of 100 respectively.

7. Sort according to the final score in descending order and display name and score
without objectID.
8. Delete user Angush that you created back in exercise 3.

9. Delete all users with a midterm score of less than 80.

4. i) Design an application using node.js and MongoDB to perform the following


operations in a student collection with a name, age, DOB, and year of admission.
ii) Insert multiple records into the collection.

iii) Sort all documents in the student collection

iv) Update the document of a student with name=’Kevin’ to age=25

v) Limit the result to 4 documents


vi) Query the document based on age>25
Ex4_20BIT0342.js
const mongoose = require("mongoose");
mongoose.connect("mongodb://localhost:27017/Class",{useNewUrlParser: true});
const studentSchema = new mongoose.Schema({
name: String,
age: Number,
dob: Date,
yearofadm: Number
});
const Student = mongoose.model("Student",studentSchema);
const PARAS = new Student({
name: "VINEET JAIN",
age: 20,
dob: "2002-12-017",
yearofadm: 2020
});
const vaibhav = new
Student({ name: "Vaibhav ",
age: 19,
dob: "2001-11-06",
yearofadm: 2021
});
const piyush = new
Student({ name: "Piyush
Kumar",
age: 26,
dob: "1994-02-10",
yearofadm: 2014
});
const dhiraj = new
Student({ name: "Dhiraj
Ganesh", age: 30,
dob: "1990-09-29",
yearofadm: 2010
});
const aarush = new
Student({ name: "Aarush
Singh",
age: 15,
dob: "2005-12-06",
yearofadm: 2024
});

Student.insertMany([PARAS,vaibhav,piyush,dhiraj,aarush],function(err){
if(err){
console.log(err);
}else{
console.log("successfully saved all the students")
}
});

Student.find(function(err,
student){ if(err){
console.log(err);
}else{
student.forEach((student) =>
{ console.log(student.name)
});
}
});

var sortage = {age: 1};


Student.find({},function(err,result){
if(err){
console.log("error query");
}else{
console.log(result);
}
}).sort(sortage);

Student.updateOne({name: "Kevin"},{age: 25},function(err){


if(err){
console.log(err);
}else{
console.log('updation completed');
}
});
Student.find(function(err,
student){ if(err){
console.log(err);
}else{
student.forEach((student) =>
{ console.log(student);
});
}
}).limit(4);

Student.find({ 'age': {$gt:25} }, function (err, result)


{ if (err) console.log(err);
console.log(result);
});
5. i) Create a web application with username in HTML and node.js using the express
framework to handle different types of HTTP requests namely get, post, put, options, and delete.
ii) Provide different route paths for each of the requests.
iii) Display the different request types with the username in the browser when the application is
executed.
CODE:
EX5_20BT0342

<!DOCTYPEhtml>
<title>20BIT0342</title>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8"/>
<title></title>
</head>
<body>
<form action="/submit-student-data"method="post"> First Name: <input
name="firstName"type="text"/><br/> Last Name: <input
name="lastName"type="text"/><br/>
<input type="submit"/>
</form>
</body>
</html>
var express = require('express'); var app = express();
var bodyParser = require("body-parser"); app.use(bodyParser.urlencoded({
extended: false })); app.get('/', function (req, res) { res.sendFile('index.html');
});
app.post('/submit-student-data', function (req, res) {
var name = req.body.firstName + ' ' + req.body.lastName; res.send(name + ' Submitted
Successfully!');
});
var server = app.listen(5000, function () { console.log('Node server is running..');
});
6. i) Write an HTML and node.js program for creating and storing session
information of the user. The HTML page contains username, password, remember me next time
checkbox option and a login button.
ii) Assume, the user name and password are already registered in the node.js server. iii) Perform the
a. If the user enters an invalid user username or password, display an appropriate error
message.
b. After successful login, display a welcome message.
c. Allow the user to enter the username and password for 3 times.
If the user enters username and password more than 3 times, display the message “you are
blocked”.
Ex6_20BIT0342.html
<html>
<body>
<form action="http://localhost:8081/login" method="GET">
Username: <input type="text" name="username"> <br>
Password: <input type="text" name="passwords">
Remeber Me:<input type="radio" value="yes" name="remember">Yes
<input type="radio" value="no" name="remember">No
<input type="submit" value="Submit">
</form>
</body>
</html>

Ex6_20BIT0342.js
var express = require('express');
var app = express();
var cookieParser = require('cookie-parser');
app.use(cookieParser());
var session = require('express-session');
app.use(session({secret: "Shh, its a secret!"}));
app.use(express.static('public'));
app.use(function(req, res, next) {
console.log('%s %s', req.method, req.url);
next();
});
app.get('/', function (req, res) {
if (req.session.rememberme=="yes")
{
res.redirect('/login?username=PARAS&passwords=123456');
}
else
{
res.sendFile( dirname + "/" + "Ex6_19BIT0378.html" );
}
});

app.get('/login', function (req, res) {

res.cookie("Username", "PARAS");
res.cookie("Password", "123456");
username=req.query.username;
passwords=req.query.passwords;
remember=req.query.remember;
if(req.cookies['Username']!=username ||
req.cookies['Password']!=passwords)
{
if(req.session.page_views)
{
req.session.page_views++;
}
else
{
req.session.page_views = 1;
}
}
if(req.session.page_views>=4)
var k="<h1>you are blocked</h1>";
else
{
if(req.cookies['Username']==username &&
req.cookies['Password']==passwords)
{
if(remember=="yes")
{
req.session.rememberme="yes";
}
else
req.session.rememberme="yes";
var k="<h1>Welcome!</h1>";
}
else
var k="<h1>Wrong!</h1>";
}

res.end(k);
});
var server = app.listen(8081, function () {
var host = server.address().address;
var port = server.address().port;
console.log("Example app listening at http://%s:%s", host, port);
});
7. A company database maintains the vehicle information of their employees. It stores the information
empid(int), vehicle number(string/int), owner name(string), brand name(string) and year of
purchase(int).
a) Create a Collection in MongoDB with the above fields and insert 10 documents at least.
b) Create an HTML form using NodeJS and express for the employee to change the details when
he/she changes his/her vehicle by submitting his/her empid and the new vehicle details. The form
creation should use CSS for making it interactive and Use ExpressJS at the server-side.
Ex7_20BIT0342.html
<!DOCTYPE html>
<html>
<head>
<title>Simple login form</title>
<link
href="https://fonts.googleapis.com/css?family=Roboto:300,400,500,700"
rel="stylesheet">
<style>
html, body {
display: flex;
justify-content: center;
font-family: Roboto, Arial, sans-serif;
font-size: 15px;
}
form {
border: 5px solid #f1f1f1;
}
input[type=text], input[type=number] {
width: 100%;
padding: 16px 8px;
margin: 8px 0;
display: inline-block;
border: 1px solid #ccc;
box-sizing: border-box;
}
button {
background-color: #8ebf42;
color: white;
padding: 14px 0;
margin: 10px 0;
border: none;
cursor: grabbing;
width: 100%;
}
h1 {
text-align:center;
fone-size:18;
}
button:hover {
opacity: 0.8;
}
.formcontainer {
text-align: left;
margin: 24px 50px 12px;
}
.container {
padding: 16px 0;
text-align:left;
}
</style>
</head>
<body>
<form action="/change" method="post">
<h1>Employee Form</h1>
<div class="formcontainer">
<hr/>
<div class="container">
<label for="uname"><strong>Enter Your Employee
ID</strong></label>
<input type="text" placeholder="Enter Your Employee ID"
name="empid" required>
<label for="owner"><strong>Enter Owner Name</strong></label>
<input type="text" placeholder="Enter Owner Name" name="owner"
required>
<label for="vehino"><strong>Enter Your Vehicle
Number</strong></label>
<input type="number" placeholder="Enter Your Vehicle Number"
name="vehino" required>
<label for="brand"><strong>Enter Brand Name</strong></label>
<input type="text" placeholder="Enter Brand Name" name="brand"
required>
<label for="year"><strong>Enter Year Of
Purchase</strong></label>
<input type="number" placeholder="Enter Year Of Purchase"
name="year" required>
</div>
<button type="submit">Submit</button>
</form>
</body>
</html>

Ex7_20BIT0342.js
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var urlencodedParser = bodyParser.urlencoded({ extended: true });
var MongoClient = require('mongodb').MongoClient;
app.get('/', function (req, res) {
res.sendFile( dirname + "/" + "Ex7_19BIT0378.html" );
})
app.post('/change',urlencodedParser, function (req, res) {
// Prepare output in JSON format

PARAS = {
empid: "1",
vehino: "5426",
owner: "PARAS",
brand: "Maruti",
year: 2020
};
vaibhav = {
empid: "2",
vehino: "7928",
owner: "Vaibhav",
brand: "TATA",
year: 2019
};
piyush = {
empid: "3",
vehino: "3415",
owner: "Raghav",
brand: "Hyundai",
year: 2018
};
dhiraj = {
empid: "4",
vehino: "3497",
owner: "Dhiraj",
brand: "Mercedes",
year: 2020
};
aarush = {
empid: "5",
vehino: "7319",
owner: "Aarush",
brand: "Audi",
year: 2017
};
shivangi = {
empid: "6",
vehino: "A101",
owner: "Shivangi",
brand: "VolkesWagon",
year: 2014
};
aakash = {
empid: "7",
vehino: "2098",
owner: "Aakash",
brand: "Honda",
year: 2019
};
binod = {
empid: "8",
vehino: "2192",
owner: "Binod",
brand: "BMW",
year: 2020
};
khushi = {
empid: "9",
vehino: "0214",
owner: "Khushi",
brand: "Renault",
year: 2000
};
priya = {
empid: "10",
vehino: "1002",
owner: "Priya",
brand: "Chevrolet",
year: 2020
};
response = {
empid:req.body.empid,
vehino:req.body.vehino,
brand:req.body.brand,
year:req.body.year,
owner:req.body.owner
};
MongoClient.connect('mongodb://localhost:27017/', function(err, db)
{
if (err) throw err;
console.log("Connected to Database");
var dbo=db.db("mydb4");
//insert record
dbo.collection('employees').insert([PARAS,vaibhav,piyush,dhiraj,aarush,s
hivangi,aakash,binod,khushi,priya], function(err, result)
{
if (err) throw err;
console.log("10 document inserted in your mongodb database" );
dbo.collection('employees').updateOne({empid:response.empid},{$set:{"own
er":response.owner,"vehino":response.vehino,"brand":response.brand,"year
":response.year}},function(err,result){
if(err) throw err;
console.log(result);
});
});
});
console.log(response);
res.end(JSON.stringify(response));
});
var server = app.listen(8080, function () {
var host = server.address().address;
var port = server.address().port;
console.log("Example app listening at http://%s:%s//", host, port);
});

Console.log:
8. The IPL website has a MongoDB database of players. The following information about the players
are stored – name, IPL franchise, country, bid_amount
a) Create an HTML form with appropriate CSS containing text field. Name the text field as find
and radio button(IPL, country, bid). Name the radio button as find_details. On submitting an
Express JS in Node server-side code is called that displays information about
b) The player if the name of the player is entered in find and no radio button is checked.
c) The players of a particular country representing IPL. If the radio button IPL is clicked and country
name is entered in find
d) The player name, IPL franchise, and country for the player whose bid amount is greater than or
equal or bid amount given in find. if the bid radio button is checked and the bid amount is entered
in find.
e) Store the data in MongoDB database

Ex8_20BIT0342.html
<!DOCTYPE html>
<html>
<head>
<title>Simple login form</title>
<link
href="https://fonts.googleapis.com/css?family=Roboto:300,400,500,700"
rel="stylesheet">
<style>
html, body {
display: flex;
justify-content: center;
font-family: Roboto, Arial, sans-serif;
font-size: 15px;
}
form {
border: 5px solid #f1f1f1;
}
input[type=text], input[type=number] {
width: 100%;
padding: 16px 8px;
margin: 8px 0;
display: inline-block;
border: 1px solid #ccc;
box-sizing: border-box;
}
button {
background-color: #8ebf42;
color: white;
padding: 14px 0;
margin: 10px 0;
border: none;
cursor: grabbing;
width: 100%;
}
h1 {
text-align:center;
fone-size:18;
}
button:hover {
opacity: 0.8;
}
.formcontainer {
text-align: left;
margin: 24px 50px 12px;
}
.container {
padding: 16px 0;
text-align:left;
}
</style>
</head>
<body>
<form action="/login" method="GET">
<h1>IPL Form</h1>
<div class="formcontainer">
<hr/>
<div class="container">
<label for="find"><strong>Find:</strong></label>
<input type="text" name="find">
<label for="find_details"><strong>Select:</strong></label>
<input type="radio" name="find_details" value="IPL">IPL
<input type="radio" name="find_details"
value="country">Country
<input type="radio" name="find_details" value="bid">Bid
</div>
<button type="submit">Submit</button>
</form>
</body>
</html>

Ex8_20BIT0342.js
var express=require('express');
var app=express();
var MongoClient=require('mongodb').MongoClient;
app.get('/', function (req, res) {
res.sendFile( dirname + "/" + "Ex8_20BIT0342.html" );
})
app.get("/login",function(req,res){
response={
choice:req.query.find_details,
find:req.query.find
};
console.log(response);
MongoClient.connect('mongodb://localhost:27017/',function(err,db){
if(err) throw err;
var dbo=db.db("IPL_Players");

if(response.choice=="IPL")
{

dbo.collection('Players').find({country:response.find},{projection:
{_id:0}}).toArray(function(err,result){
if(err) console.log(err);
res.end(JSON.stringify(result));
console.log(result);
});
}
else if(response.choice=="bid")
{

dbo.collection('Players').find({'bid':{$gte:Number(response.find)}}
,{projection:{_id:0}}).toArray(function(err,result){
if(err) console.log(err);
res.end(JSON.stringify(result));
console.log(result);
});
}
else
{

dbo.collection('Players').find({name:response.find},{projection:{_i
d:0}}).toArray(function(err,result){
if(err) console.log(err);
res.end(JSON.stringify(result));
console.log(result);
});
}
});
});
var server = app.listen(8080, function () {
var host = server.address().address;
var port = server.address().port;
console.log("Example app listening at http://%s:%s//", host, port);
});

Mongo Database:

You might also like