Mean Stack Technologies Lab Manual
Mean Stack Technologies Lab Manual
: 1
Date:
Experiment-1:
DESCRIPTION:
Case-insensitivity:
HTML is not a Case Sensitive Language because, during parsing, all HTML elements are
converted to lowercase first. HTML5, the latest version of HTML, which is a new web
standard, is also case insensitive. XHTML, an older version of HTML, was case-sensitive for
lowercase letters.
Platform independency:
The HyperText Markup Language (HTML) is the publishing language of the World Wide
Web. The first version of HTML was described by Tim Berners-Lee in late 1991. The current
W3C Recommendation for HTML is HTML5.
Attributes:
• All HTML elements can have attributes
• Attributes provide additional information about elements
• Attributes are always specified in the start tag
• Attributes usually come in name/value pairs like: name="value"
Metadata Element:
Metadata is data (information) about data. <meta> tags always go inside the <head> element,
and are typically used to specify character set, page description, keywords, author of the
document, and viewport settings. Metadata will not be displayed on the page, but is machine
parsable.
OUTPUT:
DESCRIPTION:
Sectioning Elements:
In HTML, a section is a semantic element for creating standalone sections in a web page.
These sections should be made up of related content, like contact information.
The section element should only be used if there isn't a more specific element to represent the
related content.
The sectioning elements in HTML5 are <nav> , <aside> , <article> , and <section> .
<body> is also kind of a sectioning element since all content lying inside of it is part of the
default document section.
PROGRAM:
<!DOCTYPE HTML>
<head>
<title>ShopTime website</title>
</Head>
<body bgcolor="cyan">
<h1 align="center"><i>ShopTime<i></h1>
<h2 align="center"><i>One stop for all your needs<i></h2>
<nav align="center"><h3> Home || Login || Register || Wishlist || My Orders ||
Help</h3></nav>
<main>
<section>
<p>Clothing</p>
</section>
<section>
<p>Footwear</p>
</section>
<section>
<p>Electronics</p>
</section>
<section>
<p>Furniture</p>
</section>
<section>
<p>Cosmetics</p>
</section>
</main>
OUTPUT:
AIM :Paragraph Element, Division and Span Elements, List Element Make use of
appropriate grouping elements such as list items to "About Us" page of IEKart's Shopping
Application.
DESCRIPTION:
<div>
The div (division) element is a generic block-level element, most often used to divide page
content into blocks. A block element is a page element that starts a new line and has a width
equal to the entire page or the parent container.
You’ll very often see divs used to group related paragraphs, images, headings, and links. For
example, a three-paragraph article may be enclosed in a div, and a navigation menu
containing links might be enclosed in another div. Using divs this way makes it easier to
identify different sections of a page and apply styling to them with CSS.
<span>
The span element is a generic inline element, typically used to apply styling to a portion of
inline content. An inline element does not start a new line and only takes up as much space on
the page as its content. Span tags are used on small segments of text, links, images, and other
HTML elements that appear inline with the surrounding content.
PROGRAM:
<!DOCTYPE HTML>
<head>
<title>ShopTime website</title>
</Head>
<body bgcolor="lavender">
<h1 align="center"><i>ShopTime<i></h1>
<h2 align="center"><i>One stop for all your needs<i></h2>
<nav align="center"><h3>
Home || Login || Track Order </h3>
</nav>
<center>
<p><img src="https://www.logomaker.com/wp-content/uploads/2018/01/FLS-Blog-Black-
Logos_Hero.jpg" alt="Top shopping brands" width="950" height="300"</p>
</center>
</body>
<footer>
<a href=aboutus.html">About Us</a>
</footer>
</html>
Aboutus.html :
<!DOCTYPE HTML>
<html>
<head>
<title>ShopTime website</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
</Head>
<body bgcolor="cyan">
<div class="about-section">
<h1>About Us Page</h1>
<p><span style="color:blue;font-weight:bold"><i>ShopTime</i></span> is an indigenous e-
commerce website discovering new ways to satisfy customer's needs.</p></div>
<h2>Founders</h2>
<ul>
<li>Jane Doe - Foumder &CEO</li>
<li>John Doe - Art Designer</li>
</ul>
</body>
</html>
OUTPUT:
AIM : Link Element Link "Login", "SignUp" and "Track order" to "Login.html",
"SignUp.html" and "Track.html" page respectively. Bookmark each category to its details of
IEKart's Shopping application.
DESCRIPTION:
Link Element:
The link element allows authors to link their document to other resources.
The destination of the link(s) is given by the href attribute, which must be present and must
contain a valid non-empty URL potentially surrounded by spaces.
A link element must have rel attribute.
The types of link indicated (the relationships) are given by the value of the rel attribute,
which, if present, must have a value that is a set of space-separated tokens. The allowed
keywords and their meanings are defined in a later section.
Two categories of links can be created using the link element: Links to external resources and
hyperlinks. The link types section defines whether a particular link type is an external
resource or a hyperlink. One link element can create multiple links (of which some might be
external resource links and some might be hyperlinks); exactly which and how many links are
created depends on the keywords given in the rel attribute. User agents must process the links
on a per-link basis, not a per-element basis.
PROGRAM:
<!DOCTYPE HTML>
<head>
<title>ShopTime website</title>
<meta charset="UTF-8">
<meta name="description" content="ShopTime is an online shopping website that sells goods
in retail. This company deals with various categories like Electronics, Clothing, Accessories
etc">
<meta name="keywords" content="clothing,footwear,shopping">
<meta name="author" content="Myself">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</Head>
<body bgcolor="lavender">
<h1 align="center"><i>ShopTime<i></h1>
<h2 align="center"><i>One stop for all your needs<i></h2>
<nav align="center"><h3>
<a href=”home.html”>Home</a> ||<a href=”login.html”> Login</a>
||<ahref=”trackorder.html”>Track Order</a></h3>
</nav>
<center>
<p><img src="homeimg.png" alt="Top shopping brands" width="1350" height="300"</p>
</center>
</body>
OUTPUT:
AIM: Character Entities Add the © symbol in the Home page footer of IEKart's Shopping
application.
DECRIPTION:
Some characters are reserved in HTML.
If you use the less than (<) or greater than (>) signs in your text, the browser might mix them
with tags.
Character entities are used to display reserved characters in HTML.
A character entity looks like this:
&entity_name;
OR
&#entity_number;
PROGRAM:
<!DOCTYPE HTML>
<head>
<title>ShopTime website</title>
OUTPUT:
DESCRIPTION:
PROGRAM:
<!DOCTYPE HTML>
<html>
<head>
<title>ShopTime Website</title>
</head>
<body bgcolor="lavender">
<table cellspacing="1" cellpadding="0" border="1" align="center">
<caption><h1>Electronics</h1></caption>
<b><tr bgcolor="white"><td>Smartwatches & Fitness trackers</td><td><img
src="https://consumer.huawei.com/content/dam/huawei-cbg-
site/common/mkt/pdp/wearables/watch-fit/dynamic/watch-fit/img/pc/huawei-watch-fit-
personal-assistant-3.jpg" width = "120px" height = "120px" alt="Smartwatches"></td></tr>
<tr><td>Earbuds</td><td><img
src="https://i.pinimg.com/originals/db/96/6c/db966cbb958a6c398e4e099f423ffb56.jpg"
width = "130px" height = "130px" alt="Earbuds"></td></tr>
<tr bgcolor="white"><td>Speakers</td><td><img
src="https://www.monitoraudio.com/site/assets/files/33185/silver100le-actionblock-2.jpg"
width = "130px" height = "130px" alt="Speakers"></td></tr></b>
</table>
</body>
</html>
AIM: Creating Form Elements, Color and Date Pickers, Select and Datalist Elements Using
the form elements create Signup page for IEKart's Shopping application.
DESCRIPTION:
An HTML form is used to collect user input. The user input is most often sent to a server for
processing.
The HTML <form> element is used to create an HTML form for user input:
<form>
.
form elements
.
</form>
The <form> element is a container for different types of input elements, such as: text fields,
checkboxes, radio buttons, submit buttons, etc.
All the different form elements are covered in this chapter: HTML Form Elements.
PROGRAM:
<html>
<body bgcolor="lavender">
<form align="center">
<table align=center>
<caption><h1>Sign Up</h1></caption>
<tr><td><label>First Name:</label></td><td><input type="text"></td><br>
<tr><td><label>Email:</label></td><td><input type="email" ><br>
<tr><td><label>Date of birth:</label></td><td><input type="date"></td>
<tr><td><label>Gender: </label><td><input type="radio" name="gender" value="Male">
Male <input type="radio" name="gender" value="Female"> Female</td><br>
<tr><td><label>Mobile:</label></td><td><input type="number" ><br>
<tr><td><label>Username:</label></td><td><input type="text"><br>
<tr><td><label>Password:</label></td><td><input type="password" ><br>
<tr><td><label>Confirm Password:</label></td><td><input type="password" ><br>
<tr rowspan="3"><td><label>Address :<br></label></td><td><textarea rows="3" cols="30"
></textarea></td></tr><br><br>
</table>
<br><button type="submit">Signup</button>
</form>
</body>
</html>
AIM: Input Elements - Attributes Enhance Signup page functionality of IEKart's Shopping
application by adding attributes to input elements.
DESCRIPTION:
Here are the different input types you can use in HTML:
<input type="button">
<input type="checkbox">
<input type="color">
<input type="date">
<input type="datetime-local">
<input type="email">
<input type="file">
<input type="hidden">
<input type="image">
<input type="month">
<input type="number">
<input type="password">
<input type="text"> defines a single-line text input field
<input type="password"> defines a password field
PROGRAM:
<html>
<body bgcolor="lavender">
<form align="center">
<table align=center>
<h1 align="center"><i>ShopTime</i></h1>
<caption><h3>Sign Up</h3></caption>
<tr><td><label>Name:</label></td><td><input type="text"></td><br>
<tr><td><label>Mobile:</label></td><td><input type="number"
autocomplete="on"></td><br>
<tr><td><label>Date of birth:</label></td><td><input type="date"></td>
<tr><td><label>Gender: </label><td><input type="radio" name="gender" value="Male">
Male <input type="radio" name="gender" value="Female"> Female</td><br>
<tr><td><label>Email:</label></td><td><input type="email"><br>
<tr><td><label>Username:</label></td><td><input type="text" pattern="[A-Zaz]"
maxlength="20" minlength="9"><br>
<tr><td><label>Password:</label></td><td><input type="password"
placeholder="********"><br>
<tr><td><label>Confirm Password:</label></td><td><input type="password"
placeholder="********"><br>
<tr rowspan="3"><td><label>Address :<br></label></td><td><textarea rows="3" cols="30"
spellcheck="true" ></textarea></td></tr><br><br>
</table>
<br><button type="submit">Signup</button>
Output:
AIM: Media, Iframe Add media content in a frame using audio, video, iframe elements to the
Home page of IEKart's Shopping application.
DESCRIPTION:
The media attribute specifies what media/device the linked document is optimized for.
This attribute is used to specify that the target URL is designed for special devices (like
iPhone) , speech or print media.
This attribute can accept several values.
Iframe:
An HTML iframe is used to display a web page within a web page.
The HTML <iframe> tag specifies an inline frame.
An inline frame is used to embed another document within the current HTML document.
The HTML <video> element is used to show a video on a web page.
The controls attribute adds audio controls, like play, pause, and volume.
The <source> element allows you to specify alternative audio files which the browser may
choose from. The browser will use the first recognized format.
The text between the <audio> and </audio> tags will only be displayed in browsers that do
not support the <audio> element.
Syntax:
<iframe src="url" title="description"></iframe>
PROGRAM:
<!DOCTYPE html>
<html>
<body bgcolor="lavender">
<h1 align="center"><i>ShopTime<i></h1>
<h2 align="center"><i>One stop for all your needs<i></h2>
<header>
<nav align="center"><h3>
Home || Login || Register || Wishlist || My Orders || Help</h3>
</nav>
<center>
</header>
<p>
<iframe src="homeimg1.png" name="iframe_1 height="300" width="600" title="Iframe
Example"></iframe>
Output:
AIM: Write JavaScript code to display the movie details such as movie name, starring,
language, and ratings. Initialize the variables with values of appropriate types. Use template
literals wherever necessary.
DESCRIPTION :
Every Variable has a data type that tells what kind of data is being stored in a variable. There
are two types of data types in JavaScript.
Primitive data types
Non-primitive data types
Primitive data types: The predefined data types provided by JavaScript language are known
as primitive data types. Primitive data types are also known as in-built data types.
Below is a list of Primitive Data Types:
1.Number
2.String
3.Undefined
4.Boolean
5.Null.....etc
Non-primitive data types: The data types that are derived from primitive data types of the
JavaScript language are known as non-primitive data types. It is also known as derived data
types or reference data types.
Below is a list of Non-primitive data types.
Non-primitive Data Types
Object
Array
PROGRAM:
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Template Literals</h2>
<p id="demo"></p>
<p id="demo1"></p>
<script>
let MovieName = "Transformers";
let Starring = "Meghan Fox";
let Language = "English";
var Rating = "7.9";
let Movie = "San Andreas";
let Cast = "Dwayne Johnson";
let Lang = "English";
var Ratings = "8.5";
let text = `The movie "${MovieName}" starring ${Starring} originally in
${Language} has rating of ${Rating}`;
OUTPUT:
AIM: Write JavaScript code to book movie tickets online and calculate the total price,
considering the number of tickets and price per ticket as Rs. 150. Also, apply a festive season
discount of 10% and calculate the discounted amount .
DESCRIPTION:
Operator:
JavaScript operators are symbols that are used to perform operations on operands. For
example:
var sum=10+20;
Here, + is the arithmetic operator and = is the assignment operator.
There are following types of operators in JavaScript.
• Arithmetic Operators
• Comparison (Relational) Operators
• Bitwise Operators
• Logical Operators
• Assignment Operators
• Special Operators
PROGRAM:
<!DOCTYPE html>
<html>
<head>
</head>
<body style = "text-align: center; font-size: 20px;">
<h1> Online seats reservation </h1>
Enter the number of seats: <input id = "number">
<br><br>
<button onclick = "m()">Pay only</button>
<p id = "res"></p>
<script>
function ticket(num)
{
actual=num*150;
discount=(actual/10); afterdisc=actual-discount; return afterdisc
}
function m()
{
var num = document.getElementById("number").value;
var f = ticket(num);
document.getElementById("res").innerHTML="The total price is " + num + "
is: " + f ;
}
</script>
OUTPUT:
AIM: Write a JavaScript code to book movie tickets online and calculate the total price based
on the 3 conditions:
(a) If seats to be booked are not more than 2, the cost per ticket remains Rs. 150.
(b) If seats are 6 or more, booking is not allowed.
(c) If seats to be booked are more than 2 but less than 6, based on the number of seats
booked, do the following - Calculate total cost by applying discounts of 3, 5, 7, 9, 11 percent,
and so on for customer 1,2,3,4 and 5.
DESCRIPTION:
Conditional Statements
Very often when you write code, you want to perform different actions for different decisions.
You can use conditional statements in your code to do this.
In JavaScript we have the following conditional statements:
Use if to specify a block of code to be executed, if a specified condition is true
Use else to specify a block of code to be executed, if the same condition is false
Use else if to specify a new condition to test, if the first condition is false
Use switch to specify many alternative blocks of code to be executed
PROGRAM:
<html>
<head>
<title>Movies</title>
</head>
<body bgcolor="lavender">
<h1 align="center"><i>ShopTime</i></h1>
<h2>Online bookings</h2>
<script bgcolor="lavender">
n=window.prompt("Enter a number:");
if(n<=2) {
tcost=n*150
document.write("For n tickets,you need to pay :",tcost);
}
else if(n>=6)
document.write("Bookings are not Allowed");
else
{
if (n==3) {
t1=150-(150*(3/100));
t2=150-(150*(5/100));
t3=150-(150*(7/100));
tcost=t1+t2+t3;
PROGRAM:
<html>
<head>
<title>TicketsBooking</title>
<script>
var x;
var y;
var z; fun = () => {
var a = prompt("Enter the number of tickets:"); if (a < 6) {
document.getElementById("id").innerHTML = "Total amount you need to pay:";
document.getElementById("id1").innerHTML = "Rs." + calculateCost(a);
document.getElementById("id2").innerHTML = "Discount Amount is:
Rs.”+calculateDiscount(a);
}
else {
document.getElementById("id").innerHTML = "Sorry! You can book upto 5
tickets only in online!!";
document.getElementById("id1").innerHTML = "";
document.getElementById("id2").innerHTML = "";
}
}
const p = 150; calculateCost = (a) => {
var i = 1;
DESCRIPTION: To create a class inheritance, use the extends keyword. The super() method
refers to the parent class. By calling the super() method in the constructor method, we call the
parent's constructor method and gets access to the parent's properties and methods. Classes also
allows you to use getters and setters. It can be smart to use getters and setters for your
properties, especially if you want to do something special with the value before returning them,
or before you set them. To add getters and setters in the class, use the get and set keywords.
PROGRAM:
<html>
<head>
<title>Classes and Inheritances</title>
<script> class Person {
constructor(name, age) {
this.name = name; this.age = age;
}
det() {
return "Name: " + this.name + "<br>" + "<br>" + "Age:
"+this.age;
}
}
class Employee extends Person {
constructor(name, age, role, contact) {
super(name, age); this.roll = role; this.contact = contact;
}
getDetails() {
return this.det() + "<br>" + "<br>" + "Role:
"+this.roll+" < br > "+ " < br > "+"Contact: "+this.contact;
}
}
function fun() {
let v = new Employee("John Doe", 24, "Cloud Architect", "9876543210");
document.getElementById("id1").innerHTML = v.getDetails();
}
</script>
</head>
<body bgcolor="cyan">
<h1 style="background-color:white">
<center></center>
</h1>
OUTPUT:
DESCRIPTION:
A JavaScript object has properties associated with it. A property of an object can be explained
as a variable that is attached to the object. Object properties are basically the same as ordinary
JavaScript variables, except for the attachment to objects. The properties of an object define
the characteristics of the object. You access the properties of an object with a simple dot
notation => objectName.propertyName
PROGRAM:
<!DOCTYPE html>
<html>
<script>
var c = 0; function fun() {
if (c == 0) {
document.body.style.backgroundColor = "cyan";
document.getElementById("id1").innerHTML = "Fill your cone";
document.getElementById("imag").src = "cone.jpg";
document.getElementById("link").innerHTML = "Fill";
c = 1;
}
else {
document.body.style.backgroundColor = "pink";
document.getElementById("id1").innerHTML = "Eat your cone";
document.getElementById("imag").src = "cone1.jpg";
document.getElementById("link").innerHTML = "Eat";
c = 0;
}
}
</script>
<center>
<h1 id="id1">Eat your cone</h1>
<br><br>
<img src="cone1.jpg" alt="Reload" height="300px" width="200px" id="imag">
<br>
<a href="javascript:fun()" id="link">Eat</a>
</center>
</body>
</html>
PROGRAM:
<!DOCTYPE html>
<html>
<body bgcolor="cyan">
<center><h1><i>ShopTime</i></h1>
<h2 align="center"><i>One stop for all your needs<i></h2>
<header>
<nav align="center"><h3>Home || Login || Register || Wishlist || My Orders || Movies ||
Help</h3>
</nav>
</header></center>
<I><h2>JavaScript Arrays</h2></I>
Output:
DESCRIPTION:
Modules
JavaScript modules allow you to break up your code into separate files.
This makes it easier to maintain a code-base.
Modules are imported from external files with the import statement.
Modules also rely on type="module" in the <script> tag.
A module in JavaScript is just a file containing related code.
In JavaScript, we use the import and export keywords to share and receive functionalities
respectively across different modules.
The export keyword is used to make a variable, function, class or object accessible to other
modules. In other words, it becomes a public code.
The import keyword is used to bring in public code from another module.
PROGRAM:
<!DOCTYPE html>
<html lang=“en”>
<head>
<meta charset=”UTF-8 />
<meta http-euiv=”X-UA-Compatible” content=”IE=edge” />
<meta name=“viewname” content=”width=device-width, initial-scale=1.0” />
<title>Document</title>
</head>
<body>
<input type=“text” name=”name” id=”name” placeholder=”Enter your user name here” />
<input type=“password” name=”pass” id=”password” placeholder=”Enter your password”
/>
<button type=“submit” id=”btn”> LOGIN</button>
<script src=“validateUser.js” type=”module”></script>
< script src=“login.js” type=”module”>
</script>
</body>
</html>
Login.js:
Class User{
Constructor(name, pass)
{
this.username = name;
this.password = pass;
}
validateUser(name, pass)
{
return name = this.name && pass == this.password) ? ”Login Successful” : “Unauthorized
access”;
}
}
OUTPUT:
Program-2:
function tester()
{
var m=10;
var message;
if (m%2==0)
{
message = "m is prime";
}
else
{
message = "m is not prime";
}
console.log(message);
}
tester();
OUTPUT:
AIM: Creating a web server in Node.js and showing the workflow of JavaScript code
executable by creating web server in Node.js.
DESCRIPTION:
Using require() and createServer() method Running a web server in Node.js
Step 1: Create a new JavaScript file httpserver.js and include the
HTTP module.
Step 2: Use the createServer() method of the HTTP module to create a web server.
Step 3: Save the file and start the server using the node command. When the file executes
successfully, we can observe the following output in the console.
Step 4: We will observe the output in the browser.
PROGRAM:
var http = require('http');
http.createServer(function (req, res) {
res.writeHead(200, { 'Content-Type': 'text/html' }); res.end(‘Server is connected.');
}).listen(8000);
console.log("Server started... Running on localhost:8000");
OUTPUT:
Nodemon: Nodemon is a command-line utility that can be executed from the terminal. It
provides a different way to start a Node.js application. It watches the application and whenever
any change is detected, it restarts the application. It is very easy to get started with this tool.
To install it in the application, run the below command.
npm install nodemon –g
Once the 'nodemon' is installed in the machine, the Node.js server code can be executed by
replacing the command "node" with "nodemon".
PROGRAM:
const http = require("http");
var server = http.createServer((req, res) => {
res.write("Hello ! I have created my second server!"); res.end();
});
server.listen(5000);
console.log("Server started... Running on localhost:5000");
OUTPUT:
OUTPUT:
PROGRAM:
const fs = require('fs');
const src = "source.txt";
const dest = "destination.txt";
fs.copyFile(src, dest, (error) => {
// incase of any error
if (error)
{
console.error(error); return;
}
console.log("Copied Successfully!");
});
OUTPUT:
source.txt:
destination.txt:
DESCRIPTION:
Routing: The application object has different methods corresponding to each of the HTTP
verbs (GET, POST, PUT, DELETE). These methods are used to receive HTTP
requests.Syntax: router.method(path,handler) router: express instance or router instance
method: one of the HTTP verbspath: is the route where request runs
handler: is the callback function that gets triggered whenever a request comes to a particular
path for a matching request type .
PROGRAM:
myNotes.js:
exports.packages = async (req, res) => {
try {
res.status(200).json({
message: 'You can now get the requested notes for your request ',
});
} catch (err) {
res.status(404).json({
status: 'fail', message: err,
});
}
};
exports.bookpackage = async (req, res) => {
try {
res.status(201).json({
data: 'New booking added for the POST request',
});
} catch (err) {
res.status(404).json({
status: 'fail',
message: err.errmsg,
});
}
};
exports.invalid = async (req, res) => {
res.status(404).json({
status: 'fail', message: 'Invalid path',
});
};
App.js:
const express = require('express');
const route = require('./routes/route');
const app = express(); app.use('/', route);
const port = process.env.PORT || 3000;
app.listen(port, () => {
console.log(`App running on port ${port}...`);
});
OUTPUT:
PROGRAM:
Route1.js:
const express = require('express');
const router = express.Router();
const myController = require('../Controller/myNotes1');
router.get('/', myController.myMethod);
router.get('/about', myController.aboutMethod);
module.exports = router;
myNotes.js:
exports.myMethod = async (req, res, next) => {
res.send('<h1>Welcome</h1>');
};
exports.aboutMethod = async (req, res, next) => {
res.send('<h1>About Us Page</h1>');
};
app1.js:
const express = require('express');
const router = require('./Routes/route1');
const app = express();
const mylogger = function (req, res, next) {
console.log(`Req method is ${req.method}`);
console.log(`Req url is ${req.url}`);
next();
};
app.use(mylogger);
OUTPUT:
DESCRIPTION:
Before we get into the specifics of validation syntax, please keep the following rules in mind:
•Validation is defined in the SchemaType
•Validation is middleware. Mongoose registers validation as a pre('save') hook on every
schema by default.
•You can disable automatic validation before save by setting the validateBeforeSave option
•You can manually run validation using doc.validate(callback) or doc.validateSync()
•You can manually mark a field as invalid (causing validation to fail) by using
doc.invalidate(...)
•Validators are not run on undefined values. The only exception is the required validator.
PROGRAM:
const express=require('express');
const mongoose = require('mongoose');
const app = express();
app.listen(3000, () => console.log(" server running. .... "));
const
url="mongodb+srv://mstdatabase:[email protected]/?retryWrites
=true&w=majority";
mongoose.connect(url).then(() => console.log("Database Connected. ... ")).catch(err =>
console.log(err));
CREATING SCHEMA:
const express=require('express');
const mongoose=require('mongoose');
const app=express();
app.listen(3000,()=>console.log(" Server running. .... "));
const
url="mongodb+srv://mstdatabase:[email protected]/?retryWrites
=true&w=majority";
OUTPUT:
PROGRAM:
const express = require('express')
constmongoose = require('mongoose')
const url = "mongodb://0.0.0.0:27017/Hell";
mongoose.connect(url, { useNewUrlParser: true }, { useUnifiedTopology: true }).then(() =>
console.log("DatabaseConnected....")).catch(err => console.log(err));
var bookSchema = mongoose.Schema({
name: String,
isbn: {type: String, index: true},
author: String,
pages: Number
});
var Book = mongoose.model("Book", bookSchema);
var db = mongoose.connection;
db.on("error", console.error.bind(console, "connection error:")); db.once("open", function () {
console.log("Connected to DB");
});
OUTPUT:
DESCRIPTION:
CRUD OPERATIONS
Create: We’ll be setting up a post request to ‘/save’ and we’ll create a new student object with
our model and pass with it the request data from Postman.Once this is done, we will use .save()
to save it to the database.
Retrieve: To retrieve records from a database collection we make use of the .find() function.
Update: Just like with the delete request, we’ll be using the _id to target the correct item.
.findByIdAndUpdate() takes the target’s id, and the request data you want to replace it with.
PROGRAM:
Create:
const express = require('express');
const mongoose = require('mongoose');
const url = "mongodb://0.0.0.0:27017/Hell";
mongoose.connect(url, { useNewUrlParser: true }, { useUnifiedTopology: true }).then(() =>
console.log("D atabase Connected. ... ")).catch(err => console.log(err));
var bookSchema = mongoose.Schema({
name: String,
isbn: { type: String, index: true }, author: String, pages: Number
});
var Book = mongoose.model("Book", bookSchema);
var db = mongoose.connection;
var book1 = new Book({
name: "Mongoose Demo 1", isbn: "MNG123", author: "Author1, Author2", pages: 123
});
book1.save(function (err) {
if (err)
throw err;
console.log("Book Saved Successfully");
});
PROGRAM:
import express from "express";
import mongoose from "mongoose";
const app = express();
app.use(express.json());
// Creation of Notes Schema
const Schema=mongoose.Schema;
const NoteSchema = new Schema({
title:{
type: String
},
content:{
type:String
}
});
// Creating Note model
const Note=mongoose.model("Note",NoteSchema);
// Creation of a new note using app.post
app.post("/notes/create",(req, res) => {
if(!req.body.content) {
return res.status(400).send({
message: "Note content can not be empty"
});
}
const note = new Note({
title: req.body.title || "Untitled Note",
content: req.body.content
});
note.save()
.then(data => {
res.send(data);
}).catch(err => {
res.status(500).send({
message: err.message || "Some error occurred while creating the Note."
});
});
CREATION OF A NOTE:
OUTPUT:
AIM: On the page, display the price of the mobile-based in three different colors. Instead of
using the number in our code, represent them by string values like GoldPlatinum, PinkGold,
SilverTitanium.
PROGRAM:
OUTPUT:
AIM: Define an arrow function inside the event handler to filter the product array with the
selected product object using the productId received by the function. Pass the selected product
object to the next screen.
Program:
var getproductdetails=(productId : number):string=>{
return "product Id:"+productid
};
console.log(getproductdetails(1234));
Output:
OUTPUT:
DESCRIPTION:
Optional Parameters
In TypeScript, every parameter is assumed to be required by the function. You can add a ? at
the end of a parameter name to set it as optional.
For example, the lastName parameter of this function is optional:
function buildName(firstName: string, lastName?: string) {
// ...
}
Optional parameters must come after all non-optional parameters:
function buildName(firstName?: string, lastName: string) // Invalid
Default Parameters
If the user passes undefined or doesn't specify an argument, the default value will be
assigned. These are called default-initialized parameters.
For example, "Smith" is the default value for the lastName parameter.
function buildName(firstName: string, lastName = "Smith") {
// ...
}
buildName('foo', 'bar'); // firstName == 'foo', lastName == 'bar'
buildName('foo'); // firstName == 'foo', lastName == 'Smith'
buildName('foo', undefined); // firstName == 'foo', lastName == 'Smith'
PROGRAM:
function getMobileByManufacturer(manufacturer: string = 'Samsung', id?: number): string[]
{
let mobileList: string[];
if (id) {
if (id === 101) {
mobileList = ['Moto G Play, 4th Gen', 'Moto Z Play with Style Mod'];
return mobileList;
}
}
if (manufacturer === 'Samsung') {
OUTPUT:
DESCRIPTION:
TypeScript - Rest Parameters
In the function chapter, you learned about functions and their parameters. TypeScript
introduced rest parameters to accommodate n number of parameters easily. When the number
of parameters that a function will receive is not known or can vary, we can use rest parameters.
In JavaScript, this is achieved with the "arguments" variable. However, with TypeScript, we
can use the rest parameter denoted by ellipsis ....
We can pass zero or more arguments to the rest parameter. The compiler will create an array
of arguments with the rest parameter name provided by us.
PROGRAM:
const cart: string[] = [];
const pushtoCart = (item: string) => { cart.push(item); }; function addtoCart(...productName:
string[]): string[] {
for (const item of productName) {
pushtoCart(item);
}
return cart;
}
console.log('Cart Items are:' + addtoCart(' Moto G Play, 4th Gen', ' Apple iPhone 5s'));
OUTPUT:
AIM: Declare an interface named- Product with two properties like productId and
productName with the number and string datatype and need to implement logic to populate
the Product details.
DESCRIPTION:
Duck-Typing
Duck-Typing is a method/rule used by TypeScript to check type compatibility for more
complex variable types. This method is used to compare two objects by determining whether
they have the same type of matching names or not. It means we can't change a variable's
signature.
The duck-typing technique in TypeScript is used to compare two objects by determining if they
have the same type matching properties and objects members or not. For example, if we assign
an object with two properties and a method and the second object is only assigned with two
properties. The typescript compiler raises a compile-time error in such situations when we
create a variable of object1 and assign it a variable of the second object type.
PROGRAM:
interface Product { productId: number; productName: string; }
function getProductDetails(productobj: Product): string {
return 'The product name is : ' + productobj.productName;
}
const prodObject = { productId: 1001, productName: 'Mobile', productCategory: 'Gadget' };
const productDetails: string = getProductDetails(prodObject); console.log(productDetails);
OUTPUT:
DESCRIPTION: A function type has two parts: parameters and return type. When declaring
a function type, you need to specify both parts with the following syntax:
(parameter: type, parameter:type,...) => type
Code language: PHP (php)
The following example shows how to declare a variable which has a function type that accepts
two numbers and returns a number:
let add: (x: number, y: number) => number;
Code language: JavaScript (javascript)
In this example:
The function type accepts two arguments: x and y with the type number.
The type of the return value is number that follows the fat arrow (=>) appeared between
parameters and return type.
PROGRAM:
function CreateCustomerID(name: string, id: number): string {
return 'The customer id is ' + name + ' ' + id;
}
interface StringGenerator { (chars: string, nums: number): string; }
let idGenerator: StringGenerator; idGenerator = CreateCustomerID;
const customerId: string = idGenerator('Mr.Tom', 101); console.log(customerId);
OUTPUT:
AIM:To declare a productList interface which extends properties from two other declared
interfaces like Category.
DESCRIPTION: An interface can be extended from an already existing one using the extends
keyword. In the code below, extend the productList interface from both the Category interface
and Product interface.
Example:
interface Category{ categoryName:string; }
interface Product{ productName:string; productid:number; }
interface productList extends Category,Product{ list:[‘Samsung’,’Motorola’,’LG’ ] }
PROGRAM:
interface Category {
categoryName: string;
}
interface Product {
productName: string;
productId: number;
}
interface ProductList extends Category, Product {
list: Array;
}
const productDetails: ProductList = {
categoryName: 'Gadget', productName: 'Mobile',
productId: 1234, list: ['Samsung', 'Motorola', 'LG']
};
const listProduct = productDetails.list;
const pname: string = productDetails.productName;
console.log('Product Name is ' + pname);
console.log('Product List is ' + listProduct);
OUTPUT:
AIM: To consider the Mobile Cart application, Create objects of the Product class and place
them into the productlist array.
PROGRAM:
class Product {
static productPrice: string;
productId: number;
constructor() {
this.productId = 1234;
}
getProductId(): string {
return 'Product id is : ' + this.productId;
}
}
const product: Product = new Product();
const p = {
producti: product.getProductId(),
};
console.log(p.producti);
OUTPUT:
PROGRAM:
class Product {
static productPrice: string;
productId: number;
constructor(productId: number) {
this.productId = productId;
}
getProductId(): string {
return 'Product id is : ' + this.productId;
}
}
const product: Product = new Product(1234);
console.log(product.getProductId());
OUTPUT:
OUTPUT:
AIM: To create a Product class with 4 properties namely productId and methods to
setProductId() and getProductId().
DESCRIPTION: In typescript, the method is a piece of code that has been declared within the
class and it can be carried out when it is called. Method property in it can split a huge task into
little sections and then execute the particular operation of that program so that code can be
reusable which can improve the module from the program.
PROGRAM:
// declaring a Product class
class Product {
static productPrice: string;
productId: number;
constructor(productId: number) {
this.productId = productId;
}
getProductId(): string {
return 'Product id is : ' + this.productId;
}
}
const product: Product = new Product(2345);
console.log(product.getProductId());
OUTPUT:
AIM: To create a namespace called ProductUtility and place the Product class definition in it.
Import the Product class inside productlist file and use it.
DESCRIPTION: In typescript, the method is a piece of code that has been declared within the
class and it can be carried out when it is called. Method property in it can split a huge task into
little sections and then execute the particular operation of that program so that code can be
reusable which can improve the module from the program. The classes or interfaces which
should be accessed outside the namespace should be marked with keyword export. To access
the class or interface in another namespace, the syntax will be
namespaceName.className
PROGRAM:
namespace_one12b.ts:
import util = Utility.Payment;
let paymentAmount = util.CalculateAmount(1800, 6);
console.log(`Amount to be paid: ${paymentAmount}`);
namespace_two12b.ts:
namespace Utility {
export namespace Payment {
export function CalculateAmount(price: number, quantity: number): number {
return price * quantity;
}
}
}
OUTPUT:
DESCRIPTION: A module refers to a set of standardized parts or independent units that can
be used to construct a more complex structure. TypeScript modules provides a way to organize
the code for better reuse.
export interface InterfaceName
{
//Block of statements
}
PROGRAM:
module_one12c.ts:
export function MaxDiscountAllowed(noOfProduct: number): number {
if (noOfProduct > 5) { return 30; }
else { return 10; }
}
class Utility {
CalculateAmount(price: number, quantity: number): number {
return price * quantity;
}
}
interface Category { getCategory(productId: number): string; }
export const productName = 'Mobile';
export { Utility, Category };
module_two12c.ts:
import {Utility as mainUtility, Category, productName, MaxDiscountAllowed } from
"./module_one12c";
const util = new mainUtility();
const price = util.CalculateAmount(1350, 4);
const discount = MaxDiscountAllowed(2);
console.log(`Maximum discount allowed is: ${discount}`);
console.log(`Amount to be paid: ${price}`);
console.log(`ProductName is: ${productName}`);
OUTPUT:
AIM: To create a generic array and function to sort numbers as well as string values.
DESCRIPTION: Whenever any program or code is written or executed, one major thing one
always takes care of which is nothing but making reusable components which further ensures
the scalability and flexibility of the program or the code for a long time. Generics, thus here
comes into the picture as it provides a user to flexibly write the code of any particular data type
(or return type) and that the time of calling that user could pass on the data type or the return
type specifically. Generics provides a way to make the components work with any of the data
types (or return types) at the time of calling it for a certain number of parameters (or
arguments). In generics, we pass a parameter called type parameter which is put in between the
lesser sign (<),and the greater sign (>) for example, it should be like <type_parameter_name>.
PROGRAM:
// declaring a Generic Array named orderDetails
function orderDetails<T>(arg: Array<T>): Array<T> {
console.log(arg.length);
return arg;
}
const orderid: Array = [201, 202, 203, 204];
const ordername: Array = ['Dresses', 'Toys', 'Footwear', 'cds'];
const idList = orderDetails(orderid);
console.log(idList);
const nameList = orderDetails(ordername);
console.log(nameList);
OUTPUT: