0% found this document useful (0 votes)
39 views42 pages

MSD Lab Programs

The document contains multiple exercises focused on JavaScript and Node.js programming, including creating a movie ticket booking system, implementing classes and inheritance, building a login module, and demonstrating Node.js server functionality. It also covers middleware implementation in Express.js and connecting to MongoDB using Mongoose. Each exercise includes specific aims and source code examples to illustrate the concepts.

Uploaded by

tmsubhashvaleti
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
39 views42 pages

MSD Lab Programs

The document contains multiple exercises focused on JavaScript and Node.js programming, including creating a movie ticket booking system, implementing classes and inheritance, building a login module, and demonstrating Node.js server functionality. It also covers middleware implementation in Express.js and connecting to MongoDB using Mongoose. Each exercise includes specific aims and source code examples to illustrate the concepts.

Uploaded by

tmsubhashvaleti
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Exercise -1

AIM: a).Write a JavaScript code to book movie tickets online and


calculate the total price
based on the 3 conditions:
(i) If seats to be booked are not more than 2, the cost per ticket
remains Rs. 150.
(ii) If seats are 6 or more, booking is not allowed.
(iii) If seats to be booked are more than 2 but less than 5, based on
the number of
seats booked. (festival season discount of 10% )
SOURCE CODE: [Link]
<!DOCTYPE html>
<html>
<head>
<title>Booking Movie Details</title>
<style>
.mydiv {
text-decoration: bold;
text-align: left;
width: 1000px;
border: 1px solid purple;
text-align: center;
color:red;
background-color:#c7f15e;
font-family: Arial;
font-size: 20px;
}
</style>
</head>
<body bgcolor="orange">
<center>
<br><br>
<h1 style="color:blue;font-size: 50px;"><b>Theatre Mohan,
Chirala</h1>
<div class="mydiv">
<h2><u>Your Ticket Details:</u> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
Date: <input type="date">
<br>
<script>
let ticket_price = 150; // ticket price
var seats=prompt("Enter the Number of Tickets");
var totalcost = ticket_price * seats;
[Link]("<br>The Number of Seats Booked: " +seats);
[Link]("<br>Total Cost :Rs."+totalcost);
for (let i = 1; i<=seats; i++)
{
if (seats<=2)
{
[Link]('<br>The cost per '+seats+ ' ticket(s) Rs: '+totalcost);
break;
}
else if (seats >= 6)
{
[Link]('<br>Booking is not allowed for 6 or more Tickets');
break;
}
else if ( seats> 2 && seats <5)
{
var discount = (totalcost *10)/100
[Link]('<br>Tickets Count is >2 and <5, <br>Festival Season
Discount 10%, Cost is : Rs. ' + (totalcost - discount));
[Link]('<br>For '+seats+' Tickets ,you need to pay: Rs. '+
(totalcost - discount) +' instead of Rs. '+totalcost);
break;
}
}</script> </div></center></body></html>

AIM:
Write a JavaScript to create an array of objects having movie details.
The object should include the movie name, starring, language, and
ratings. Render the details of movies on the page using the array.
SOURCE CODE: [Link]
<!DOCTYPE html>
<html>
<head>
<title>Pan Indian Movies</title>
<style>
.mydiv {
text-decoration: bold;
text-align: left;
margin-top: 10px;
height: 200px;
width: 1450px;
border: 4px solid purple;
text-align: left;
color: red;
background-color: #c7f15e;
font-family: verdana;
font-size:20pt;
padding: 15px;
}
</style>
</head>
<body bgcolor="lightblue">
<center>
<h1 style="color:red;font-size:38pt;"><b>Render the Details of Telugu
Pan Indian Movies </b></h1>
<img src="[Link]" width="360px" height="400px" > &nbsp;&nbsp;
&nbsp;&nbsp;&nbsp;
<img src="[Link]" width="360px" height="400px" >
&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;
<img src="[Link]" width="360px" height="400px">
<div class="mydiv">
<p id="movie-list"></p>
<script>

const movies=[
{ name: 'Kalki', starring: 'Prabhas,Deepika Padukone,Disha Patani',
director: 'Nag Ashwin', language: 'Pan India', ratings: 9.6 },
{ name: 'Devara', starring: 'Jr. N.T. R ,Janhvi Kapoor,Saif Ali Khan',
director: 'Koratala Siva',language: 'Pan India', ratings: 9.5 },
{ name: 'Pushpa2', starring: 'Allu Arjun,Rashmika,Fahadh Faasil',
director:'Sukumar',language: 'Pan India', ratings: 9.7 }
];
const movieList = [Link]('movie-list');
[Link](movie => {
const p = [Link]('p');
[Link] = `${[Link]} (${[Link]}), Starring: $
{[Link]}, Director: ${[Link]},Ratings:$
{[Link]}`;
[Link](p);
});
</script>
</center>
</div>
</body>
</html>
Exercise -2
AIM:
a).Write a JavaScript to create an Employee class extending from a base class
Person.
Hints:
(i) Create a class Person with name and age as attributes.
(ii) Add a constructor to initialize the values
(iii) Create a class Employee extending Person with additional attributes role
SOURCE CODE: [Link]

<!DOCTYPE html>
<html>
<head>
<title> Employee Details</title>
<style>
.mydiv {
text-decoration: bold;
text-align: left;
margin-top: 10px;
width: 700px;
height: 550px;
border: 6px solid purple;
text-align: center;
color: blue;
background-color: #c7f15e;
font-family: verdana;
font-size:25pt;
}
</style>
</head>
<body bgcolor="pink">
<center>
<h1 style="color:red;font-size:40pt;"><b>Creating and Inheriting Classes
</b></h1>
<div class="mydiv">
<script type="text/javascript">
class Person
{
constructor(name, age,empid)
{
[Link] = name;
[Link] = age;
[Link] = empid;
}
}
class Employee extends Person
{
constructor(name, age,empid,job,salary,mobileno,emailid,role)
{
super(name, age,empid);
[Link]=job;
[Link]=salary;
[Link]=mobileno;
[Link]=emailid;
[Link] = role;
}
getEmployeeDetails()
{
[Link]("<br><br>*** EMPLOYEE INFORMATION ***<br>");
[Link](" <br> Name : "+[Link]);
[Link](" <br> Age : ",[Link]);
[Link]("<br> Empid : ",[Link]);
[Link]("<br> Job : ",[Link]);
[Link]("<br> Salary : ",[Link]);
[Link]("<br>Mobile No : ",[Link]);
[Link]("<br>Email Id : ",[Link]);
[Link]("<br> Job Role : ",[Link]);
}
}
let employee1 = new Employee("Karth", 25,"Sacet180", "Software",100000,
9110307238,"Dr [Link]@[Link]","Software Manager");
[Link]();
</script>
</div>
</body>
</html>

AIM:
b).Write a JavaScript to validate the user by creating a login module. Hints:
(i) Create a file [Link] with a User class.
(ii) Create a validate method with username and password as arguments.
(iii) If the username and password are equal it will return "Login Successful"
else will return "Unauthorized access".
SOURCE CODE: [Link]

<!DOCTYPE html>
<html>
<head>
<title>Creating a Login Module</title>
<style>
.mydiv {
text-decoration: bold;
margin-top: 10px;
width: 600px;
height:400px;
border: 5px solid purple;
text-align: center;
color: blue;
background-color: #c7f15e;
font-family: verdana;
font-size:25pt;
padding: 20px;
}
</style>
</head>
<body style="background-color:#F0E68C;">
<center>
<h1 style="color:red;font-size:35pt;">Creating a Login Module</h1>
<div class="mydiv">
<script src="[Link]">
</script>
<form id="login-form">
<br><br>
<label for="username"><b>Username:</label>
<input type="text" id="username" name="username"><br><br>
<label for="password"><b>Password:</label>
<input type="password" id="password" name="password"><br><br>
&nbsp;&nbsp;&nbsp;&nbsp;<input type="submit" value="Login"
onclick="validate()">&nbsp;&nbsp;&nbsp;<input type="reset" value="Reset">
<br><br>
<div id="result"></div>
</center>
</body>
</html>

[Link]
class User {
constructor(username, password)
{
[Link] = username;
[Link] = password;
}
validate() {
if ([Link] === [Link]) {
return "Login Successful!";
}
else {
return "Unauthorized Access!";
}
}
}
function validate() {
form = [Link]('login-form');
resultDiv = [Link]('result');
username = [Link]('username').value;
password = [Link]('password').value;
[Link]();
const user = new User(username, password);
const result = [Link]();
[Link] = result;
}

Exercise -3
a).Write a program to show the workflow of JavaScript code
executable by creating web
server in [Link].
SOURCE CODE:
const http = require("http"); // Importing the http module
var server = [Link]((req,res) => { // Creating server
[Link]( ` // Sending the response
<!DOCTYPE html>
<html>
<head>
<title>[Link] Server</title>
</head>
<body bgcolor="pink">
<br><br><center><h1><font color="blue" size="25">Hello World!
Welcome To CSE! </font></h1>
<h1><font color="red" size="20">[Link]'s College of
Engineering&Technology! </font></h1>
<h2><font color="green" size="15">This page is served by a simple
[Link] server. </font></h2>
</center></body>
</html>
`);
[Link](); // [Link]() function is used to end the response process.
});
[Link](3000); // server listening to port 3000 of your computer.
[Link]("Server started... Running on localhost:3000");

AIM:
Write a [Link] module to show the workflow of Modularization of
Node application
SOURCE CODE: [Link]
// Create your own Module
[Link] = (username, password) => {
if (username === "admin" && password === "admin") {
return "Valid User!";
} else return "Invalid User";
};
How to import the [Link] file into another file [Link]?

[Link]
const http = require("http");
var nodemodule =require("./NodeModule");
var server =[Link]((request, response) => {
result = [Link]("admin", "admin");
// The [Link]() method is the status code where 200 means it is OK,
while the second
argument is an object containing the response headers.
[Link](200, { "Content-Type": "text/html" });
[Link]( `
<!DOCTYPE html>
<html>
<head> <title>[Link] </title>
</head>
<body style="background-color:#F0E68C;">
<br><br>
<center><h1><font color="red" size="30"><u>Modular Programming
in [Link] </u> </font></h1>
<h1><font color="blue" size="25">Hello World! Welcome To
CSE!</font></h1>
<h1><font color="red" size="24">[Link]'s College of
Engineering&Technology! </font></h1>
<h2><font color="green" size="15">This page is served by a simple
[Link] server. </font></h2></center></body></html>
`);
[Link]("<center><h1>" + result +"</h1> </center>");
[Link]("Request Received");
});
[Link](2000);
[Link]("Server is running at port 2000");

Exercise -4
AIM:
Write a [Link] program to show the workflow of restarting a Node
application.
SOURCE CODE: [Link]
const http = require("http");
var server = [Link]((req, res) => {
[Link]("Hello World! I have created my first server!");
[Link]();
});
[Link](3000);
[Link]("Server started... Running on localhost:3000");

Modify the code in [Link] file:


const http = require("http");
var server = [Link]((req, res) => {
[Link]("Hello! Welcome to CSE\n"); //modified code
[Link]("Hello World! I have created my first server!");
[Link]();
});
[Link](3000);
[Link]("Server started... Running on localhost:3000");

AIM:
Implement Middleware for myNotes application:
(i) we want to handle POST submissions.
(ii) display customized error messages.
(iii) perform logging.
SOURCE CODE: [Link]
var express = require('express');
var app = express();
var fs = require('fs');
var path = require('path');
var morgan = require('morgan');
const morganBody= require( 'morgan-body');
//Simple app that will log all requests in the Apache combined format to
the file [Link].
var LogStream = [Link]([Link](__dirname,
'[Link]'), { flags: 'a' });
[Link](morgan('combined', { stream: LogStream }));
morganBody(app, {
noColors: true,
stream: LogStream,
});
[Link]((req, res,next)=> {
if(10<20) {
next();
}
});
//Handle Get Submission in [Link]
[Link]('/getRequest', (req, res)=> {
[Link](`
<!DOCTYPE html>
<html>
<head>
<title>[Link] </title>
</head>
<body style="background-color:#F0E68C;">
<br><br><br><center><h1><font color="red" size="25">Hello World!
Welcome To CSE!</font></h1>
<h1><font color="red" size="25"> Develop Middleware in
[Link]</font></h1>
<h1><font color="blue" size="24"> Handle Get Submission in
[Link]-Middleware</font></h1>
</center></body>
</html>
`);
next();
});
//Handle Post Submission in [Link]
[Link]('/postRequest', (req, res)=> {
[Link]("Handle Post Submission in [Link]-Middleware")
next();
});
[Link](function(err, req, res, next) {
// Do logging and user-friendly error message display
[Link](err);
[Link]({status:500, message: 'internal error', type:'internal'});
})
[Link](5000, () => {
[Link](`Server is running on [Link]
});

Exercise-5
AIM: Write a [Link] program to write a Mongoose schema to
connect with MongoDB
PROCEDURE STEPS:
Step1: Installing two packages express and mongoose for mongodb
database:
 For installing the Mongoose library, issue the below command in
the Node command prompt.
PS D:\MSD LAB\ Exercise-4 > npm i express mongoose
Step2:Connecting to MongoDB using Mongoose(open mongoDB
database):
 To establish a connection to the MongoDB database, create a
connection object using Mongoose. This is done through the below
code:
const mongoose = require('mongoose');
[Link]('mongodb://localhost:27017/Database_Name');
Step3: Create a [Link] file in VSCODE or [Link] command prompt .
Step4: Start the server using the following node command.
PS D:\MSD LAB\ Exercise-4 > node [Link] press enter button then
server starts.
Step 5: Open the postman and select the POST from the list box and
enter the URL
[Link]
Step 6: Open the Body, click on the none list box and select the raw
and select JSON from
second list box.
Step 7: Type the following code
{
“name”: “Karth”,
“email”: “stanns@[Link]”
}
Step 8: Click on the send button and click on Preview then output will
be displayed
in JSON format.
Step 9: Now, open the MongoDB database, see your database,
collection and document.
(The output data is transferred from server to client and also to
MongoDB database).
SOURCE CODE: [Link]
const express = require('express');
const mongoose = require('mongoose');
const app = express();
// Define Mongoose schema
const Schema = [Link];
const userSchema = new Schema({
name: {
type: String,
required: true
},
email: {
type: String,
required: true,
unique: true
}
});

// Create Mongoose model


const User = [Link]('User', userSchema);

// Connect to MongoDB
[Link]('mongodb://localhost:27017/Meanstack', {
useNewUrlParser: true,
useUnifiedTopology: true
})
.then(() => {
[Link]('Connected to MongoDB');
})
.catch((err) => {
[Link]('Error connecting to MongoDB:', err);
[Link](1); // Exit the application if unable to connect to
MongoDB
});
// Middleware to parse JSON bodies
[Link]([Link]());

// Define route to create a new user


[Link]('/users', async (req, res) => {
try {
// Check if the name and email fields are present in the request
body
if (![Link] || ![Link]) {
// If either field is missing, return a 400 Bad Request response
with an error message
return [Link](400).json({ error: 'Name and email are
required fields' });
}

// Create a new user document with name and email from request
body
const newUser = new User({
name: [Link],
email: [Link]
});

// Save the new user document to the database


const savedUser = await [Link]();
[Link](savedUser);
} catch (error) {
[Link]('Error creating user:', error);
[Link](500).json({ error: 'Internal Server Error' });
}
});
// Start the server
[Link](5000, () => {
[Link](`Server is running on [Link] });
Exercise -6
AIM: Write a [Link] program to perform various CRUD (Create-
Read-Update-
Delete) operations using Mongoose library functions.
PROCEDURE STEPS:
Step1: Installing [Link] S/W and two packages express and mongoose
for MongoDB
Database.
Step 2: Create a file [Link] at [Link] command prompt or Power
shell in VSCODE.
Step 3: Start the server using the following node command.
PS D:\MSD LAB/Exercise-4> node [Link] press enter button
then server starts.
Step 4: Open the postman and select the POST and enter the URL
[Link]
Step 5: Open the Body, click on the none list box and select the raw
and select JSON from
second list box.
Step 6: Type the following code and click on the Send button and click
on the Preview then
output will be displayed in JSON format .
First Record:
{
“name”: “sacet”,
“email”: “cse@[Link]”
}
Second Record:
{
“name”: “cse”,
“email”: “[Link]@[Link]”
}

Step 7: Read the users data from the data base.


Open the browser, enter the [Link] then read
the data from
database and output displayed on the browser.
Step 8: Retrieve the data by ID from the data base.
Open the browser, enter the
[Link]
then read the data from data base and output will be displayed on the
web browser.
Step 9: Update the data by ID into data base
Open the postman and select the PUT and enter the URL
[Link]
Type the following update code and click on the Send button then
existing data is
update by new data and transfer updated data to a data base.
{
“name”: “stanns”,
“email”: “sacet@[Link]”
}
Step 10: Delete the data by ID from Data base.
Open the postman and select the DELETE and enter the URL
[Link] and click on the
Send
button then above ID document is deleted from the data base.
Step 11: Open the MongoDB database, and verify all CRUD Operations.

SOURCE CODE: [Link]


const express = require('express');
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
const app = express();
const PORT = [Link] || 5000;
// Connect to MongoDB
[Link]('mongodb://localhost:27017/meanstack', {
useNewUrlParser: true,
useUnifiedTopology: true,
//useFindAndModify: true // To avoid deprecation warning for
findOneAndUpdate()
})
.then(() => {
[Link]('Connected to MongoDB');
})
.catch((err) => {
[Link]('Error connecting to MongoDB:', err);
[Link](1); // Exit the application if unable to connect to
MongoDB
});
// Middleware to parse JSON bodies
[Link]([Link]());
// Define User model
const User = [Link]('User', {
name: String,
email: String
});
// Create a new user
[Link]('/users', async (req, res) => {
try {
const { name, email } = [Link];
const newUser = new User({ name, email });
const savedUser = await [Link]();
[Link](savedUser);
} catch (error) {
[Link]('Error creating user:', error);
[Link](400).json({ error: 'Could not create user' });
}
});

// Get all users


[Link]('/users', async (req, res) => {
try {
const users = await [Link]();
[Link](users);
} catch (error) {
[Link]('Error fetching users:', error);
[Link](500).json({ error: 'Internal Server Error' });
}
});

// Get a user by ID
[Link]('/users/:id', async (req, res) => {
try {
const user = await [Link]([Link]);
if (!user) {
return [Link](404).json({ error: 'User not found' });
}
[Link](user);
} catch (error) {
[Link]('Error fetching user:', error);
[Link](500).json({ error: 'Internal Server Error' });
}
});

// Update a user by ID
[Link]('/users/:id', async (req, res) => {
try {
const { name, email } = [Link];
const updatedUser = await
[Link]([Link], { name, email }, { new:
true });
if (!updatedUser) {
return [Link](404).json({ error: 'User not found' });
}
[Link](updatedUser);
} catch (error) {
[Link]('Error updating user:', error);
[Link](500).json({ error: 'Internal Server Error' });
}
});
// Delete a user by ID
[Link]('/users/:id', async (req, res) => {
try {
const deletedUser = await [Link]([Link]);
if (!deletedUser) {
return [Link](404).json({ error: 'User not found' });
}
[Link](deletedUser);
} catch (error) {
[Link]('Error deleting user:', error);
[Link](500).json({ error: 'Internal Server Error' });
}
});

// Start the server


[Link](PORT, () => {
[Link](`Server is running on port ${PORT}`);
});
Exercise -7
a). Write a [Link] program to explain session management using cookies.
SOURCE CODE: [Link]
var express = require('express');
var cookieParser = require('cookie-parser');
var app = express();
[Link](cookieParser());
[Link]('/cookieset',function(req, res){ // create or set cookies
[Link]('College', 'Stanns'); // cookie-name and value
[Link]('Dept', 'CSE');
//[Link]('cookie_name'); // remove cookie
[Link]('<h1><font color="red">Cookie is set</font></h1>');
});
[Link]('/cookieget', function(req, res) { // get cookies
[Link]([Link]);
});
[Link]('/', function (req, res) {
[Link]('<h1><font color="blue">Welcome to Cookies in Express
</font></h1>');
});
// Start the server
[Link](5000, () => {
[Link](`Server is running on [Link]
});

b). Write a [Link] program to explain session management using sessions.


SOURCE CODE: [Link]
const express = require("express")
const session = require('express-session')
const app = express()
// Session Setup
[Link](session({
secret: 'Your_Secret_Key', // It holds the secret key for session
// Forces the session to be saved & back to the session store
resave: true,
// Forces a session that is "uninitialized" to be saved to the store
saveUninitialized: true
}))
[Link]("/", function(req, res){
[Link] = '<h1> <font color="orange">Welcome to
Sessions in Express</font></h1>';
[Link]('<h1><font color="blue">Session is Set in
Express</font></h1>')
})
[Link]("/session", function(req, res){
var name = [Link]
[Link](name)
//To destroy session you can use this function
[Link](function(error){
[Link]("Session Destroyed")
})
})
// Start the server
[Link](5000, () => {
[Link](`Server is running on [Link]
});
Exercise – 8
a).Write a Typescript program to declare an interface named - Product
with two
properties like productId and productName with a number and
string data type and
need to implement logic to populate the Product details using Duck
typing.
SOURCE CODE: [Link]
interface Product { // declaring an interface
productId: number;
productName: string;
}
// logic to display the Product details with interface object as parameter
function getProductDetails(productobj: Product): string {
return 'Product Id : ' +[Link]+"\n"+'Product Name : ' +
[Link];
}
// Declaring a variable along with interface properties
//Adding an additional property productCategory to demonstrate Duck
typing
const prodObject = {productId: 180, productName: 'Mobile',
productCategory: 'Gadget'};
// Declaring variable and invoking Product details function
const productDetails: string = getProductDetails(prodObject);
// line to populate the created product variable on console
[Link](productDetails);
[Link]("ProductCategory : "+[Link]);

b). Write a Typescript program to declare a productList interface


which extends
properties from two other declared interfaces like Category,
Product as well as
implementation to create a variable of this interface type.
SOURCE CODE: [Link]

interface Category { // Declaring a Category interface


categoryName: string;
}
interface Product { // Declaring a Product interface
productName: string;
productId: number;
}
// Declaring a ProductList interface which is extends from Category and
Product interfaces
interface ProductList extends Category, Product {
list: Array<string>;
}
// Creating object literal productDetails with ProductList interface type.
const productDetails: ProductList = {
categoryName: 'Gadget',
productName: 'Mobile',
productId: 180,
list: ['Samsung', 'Motorola', 'LG','Apple']
};
// Assigning list value of productDetails variable into another variable
const listProduct = [Link];
[Link]('Product Id : ' + [Link]);
[Link]('Category Name : ' + [Link]);
[Link]('Product Name : ' + [Link]);
[Link]('Product List : ' + listProduct);
Exercise -9
a). Write a Typescript program to create a Product class with 4 properties
namely productId,
productName, productPrice, productCategory with private, public, static,
and protected
access modifiers and accessing them through Gadget class and its
methods.
SOURCE CODE: [Link]

class Product // declaring a Product class with access modifiers


{
private productId: number;
public productName: string;
protected productCategory: string;
static productPrice = 650;
// declaration of constructor with 3 parameters
constructor(productId: number, productName , productCategory)
{
[Link] = productId;
[Link] = productName;
[Link] = productCategory;
}
getProductId() // method to display product id details
{
[Link]('Product Id : ' + [Link]);
}
}
// declaring a Gadget class extending the properties from Product class
class Gadget extends Product {
// method to display productCategory property
getProduct(): void {
[Link]('Product category : ' + [Link]);
// static property product price directly access with Product class name
[Link]('Product Price : $' + [Link]);

}
}
// Gadget Class object creation
const g1: Gadget = new Gadget(180, 'SmartPhone', 'Mobile');
// invoking getProduct method with the help of Gadget object
[Link]();
// invoking getProductId method with the help of Gadget object
[Link]();
// product name property access with Gadget object
[Link]('Product Name : ' + [Link]);

b) Write a Typescript program to create a namespace called ProductUtility and


place the
Product class definition in it. Import the Product class inside productlist file
and use it.
SOURCE CODE: namespace_demo.ts
namespace ProductUtility {
export class Product
{
productId: number;
productName:string;
quantity: number;
price: number;
constructor( productId: number, productName:string, quantity:
number, price: number){
[Link] =productId;
[Link] =productName;
[Link]=quantity;
[Link] = price;
[Link]("Product Name : "+productName);
}
CalculateAmount(){
var totalPrice= [Link] * [Link];
return totalPrice;
return [Link], [Link], [Link];
}
}
}

namespace_import.ts

// Accessing Namespace
/// <reference path="./namespace_demo.ts" />
let paymentAmount = new [Link](180,"Apple", 2,
60500);
[Link]("Product Id :"+[Link]);
[Link]("Product Quantity : "+[Link]);
[Link]("Product Price : "+[Link]);
[Link]("Amount to be paid:"+[Link]());
Exercise -10
a) Write MongoDB queries to Create and Delete databases and collections.
CREATE OR CHANGE A DATABASE USING MONGOSH IN MONGODB:
 The MongoDB Shell (mongosh) is a REPL (Read-Eval-Print
Loop) environment. It’s like a command-line interface where we can
execute MongoDB commands and interact with the database allowing us
to perform administrative tasks and read, write or manipulate data
directly.
 For storing data in a MongoDB, you need to create a database first.
MongoDB has no "create" command for creating a database. you don't
need to create a database manually because MongoDB will create it
automatically when you save the value into the defined collection at first
time. You can make use of the "use" command followed by the
database_name for creating a database.
Syntax: use Database_Name

Example:
 Here 'use' is the command for creating a new database in MongoDB and
‘meanstack’ is the name of the database. This will prompt you with a
message that it has switched to a new DB (database) name 'meanstack'.
For checking your currently selected database, you can use the command
db.
 To see how many databases are present in your MongoDB server, write the
statement: show databases or show dbs

DELETING A DATABASE IN MONGODB:


The dropDatabase command is used to drop a database. It also deletes the
associated data files. It operates on the current database.
Syntax: [Link]()
If you want to delete the database "meanstack", use the dropDatabase()
command as follows:
Output:

CREATE A COLLECTION IN MONGODB:


 Collections are just like tables in relational databases, they also store data,
but in the form of documents. A single database is allowed to store
multiple collections.
 After creating database now we create a collection to store documents.
There are 2 ways to create a collection.
Method 1:
You can create a collection using the createCollection() database method.
Syntax: [Link]("collectionName")
Example, To create collection and see how many collections are present in your
MongoDB server, write the following statements:

Method 2:
You can also create a collection during the insert process.
Syntax: [Link]({object})
 Here, insertOne() function is used to store single data in the specified
collection and in the curly braces {}, we store our data .
Example,

insertMany():
To insert multiple documents at once, use the insertMany() method. This method
inserts an array of objects into the database.
Example,
>[Link]([{ name:"Sacet", course:"[Link]", branch:"CSE",
due_amt:30000, paid:"no"},{ name:"Karth", course:"[Link]", branch:"CSE",
due_amt:20000, paid:"yes"}] )
Output:

DELETING A COLLECTION IN MONGODB:


For dropping a collection in MongoDB, you have to make use of the
[Link]() method.
Syntax : db.collection_name.drop()
Example,
Output:

b) Write MongoDB queries to work with records using find(), limit(),


sort(),
update() and count().
Find Data:
There are 2 methods to find and select data from a MongoDB database
collection, find() and findOne().
find(): Find all documents in a collection
Retrieve all documents from the specified collection in MongoDB, we can use
the find() method. This method accepts a query object.
Syntax: db. [Link]();
Example, [Link]() or db["Sudent"].find()
Output:

findOne(): To select only one document, we can use the findOne() method. This
method accepts a query object. This method only returns the first match it finds.
Example,
Output:

limit() : Limit the number of results


 The limit() method takes a number as an argument, specifying the
maximum number of documents to return.
Syntax: [Link]().limit(n);
Where n is the number of documents you want to return.
Example, Limiting to a Single Document
 When working with large datasets, sometimes we only need to retrieve
a single document from a collection. This can be done using
the limit(1) method, which ensures that MongoDB returns only one
document, even if multiple documents match the query criteria.
> [Link]().limit(1)
This will return the first document in the `Student` collection.
Output:

sort() : Sort the results of a query


 sort() method takes an object where each key represents a field, and its
value determines the sorting order. 1 represents ascending order (smallest
to largest, A-Z for strings).
-1 represents descending order (largest to smallest, Z-A for strings).
Syntax: db.collection_name.find().sort({ field1: 1, field2: -1 });
Example, [Link]().sort({name:-1})
Output:
update():Update the documents in a Collection
 MongoDB provides the update() command to update the documents of a
collection. To update an existing document in MongoDB, you can use the
`updateOne` or`updateMany` methods.

count(): Count the number of documents in a Collection


The count() method counts the number of documents that match the query
criteria in a Collection. Syntax: db.collection_name.count()
Exercise -11
a) Write a Angular JS program to implements the concept of Form Validation and
Form
Submission
SOURCECODE: [Link]

<!DOCTYPE html>
<html>
<head> <title> Registration Form</title>
<script src="[Link]
<script type="text/javascript">
function validation()
{
var name=[Link];
var pwd=[Link];
var phno=[Link];
var phlen=[Link];
var pwdlen=[Link];
var namelen=[Link];
if(namelen<6)
{
alert("The Name should be minimum 6 characters ");
if(pwdlen>6)
{
alert("Password Should not be more than 6 characters ");
if(phlen!=10)
{
alert("Phonumber Length must be 10 digits ");
}
}
}
else
alert("Registration is Successful");
}
</script>
</head>
<body bgcolor="orange">
<center>
<br><br>
<h1> <font color="red">Angular JS Form Validation & Form
Submission</font></h1>
<div ng-app = "MainApp" ng-controller="AngularController">
<form name="reg" >
<table border=1 bordercolor="green">
<tr><td>Enter Name(min 6 chars)</td><td><input type="text"
name="name" value="" ></td></tr>
<tr><td>Enter Pasword(not more than 6)</td><td><input
type="password" name="pwd" value="" ></td></tr>
<tr><td>Enter E-mail ID</td><td><input type="email" name="eid"
value="" ></td><tr>
<tr><td>Enter Phone Number(10 Digits)</td><td><input
type="number" name="phno" value="" ></td></tr>
<tr><td>Enter Date of Birth</td><td><input type="date" name="Dt"
value=""></td></tr>
<tr><td>Enter Address</td><td><textarea cols=16 name="Ta"
value="" ></textarea></td></tr>
<tr><td >&nbsp&nbsp&nbsp&nbsp<input type="button"
value="Submit" onclick="validation()"
></td><td>&nbsp&nbsp&nbsp&nbsp<input type="reset" ></td></tr>
</table>
</form>
</div>
</center>
</body>
</html>
b) Write a Angular program to create a new component called hello and render
Hello
Angular on the page.
Source code: [Link]
import { Component } from '@angular/core';
@Component({
selector: 'app-hello',
templateUrl: './[Link]',
styleUrls: ['./[Link]']
})
export class HelloComponent {
courseName: string = "Angular";
}

 Open [Link] file MyApp/ src/app/hello and display


the courseName as shown below in Line 2
Source code: [Link]
<p>
Hello {{ courseName }}
</p>

 Open [Link] file MyApp/ src/app/hello and add the


following styles for the paragraph element
Source code: [Link]
p{
color:blue;
font-size:25px;
}

 Open [Link] file from MyApp/src/app folder and add


HelloComponent to bootstrap property as shown below to load it for
execution
Source code: [Link]
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppRoutingModule } from './[Link]';
import { AppComponent } from './[Link]';
import { HelloComponent } from './hello/[Link]';
@NgModule({
declarations: [
AppComponent,
HelloComponent
],
imports: [
BrowserModule,
AppRoutingModule
],
providers: [],
bootstrap: [HelloComponent]
})
export class AppModule { }

 Open [Link] file from MyApp/src folder and load the hello
component by using its selector name i.e., app-hello as shown below in
Line 11
Source code: [Link]
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>MyApp</title>
<base href="/">
<meta name="viewport" content="width=device-width, initial-
scale=1">
<link rel="icon" type="image/x-icon" href="[Link]">
</head>
<body>
<app-hello></app-hello></body></html>

You might also like