MST Lab Manual (R20)
MST Lab Manual (R20)
MST Lab Manual (R20)
MEANStackTechnologiesLaboratory(20CS6S06)
IVB.Tech I Sem
(R20 Regulation)
LAB MANUAL
Prepared by
M V Rajesh
Associate Professor
Pragati Engineering College
(Autonomous)
(Approved by AICTE, New Delhi & Affiliated to JNT University, Kakinada)
1-378, ADB Road, Surampalem – 533 437
INDEX
1
Department of CSE(DS),PEC
MEANStackTechnologiesLab Manual
2
Department of CSE(DS),PEC
MEANStackTechnologiesLab Manual
3
Department of CSE(DS),PEC
MEANStackTechnologiesLab Manual
Excersice-1:
ProblemStatement1:
VerifyhowtoexecutedifferentfunctionssuccessfullyintheNode.jsplatform.
Todo:
Step1:Createafiledemo.jsinthefolder created earlier.
Step2:Addthefollowinglinesofcodeinthecreated file.
functiontester(){
alert("Hello! Iamanalertbox!");
}
tester();
Step3:Runthecodeandobservetheoutput.
Step4: Modifythecodeasshownbelow:
functiontester(){ var
message;
if(confirm("Pressabutton!"))
{
message="YoupressedOK!";
}
else
{
message="YoupressedCancel!";
}
console.log(message);
}
tester();
Step5:Runthecodeandobservetheoutput.
Observation
Functionsthatperform browserinteractionarenot compatiblewithNode.js.You can try out other
functionsas well and observe the output.
4
Department of CSE(DS),PEC
MEANStackTechnologiesLab Manual
ProblemStatement2:
WriteaprogramtoshowtheworkflowofJavaScriptcodeexecutablebycreatingwebserverin Node.js.
Highlights:
Using require() and createServer()method
RunningawebserverinNode.js
Demo steps:
Step1:CreateanewJavaScriptfilehttpserver.js andincludetheHTTPmodule
consthttp=require("http");
Step2:Use thecreateServer()methodoftheHTTPmoduletocreateawebserver.
var server=http.createServer((req,res)=>
{
res . write ("Hello World! I have created my first server!");
res.end();
});
server.listen(3000);
console.log("Serverstarted...Runningonlocalhost:3000");
Step4:Wewillobservethefollowinginthebrowser.
ThuswehavecreatedaNodeserverandsenttheresponsefromtheservertotheclient.
5
Department of CSE(DS),PEC
MEANStackTechnologiesLab Manual
Excersice-2:
ProblemStatement1:
WriteaNode.jsmoduleto showtheworkflowofModularization ofNodeapplication.
Highlights:
Creatingamodule
Loadingthemodule
Demosteps:
LetustryouthowtocreateandloadamoduleinaNodeapplication
Step1:CreateafileDBModule.jswithintheNodeJSfoldercreated earlier.
exports.authenticateUser=(username,password)=>{
if(username==="admin"&&password==="admin"){ return
"Valid User";
}elsereturn"InvalidUser";
};
Step2:Modifythefile httpserver.jsfilecreatedearlierasbelow.
app.js
consthttp=require("http");
vardbmodule= require("./DBModule");
var server = http.createServer((request, response) => {
result = dbmodule.authenticateUser("admin","admin");
response.writeHead(200,{"Content-Type":"text/html"});
response.end("<html><body><h1>"+result +"</h1></body></html>");
console.log("Request received");
});
server.listen(3000);
console.log("Serverisrunningatport3000");
Inthehttpserver.jsfile,weareloadingthemodule"DBModule"andtheninvokingthefunction named
"authenticateUser()".
Step3:Runthe httpserver.jsusingthenodecommand
6
Department of CSE(DS),PEC
MEANStackTechnologiesLab Manual
7
Department of CSE(DS),PEC
MEANStackTechnologiesLab Manual
ProblemStatement2:
WriteaprogramtoshowtheworkflowofrestartingaNodeapplication.
Wheneverwe are working on a Node.jsapplication and we do any change in code after the
applicationis started, wewill berequiredtorestarttheNodeprocessforchangestoreflect. Inorderto
restartthe server andto watchfor any code changesautomatically, we canuse the Nodemon tool.
Nodemon
Itisveryeasytogetstartedwiththistool.Toinstallitintheapplication,runthebelowcommand.
npminstallnodemon-g
Once the 'nodemon' is installed in the machine, the Node.js server code canbe executed byreplacing
the command"node" with "nodemon".
nodemonapp.js
Observetheconsoleonstartingthenodemoninacommandpromptwindow.
8
Department of CSE(DS),PEC
MEANStackTechnologiesLab Manual
});
server.listen(3000);
console.log("Serverstarted...Runningonlocalhost:3000");
Toavoidoverandoverrestartingofserverforsmallchangestoreflect.Itisimportant tohavean
automaticrestartoftheserver ofyour application. Use nodemon for this purpose.
9
Department of CSE(DS),PEC
MEANStackTechnologiesLab Manual
ProblemStatement3:
Createatextfilesrc.txtand addthefollowingdatato it.Mongo,Express,Angular,Node.
Creatingatextfile:
constfs=require('fs');
const{ promisify } = require('util');
constwriteFile=promisify(fs.writeFile);
(async () => {
try{
await writeFile('src.txt', `Mongo, Express,Angular,Node`);
console.log('Filecreatedsuccessfullywithpromisify and async/await!');
} catch (err) {
console.log(err);
}
})();
Output:
Readingatext file:
constfs=require('fs');
const{ promisify } = require('util');
constreadFile=promisify(fs.readFile);
(async () => {
try{
constfileData=awaitreadFile('src.txt','utf8');
console.log(fileData);
} catch (err) {
console.log(err);
}
})();
Output:
10
Department of CSE(DS),PEC
MEANStackTechnologiesLab Manual
Excersice-3:
ProblemStatement1:
Implementroutingforthe Adventure Trailsapplicationbyembedding thenecessarycodeinthe
routes/route.js file.
Step1:Setuptheproject
Createanewdirectoryfor your projectandnavigate intoit:
bash
mkdirAdventureTrailsApp
cd AdventureTrailsApp
Initializetheprojectandcreateapackage.jsonfile:
bash
npminit-y
Step2:InstallExpress
InstallExpressinyourproject:
bash
npminstallexpress
Step 3: Create the directory structure
Createthefollowingdirectorystructure:
- AdventureTrailsApp
- routes
-trailRoutes.js
- index.js
- package.json
Step 4:Createtheindex.jsfile
Inthe`index.js` file,setuptheExpress serverandincludethe necessaryroutes:
javascript
constexpress=require('express');
const app = express();
consttrailRoutes=require('./routes/trailRoutes');
// Middlewaretoparserequestbodies as JSON app.use(express.json());
//UsetheAdventureTrailsroutes
app.use('/api/trails',trailRoutes);
//Starttheserver
constport=process.env.PORT||3000;
app.listen(port, () => {
console.log(`AdventureTrailsserverisrunningonhttp://localhost:${port}`);
});
Step5:CreatethetrailRoutes.jsfile
Inthe`routes/trailRoutes.js`file,definethe routesfortheAdventureTrailsapplication:
javascript
11
Department of CSE(DS),PEC
MEANStackTechnologiesLab Manual
constexpress=require('express');
const router = express.Router();
//Sampledatafor trails(replacethiswithyouractual datasourceordatabase) const
trails = [
{id:1,name:'AdventureTrail1',length:'10km'},
{id:2,name:'AdventureTrail2',length:'8km'},
{id:3,name:'AdventureTrail3',length:'15km'},
];
// Route to get all trails
router.get('/', (req,res)=>{
res.json(trails);
});
// Route to get a specific trail byID
router.get('/:id', (req, res) => {
consttrailId=parseInt(req.params.id);
const trail =trails.find((trail) =>trail.id===trailId); if
(trail) {
res.json(trail);
}else{
res.status(404).json({message:'Trailnotfound'});
}
});
//Addmoreroutesasperyour application'srequirements
module.exports= router;
Step6:Runtheapplication
12
Department of CSE(DS),PEC
MEANStackTechnologiesLab Manual
ProblemStatement2:
InmyNotesapplication:(i)wewanttohandlePOSTsubmissions.(ii)displaycustomizederror messages.
(iii) performlogging.
Handling post submissions in the myNotes application involves processing user input, validating it,
displaying customized error messages for any issues, and performing logging to keep track of
importantevents. Below,I'll outline the steps you cantake to achieve these functionalities:
1. *FormSubmissionandValidation*:
- CreateanHTMLformwithappropriateinputfields(e.g.,title,content)andasubmitbutton.
- Inthebackend,whentheformissubmitted,extractthedatafromtherequest.
- Validate the data to ensure it meets the required criteria (e.g., checkingifthe title and contentare
not empty and within character limits).
2. *DisplayCustomizedErrorMessages*:
- Ifanyvalidationfails,generatespecificerrormessagesfortheuser.
- Displaytheseerrormessagesontheform,sotheuserknowswhatneedstobecorrected.
- You can use server-side rendering or AJAX to handle formsubmissions and show errors without
refreshing the entire page.
3. *Logging*:
- Implement alogging mechanism to record important events and errors that occur duringthe form
submission process.
- Choosean appropriatelogging library orwritecustom logging functionstohandledifferent log levels
(e.g., info, warning, error).
- Logrelevantinformationsuchastheuser,timestamp,errormessage,andanyotheradditional details that
mightbeusefulfor debuggingor monitoring.
Here'sasimpleexample of how you could handle post submissions, show custom error messages, and
perform loggingin a Python-basedweb applicationusing Flask:
python
13
Department of CSE(DS),PEC
MEANStackTechnologiesLab Manual
app=Flask(name)
#Configurelogging
logging.basicConfig(filename='mynotes.log',level=logging.INFO
@app.route('/submit', methods=['POST'])
defsubmit_post():
#Getdatafromtheformsubmission
title = request.form.get('title')
content=request.form.get('content')
# Validate the data
ifnottitleornotcontent:
returnrender_template('form.html',error_message=error_message)
In thisexample,when the user submits the form, the `submit_post()` function is called, which extracts
the data, validates it, and shows an error message or saves the post based on the validation results.The
logging statementsare usedtokeep trackof important events inthe application.
14
Department of CSE(DS),PEC
MEANStackTechnologiesLab Manual
ProblemStatement3:
WriteaMongooseschematoconnectwithMongoDB.
ToestablishaconnectiontotheMongoDBdatabase,weneedtocreateaconnectionobjectusing Mongoose.
This is done throughthe below code:
const mongoose= require('mongoose');
mongoose.connect('mongodb://localhost:27017/Database_Name');
InLine 1,weareimportingthe Mongooselibraryintoour application.
InLine2,theconnect()methodtakesMongoDBprotocolfollowedbythehostandthedatabase name
asaparameter.
Let usnowestablish aconnection tothe MongoDBdatabase IntellectNotes for storing detailsusing the
below code:
const mongoose= require('mongoose');
mongoose.connect('mongodb://localhost:27017/IntellectNotes',{
useNewUrlParser: true,
useCreateIndex: true,
useFindAndModify:false,
useUnifiedTopology:true,
})
Line2:HerewearespecifyingtheURIwherethedatawillbestored/retrieved.Thesecond parameter
{ useNewUrlParser: true, useCreateIndex: true, useFindAndModify:false,
useUnifiedTopology:true}
istosuppressthebelowwarningsthrownbyMongoDB.
Implementationofcode:
First,make sureyouhaveinstalledtherequireddependencies:mongooseandMongoDB. bash
npminstallmongoosemongodb
Now,createafile(e.g.,`db.js`)todefinetheMongooseschemaandconnecttotheMongoDB database:
javascript
constmongoose=require('mongoose');
//Replace'your-mongodb-uri' withtheactualconnection stringtoyour MongoDBdatabase
constmongoURI= 'mongodb://localhost:27017/your-database-name';
15
Department of CSE(DS),PEC
MEANStackTechnologiesLab Manual
//ConnecttotheMongoDBdatabase
mongoose.connect(mongoURI,{
useNewUrlParser: true,
useUnifiedTopology:true,
})
.then(()=>console.log('MongoDBconnected successfully'))
.catch((err)=>console.error('ErrorconnectingtoMongoDB:',err.message));
// Define the Mongoose schema
constSchema=mongoose.Schema;
constnoteSchema=newSchema({
title: {
type: String,
required:true,
},
content: {
type:String,
required:true,
},
createdAt: {
type:Date,
default:Date.now,
},
});
// Create the 'Note' model using the 'noteSchema'
constNote =mongoose.model('Note',noteSchema);
module.exports= Note;
Inthis example, we create a simple schema for a `Note` withfields `title`,`content`,and `createdAt`.
We also connect to the MongoDB database using Mongoose and define a model called `Note` based
on the `noteSchema`.
Remember toreplace `'your-mongodb-uri'`withyour actual MongoDBconnectionstring.Thisshould
point to your MongoDBinstance, either locallyor ona cloud service like MongoDB Atlas.
ProblemStatement4:
Writeaprogramtowrapaschemaintomodelobject.
Createafile(e.g.,`noteModel.js`)to definetheMongooseschemaandwrapitintoaModel:
javascript
constmongoose=require('mongoose');
//Replace'your-mongodb-uri' withtheactualconnection stringtoyour MongoDBdatabase
constmongoURI= 'mongodb://localhost:27017/your-database-name';
16
Department of CSE(DS),PEC
MEANStackTechnologiesLab Manual
//ConnecttotheMongoDBdatabase
mongoose.connect(mongoURI,{
useNewUrlParser: true,
useUnifiedTopology:true,
})
.then(()=>console.log('MongoDBconnected successfully'))
.catch((err)=>console.error('ErrorconnectingtoMongoDB:',err.message));
required:true,
},
content: {
type:String,
required:true,
},
createdAt: {
type:Date,
default:Date.now,
},
});
// Create the 'Note' model using the 'noteSchema'
constNote =mongoose.model('Note',noteSchema);
module.exports= Note;
Now, in your main application file (e.g., `app.js`), you can use the `Note`model byimportingitfrom the
`noteModel.js` file:
Javascript
17
Department of CSE(DS),PEC
MEANStackTechnologiesLab Manual
const express=require('express');
constNote=require('./noteModel');//Import theNotemodel const
app = express();
//Yourapplicationroutesandothermiddlewarecanbedefinedhere
//Forexample:
app.get('/notes', async (req,res)=>{ try
{
//FetchallnotesfromtheMongoDBdatabaseusingtheNotemodel const
notes = await Note.find({});
//Respondwiththefetched notes
res.json(notes);
}catch (err){
// Handle errors, e.g., send an error response
res.status(500).json({error:'Errorfetchingnotes' });
}
});
// Start the server
constport=3000;
app.listen(port,()=>{
console.log(`Serverrunningonhttp://localhost:${port}`);
});
In the `app.js` file, we import the `Note` model from`noteModel.js`, and we can now use the `Note`
model to perform CRUD operations (e.g., `find`, `create`, `update`, `delete`) onthe `Note` collection
in the MongoDBdatabase.
Remember to replace `'your-mongodb-uri'` with your actual MongoDB connection string.
Additionally, ensure that the `noteModel.js` file and the `app.js` file are in the same directory or
provide the correct relative pathwhen importing the`Note` model.
18
Department of CSE(DS),PEC
MEANStackTechnologiesLab Manual
Excersice-4:
ProblemStatement1:
WriteaprogramtoperformvariousCRUD(Create-Read-Update-Delete)operationsusingMongooselibrary
functions.
Node.jsprogramthatusestheMongooselibrarytoperformCRUDoperationsonaMongoDBdatabase.Before
runningthisprogram,makesuretoinstallthenecessarydependenciesbyrunning npminstallmongoose
i
n your project directory.
constmongoose=require('mongoose')
//ConnecttoMongoDB
mongoose.connect('mongodb://localhost:27017/mydatabase',{useNewUrlParser:true,useUnifiedTopol
ogy:true });
constdb=mongoose.connection;
// Define a schema for the data
constuserSchema= new
mongoose.Schema({ name: String,
email:String,
age: Number
});
//Createamodelbasedontheschema
constUser=mongoose.model('User',userSchema);
//Createoperation
constcreateUser= async (name, email,age)
=>{ const user = new User({ name,
email,age }); await user.save();
console.log('Usercreated:',user);
};
//ReadoperationconstgetUs
ers= async () =>{ const
users = await User.find();
console.log('Users:',users);
};
//Updateoperation
constupdateUser=async(id,newData)=>{
19
Department of CSE(DS),PEC
MEANStackTechnologiesLab Manual
};
// Delete
operationconstdeleteUser=
async (id) => {
const user = awaitUser.findByIdAndDelete(id);
console.log('Userdeleted:', user);
};
//Exampleusage
asyncfunctionmain(){
//Create
awaitcreateUser('JohnDoe','john@example.com',25);
//Read
awaitgetUsers();
//Update
constuserIdToUpdate = '<user_id_to_update>';
constnewData = { age: 26 };
awaitupdateUser(userIdToUpdate,newData);
constuserIdToDelete=
'<user_id_to_delete>'; await
deleteUser(userIdToDelete);
// Read again after delete
await getUsers();
// Disconnect from MongoDB
mongoose.disconnect();
}
main().catch(err=>console.error(err));
20
Department of CSE(DS),PEC
MEANStackTechnologiesLab Manual
ProblemStatement2:
ToimplementthedescribedAPIsforfetchingandupdatingnotesinamyNotesapplication,youcanusea
Node.jsframeworklikeExpressalong withMongoose for MongoDB interactions.Below is a simple
example using Expressand Mongoose:
1. Install the necessary
dependencies: npm installexpress
mongoose
2. Createa server.js filewiththefollowingcode:
constexpress=require('express');co
nst mongoose=
require('mongoose');
constbodyParser=require('body-parser');
const app =
express(); const port
= 3000;
//ConnecttoMongoDB
mongoose.connect('mongodb://localhost:27017/myNotesDB',{useNewUrlParser:true,useUnifiedTopo
logy:true });
constdb=mongoose.connection;
//Createamodelbasedontheschema
const Note = mongoose.model('Note',noteSchema);
app.use(bodyParser.json());
// Fetch note detailsbased on
noteIDapp.get('/notes/:noteID',async
(req, res) => { constnoteID =
req.params.noteID;
try{
constnote=awaitNote.findById(noteID);
21
Department of CSE(DS),PEC
MEANStackTechnologiesLab Manual
if (note) {
res.json(note);
}else{
res.status(404).json({message:'Notenotfound'});
}
}catch(error){
res.status(500).json({message:'Internalservererror'});
}
});
if (updatedNote)
{
res.json(updatedNot
e);
}else{
res.status(404).json({message:'Notenotfound'});
}
}catch(error){
res.status(500).json({message:'Internalservererror'});
}
});
22
Department of CSE(DS),PEC
MEANStackTechnologiesLab Manual
ProblemStatement3:
Writeaprogramtoexplainsessionmanagementusingcookies.
Ina real-world application, youwould wantto implementmore robustsecuritymeasuresandpossibly use a
dedicated sessionmanagementlibrary.
1. First,installthenecessarydependencies:
npm install express cookie-parser
2. Createa filewiththefollowingcode:
const express = require('express');
server.js
constcookieParser = require('cookie-parser');
constapp=express(); const
port = 3000;
app.use(express.urlencoded({extended:true}));
app.use(cookieParser());
//Middlewaretocheckiftheuser isauthenticated
constisAuthenticated= (req, res, next) =>{ constuserCookie
= req.cookies.user;
if(userCookie&&userCookie==='authenticated'){
next();//Userisauthenticated,proceedtothenextmiddlewareorroute
}else{
res.status(401).send('Unauthorized');//Userisnotauthenticated
}
};
23
Department of CSE(DS),PEC
MEANStackTechnologiesLab Manual
//Loginroutesetsacookietoauthenticatethe user
app.post('/login', (req, res) => {
const{username,password}=req.body;
//Inarealapplication,youwouldperformproperauthenticationhere if
(username=== 'user' && password === 'password') {
res.cookie('user', 'authenticated');
res.send('Loginsuccessful');
} else {
res.status(401).send('Loginfailed');
}
});
//Logout routeclearstheauthenticationcookie
app.post('/logout', (req, res) => {
res.clearCookie('user');
res.send('Logoutsuccessful');
});
constapp=express(); const
port = 3000;
24
Department of CSE(DS),PEC
MEANStackTechnologiesLab Manual
//Usetheexpress-sessionmiddleware
app.use(session({
secret:'mySecretKey', resave: false,
saveUninitialized: true,
cookie:{ secure:false} //SettotrueifusingHTTPS
}));
//Loginroutesetstheusersessiontoauthenticate
app.post('/login', (req, res) => {
const{username,password}=req.body;
//Inarealapplication,youwouldperformproperauthenticationhere if
(username=== 'user' && password === 'password') { req.session.user
= 'authenticated';
res.send('Loginsuccessful');
} else {
res.status(401).send('Loginfailed');
}
});
25
Department of CSE(DS),PEC
MEANStackTechnologiesLab Manual
//Logout routedestroystheusersession
app.post('/logout', (req, res) => {
req.session.destroy((err) => {
if (err) {
console.error(err);
}
res.send('Logoutsuccessful');
});
});
});
The express-session middleware is used to handle sessions. It is configured witha secretkey, and
the session data is stored in memory by default (for simplicity; in production, you might use a more
robust store like Redis).
The/login routesetstheuserpropertyinthesessionto'authenticated'upon successfullogin.
The/dashboardrouteisprotectedbytheisAuthenticatedmiddleware,whichchecksiftheuser
propertyinthesessionissetto 'authenticated'.
26
Department of CSE(DS),PEC
MEANStackTechnologiesLab Manual
Excersice-5:
ProblemStatement1:
Onthepage,displaythepriceofthemobile-basedinthreedifferentcolors.Insteadofusingthe numberinour
code,representthem bystring values likeGoldPlatinum,PinkGold, SilverTitanium.
<!DOCTYPEhtml>
<htmllang="en">
<head>
<metacharset="UTF-8">
<metaname="viewport"content="width=device-width,initial-scale=1.0">
<title>MobilePrices</title>
<style>
/*Definestylesfordifferentcolors*/
.gold-platinum{color: gold;}
.pink-gold{color:pink;}
.silver-titanium{color:silver;}
</style>
</head>
<body>
27
Department of CSE(DS),PEC
MEANStackTechnologiesLab Manual
<h1>MobilePrices</h1>
<divid="goldPlatinumPrice"class="gold-platinum"></div>
<divid="pinkGoldPrice"class="pink-gold"></div>
<divid="silverTitaniumPrice"class="silver-titanium"></div>
<script>
//Definepricevaluesasstringconstants constGoldPlatinum
= "GoldPlatinum"
28
Department of CSE(DS),PEC
MEANStackTechnologiesLab Manual
constPinkGold= "PinkGold";
constSilverTitanium = "SilverTitanium";
//Functiontodisplaypricesdynamically
functiondisplayPrices() {
constgoldPlatinumPriceElement= document.getElementById("goldPlatinumPrice");
constpinkGoldPriceElement= document.getElementById("pinkGoldPrice");
constsilverTitaniumPriceElement= document.getElementById("silverTitaniumPrice");
//Callthefunction to displayprices
displayPrices();
</script>
</body>
</html>
29
Department of CSE(DS),PEC
MEANStackTechnologiesLab Manual
ProblemStatement2:
Define an arrow function inside the event handler to filter the productarraywiththe selected product
object using the productId received by the function. Pass the selected product object to the next
screen.
<!--Assumingyouhaveabuttonorsomeclickableelementtriggeringtheevent-->
<buttonid="selectProductButton">SelectProduct</button>
<script>
//Samplearrayofproducts
const products = [
{productId:1,productName:'ProductA',price:100},
{productId:2,productName:'ProductB',price:150},
{productId:3,productName:'ProductC',price:120}
//...more products
];
if(selectedProduct){
30
Department of CSE(DS),PEC
MEANStackTechnologiesLab Manual
//Assumingyouwanttopasstheselectedproducttothenextscreen(console.logfor demonstration)
console.log('SelectedProduct:',selectedProduct);
//Addcodeheretonavigatetothenextscreenorperformotheractions
}else{
console.error('Productnotfound!');
};
31
Department of CSE(DS),PEC
MEANStackTechnologiesLab Manual
</script>
ProblemStatement3:
//Samplearrayofmobiles
const mobiles = [
{id:1,vendor:'Apple',model:'iPhone 12',price:999},
{id:3,vendor:'Apple',model:'iPhoneSE',price:399},
//...more mobiles
];
32
Department of CSE(DS),PEC
MEANStackTechnologiesLab Manual
};
//Example usage
constappleMobiles=getMobileByVendor('Apple');
33
Department of CSE(DS),PEC
MEANStackTechnologiesLab Manual
ProblemStatement4:
{id:null,price:150},
{id:null, price:200},
{id:null, price:250}
];
//Implementanarrowfunction-myFunctiontopopulatethe idparameter
constmyFunction= (array, thresholdPrice) =>{
array.forEach(manufacturer=> {
if(manufacturer.price>=thresholdPrice){
//Populatetheidparameterbasedonthecondition
34
Department of CSE(DS),PEC
MEANStackTechnologiesLab Manual
manufacturer.id= manufacturer.price;
}
});
};
//CallmyFunctionwiththemanufacturersarrayandathresholdprice
35
Department of CSE(DS),PEC
MEANStackTechnologiesLab Manual
myFunction(manufacturers,150);
{id:150,price:150},
{id:200,price:200},
{id:250,price:250}
ProblemStatement5:
Declare a function - getMobileByManufacturer with two parameters namely manufacturer and id,
where manufacturer value should passed as Samsung and id parameter should be optional while
invoking the function,ifid is passed as 101 thenthis functionshoul
functiongetMobileByManufacturer(manufacturer,id=101){
//Logic tofetchmobiledetailsbasedonthemanufacturerandoptionalid
//Fordemonstration purposes,let'screateasampledataobject
constmobilesDatabase = {
Samsung:[
36
Department of CSE(DS),PEC
MEANStackTechnologiesLab Manual
{id:101,model:'GalaxyNote20',price:1099},
//Addmore Samsungmobilesasneeded
],
//Addmoremanufacturersandtheirmobiles asneeded
};
//Checkiftheprovidedmanufacturerexistsinthedatabase
37
Department of CSE(DS),PEC
MEANStackTechnologiesLab Manual
if(manufacturerinmobilesDatabase) {
constmobiles=mobilesDatabase[manufacturer];
if (selectedMobile) {
returnselectedMobile;
}else{
return`Nomobilefoundwithid${id}formanufacturer${manufacturer}`;
}else{
return`Manufacturer${manufacturer}notfoundinthedatabase`;
//Example usage:
constmobileDetails=getMobileByManufacturer('Samsung',101);
console.log(mobileDetails);
38
Department of CSE(DS),PEC
MEANStackTechnologiesLab Manual
//Output
{id:101,model:'GalaxyNote20',price:1099}
39
Department of CSE(DS),PEC
MEANStackTechnologiesLab Manual
Excersice-6:
ProblemStatement1:
ImplementbusinesslogicforaddingmultipleProductvaluesintoacartvariablewhichistypeofstringarray.
class ShoppingCart{
privatecart:string[]=[];
//Addasingleproductto the cart
addProduct(product: string) {
this.cart.push(product);
}
//Exampleusage
constshoppingCart=new ShoppingCart();
constproductsToAdd =["ProductB","ProductC","ProductD"];
shoppingCart.addProducts(productsToAdd);
// Getting the current contentsofthe cart
constcartContents=shoppingCart.getCartContents();
console.log("Cart Contents:",cartContents);
40
Department of CSE(DS),PEC
MEANStackTechnologiesLab Manual
ProblemStatement2:
Declareaninterfacenamed-ProductwithtwopropertieslikeproductIdandproductNamewithanumberand
stringdatatypeand need to implementlogicto populatethe Product details.
//DeclaretheProductinterface
interface Product {
productId: number;
productName:string;
}
//Functionto populateproductdetails
functionpopulateProductDetails(id:number,name: string):Product{
//CreateanewProductobject const
product: Product = { productId: id,
productName:name,
};
//Returnthepopulatedproduct
return product;
}
//Example usage
constproduct1:Product=populateProductDetails(1,"ProductA");
constproduct2:Product=populateProductDetails(2,"ProductB");
// Display product details
console.log("Product1:",product1);
console.log("Product2:",product2);
41
Department of CSE(DS),PEC
MEANStackTechnologiesLab Manual
ProblemStatement3:
Declareaninterfacenamed-ProductwithtwopropertieslikeproductIdandproductNamewiththenumber and
stringdatatypeand need to implementlogicto populatethe Product details.
//DeclaretheProductinterface
interface Product {
productId: number;
productName:string;
}
//Functiontopopulateproductdetails
functionpopulateProductDetails(id:number,name:string):Product{
//CreateanewProductobject const
product: Product = { productId: id,
productName:name,
};
//Returnthepopulatedproduct
return product;
}
//Example usage
constproduct1:Product=populateProductDetails(1, "ProductA");
constproduct2:Product=populateProductDetails(2,"ProductB");
// Display product details
console.log("Product1:",product1);
console.log("Product2:",product2);
ProblemStatement4:
Declareaninterfacewithfunctiontypeandaccessitsvalue.
//Declareaninterfacewithafunctiontype
interface MyFunction{
(param1:number,param2:string):void;
42
Department of CSE(DS),PEC
MEANStackTechnologiesLab Manual
//Accessthefunction
myFunctionImplementation(42,"Hello,TypeScript!");
1. TheMyFunctioninterfaceisdeclaredwithafunctiontypethattakestwoparameters
(param1oftype numberand param2oftype string) and returns void.
2. ThemyFunctionImplementationvariableisdeclaredandassigneda functionthatmatches the
signaturedefined intheMyFunctioninterface.
3. YoucanthenaccessthefunctionbycallingmyFunctionImplementationwiththe appropriate
arguments.
43
Department of CSE(DS),PEC
MEANStackTechnologiesLab Manual
Excersice-7:
ProblemStatement1:
InstallingMongoDBLocally:
1. DownloadMongoDB:
VisittheMongoDBdownloadpage:MongoDBDownloadCenter.
Chooseyouroperatingsystemand downloadtheappropriateversion.
2. InstallMongoDB:
Followtheinstallationinstructionsforyouroperatingsystem.
For Windows,theinstaller will guideyouthroughtheinstallationprocess.Makesure to
install MongoDBas a service.
3. Start MongoDB:
Once the installationiscomplete,starttheMongoDBservice.OnWindows,thismay
involve starting the service through the Services application.
4. VerifyInstallation:
Open acommandprompt orterminalandrun thefollowing command to connect to the
MongoDBserver:
mongo
ThisshouldconnectyoutotheMongoDBshell.
ConfiguringMongoDB Atlas:
1. CreateaMongoDBAtlasAccount:
VisittheMongoDBAtlaswebsite:MongoDBAtlas.
Clickon"GetStartedFree"tocreatean account.
2. CreateaNewCluster:
Afterloggingin,clickon"BuildaCluster."
Chooseyourpreferredcloudprovider,region,andothersettings.
Clickon"CreateCluster"tostartthedeployment.
3. ConfigureNetworkAccess:
Intheleftsidebar,clickon"DatabaseAccess"andcreateanewdatabase user.
Intheleftsidebar,clickon"NetworkAccess"andaddyourIPaddresstotheIP Whitelist.
4. ConnecttoYourCluster:
Intheleftsidebar,clickon"Clusters"andthenclickon"Connect"foryourcluster.
Choose"ConnectYourApplication"andcopytheconnectionstring.
5. UpdateYourApplicationConnectionString:
Ifyou'reusingaNode.jsapplication,forexample,replacethe<password>,
<dbname>,and other placeholders inthe connectionstringwithyour actual credentials and database
name.
44
Department of CSE(DS),PEC
MEANStackTechnologiesLab Manual
6. TesttheConnection:
ConnectyourapplicationtoMongoDBAtlasusingtheupdatedconnectionstring.
VerifythatyourapplicationcansuccessfullyconnecttotheMongoDBAtlas cluster.
ProblemStatement2:
WriteMongoDBqueriestoperformCRUDoperationsondocumentusinginsert(),find(),update(),remove()
InsertDocuments:
//Insertasingledocumentintoacollection db.products.insert({
name:"Laptop",
price: 1200,
category:"Electronics"
});
//Insertmultipledocumentsintoacollection db.products.insertMany([
{name:"Smartphone",price:600,category:"Electronics"},
{name:"Book",price:20,category:"Books"}
]);
1. FindDocuments:
//Findalldocuments inthe"products" collection
db.products.find();
//Finddocumentsthatmatch aspecificcondition
db.products.find({ category:"Electronics" });
2. UpdateDocuments:
//Updateasingledocument
db.products.update({name:"Laptop"},{$set:{price:1300}});
45
Department of CSE(DS),PEC
MEANStackTechnologiesLab Manual
//Updatemultiple documents
db.products.update({category:"Electronics"},{$inc:{price:50}},{multi:true });
//Update orinsertadocumentifitdoesn'texist
db.products.update(
{name:"Tablet"},
{ $set:{price:300,category:"Electronics"}},
{upsert:true}
);
3. Remove Documents:
// Remove a single document
db.products.remove({name:"Book"});
46
Department of CSE(DS),PEC
MEANStackTechnologiesLab Manual
Excersice-8:
ProblemStatement1:
WriteMongoDBqueriestoCreateanddropdatabasesandcollections.
1. CreateDatabase:
2. DropDatabase:
//Drop(delete)thecurrentdatabase
db.dropDatabase()
3. CreateCollection:
4. DropCollection:
//Drop(delete)the"mycollection" collection
db.mycollection.drop()
Thiscommandpermanentlydeletesthespecifiedcollection.
ProblemStatement2:
Write MongoDBqueriestoworkwithrecordsusingfind(),limit(),sort(),createIndex(),aggregate().
1. FindDocuments:
47
Department of CSE(DS),PEC
MEANStackTechnologiesLab Manual
//Findalldocuments inthe"mycollection"collection
db.mycollection.find()
//Finddocumentsthatmatch aspecificcondition
db.mycollection.find({category:"Electronics"})
48
Department of CSE(DS),PEC
MEANStackTechnologiesLab Manual
//Findthefirst5documentsinthe"mycollection"collection
db.mycollection.find().limit(5)
3. SortDocuments:
db.mycollection.find().sort({price:1})
4. CreateIndex:
5. Aggregate:
$group:{
_id: "$category",
avgPrice:{$avg:"$price"}
}
},
49
Department of CSE(DS),PEC
MEANStackTechnologiesLab Manual
$sort: {
avgPrice:-1
}
])
50
Department of CSE(DS),PEC
MEANStackTechnologiesLab Manual
Excersice-9:
ProblemStatement1:
ModuleName:AngularApplicationSetup
Observethelinkhttp://localhost:4200/welcomeonwhichthemCartapplicationis running.Performthe
belowactivitiestounderstandthe featuresofthe application.
2.InstallAngularCLI: Openaterminalorcommandpromptandrunthefollowingcommandtoinstallthe
AngularCLI globallyon your machine:
npminstall-g@angular/cli
5.InstallDependencies: Installtheprojectdependenciesusingthefollowingcommand:
npminstall
6.RuntheApplication: StarttheAngulardevelopmentserverwiththefollowingcommand:
ngserve
athttp://localhost:4200.
Thiswillcompiletheapplicationandstartadevelopmentserver.Bydefault,theapplicationwillbeaccessible
51
Department of CSE(DS),PEC
MEANStackTechnologiesLab Manual
ProblemStatement2:
ModuleName:ComponentsandModules
CreateanewcomponentcalledhelloandrenderHelloAngularonthepage.
1.OpenaTerminalorCommandPrompt: Openaterminalorcommandpromptintheprojectdirectory
whereyouwanttocreatethenewcomponent.
2.GenerateaNewComponent: RunthefollowingAngularCLIcommandtogenerateanewcomponent
named"hello":
nggeneratecomponenthello
src/app
Thiscommandcreatesanewfoldernamed hello inthe directorywiththenecessaryfilesforthe
Angularcomponent.
<p>HelloAngular</p>
Thissimpletemplatewillrenderthetext"HelloAngular"onthepage.
@NgModule({
declarations:[
//...othercomponents
HelloComponent,
],
//...otherconfigurations
})
52
Department of CSE(DS),PEC
MEANStackTechnologiesLab Manual
component'stemplat
e.
7.RuntheApplication: IfyourAngulardevelopmentserverisnotrunning,startitwiththefollowing
ngserve
command:
Openyourwebbrowserandnavigatetohttp://localhost:4200.Youshouldsee"Hello Angular"renderedonthe
page.
53
Department of CSE(DS),PEC
MEANStackTechnologiesLab Manual
ProblemStatement3:
import{Component}from'@angular/core';
@Component({ selector:
'app-hello',
templateUrl: './hello.component.html',
styleUrls:['./hello.component.css']
})
changeCourseName(){this.courseName =
'New Course Name';
}
Openthe fileandaddaclickeventtothe"Hello
2.Updatehello.component.html: hello.component.html
Angular"text
:
<p(click)="changeCourseName()">Hello{{courseName}}</p>
54
Department of CSE(DS),PEC
MEANStackTechnologiesLab Manual
55
Department of CSE(DS),PEC
MEANStackTechnologiesLab Manual
3.RuntheApplication: IfyourAngulardevelopmentserverisnotrunning,startitwiththefollowing
command:
Openyourwebbrowserandnavigatetohttp://localhost:4200.Youshouldsee"HelloAngular"displayedon
the page.Clickingon itshouldchangethe textto "HelloNew Course Name".
Now,your hello componentrespondstoaclickeventandupdatesthe propertyaccordingly.
courseName
ProblemStatement4:
ModuleName:ChangeDetectionprogressivelybuildingthePoolCarzapplication.
Let'sprogressivelybuildasimple"PoolCarz"applicationandexplorechangedetectioninAngular.We'llcreat
e acomponentthatdisplaysalistofcarsandallowsuserstoaddnewcarstothelist.
src/app
1.CreateaCarModel: Createafilenamed car.model.ts inthe directorywiththefollowingcontent:
exportinterfaceCar{
id:number;
make:string;
model:string;
year:number;
}
2.CreateaCarService: Generateaservicetomanagethelistofcars.Runthefollowingcommandinthe
nggenerateservicecar
terminal:
Openthegeneratedcar.service.tsfileandimplementabasicservicethatinitializesandmanagesthelistof cars.
//car.service.ts
import{Injectable}from'@angular/core';
import{Car}from'./car.model';
56
Department of CSE(DS),PEC
MEANStackTechnologiesLab Manual
@Injectable({
providedIn:'root',
})
exportclassCarService{
privatecars:Car[]=[];
getCars():Car[]{
returnthis.cars;
}
addCar(car:Car):void{
this.cars.push(car);
57
Department of CSE(DS),PEC
MEANStackTechnologiesLab Manual
}
}
3.CreateaCarComponent: Generateacomponenttodisplaythelistofcarsandallowuserstoaddnewcars.
Runthefollowingcommandintheterminal:
nggeneratecomponentcar-list
Openthegenerated car-list.component.ts
//car-list.component.ts fileandimplementthecomponentlogic.
import{Component}from'@angular/core';
import{CarService}from'../car.service';
import{Car}from'../car.model';
@Component({
selector:'app-car-list',
templateUrl:'./car-list.component.html',
styleUrls:['./car-list.component.css'],
})
exportclassCarListComponent{
cars:Car[]=[];
newCar:Car={id:0,make:'',model:'',year:0};
constructor(privatecarService:CarService){
this.cars=carService.getCars();
}
addCar():void{
this.carService.addCar({...this.newCar,id:this.cars.length+1});
this.newCar={id:0,make:'',model:'',year:0};
58
Department of CSE(DS),PEC
MEANStackTechnologiesLab Manual
}
}
Openthe fileandupdateittodisplaythelist
4.UpdateCarComponentTemplate: car-list.component.html
ofcarsandaformtoaddnewcars.
<!--car-list.component.html-->
<h2>PoolCarz</h2>
<ul>
<li*ngFor="letcarofcars">{{car.make}}{{car.model}}({{car.year}})</li>
</ul>
<div>
<h3>AddaNewCar</h3>
<form(ngSubmit)="addCar()">
59
Department of CSE(DS),PEC
MEANStackTechnologiesLab Manual
<label>Make:<input[(ngModel)]="newCar.make"/></label>
<label>Model:<input[(ngModel)]="newCar.model"/></label>
<label>Year:<inputtype="number"[(ngModel)]="newCar.year"/></label>
<buttontype="submit">AddCar</button>
</form>
</div>
app.module.ts
ngModel.
Openthe fileandincludethe
5.UpdateAppComponentTemplate: app.component.html app-car-list
component
<!--app.component.html--
>
<div>
<app-car-list></app-car-
list>
</div>.
6.RuntheApplication: IfyourAngulardevelopmentserverisnotrunning,startitwiththefollowing
ngserve
command:
60
Department of CSE(DS),PEC
MEANStackTechnologiesLab Manual
Excersice-10:
ProblemStatement1:
CourseName:AngularJS
ModuleName:StructuralDirectives-ngIfCreatealoginformwithusernameand
passwordfields.Iftheuserentersthecorrectcredentials,itshouldrendera"Welcome
<>"messageotherwiseitshouldrender"InvalidLogin!!!Pleasetryagain..."message.
<div*ngIf="isLoggedIn;elseinvalidLogin">
<p>Welcome{{username}}!</p>
</div>
<ng-template#invalidLogin>
<p>InvalidLogin!!!Pleasetryagain...</p>
</ng-template>
In thistemplate:
Weusetwo-way databinding ([(ngModel)])tobindtheinputfieldstothe
properties.
(ngSubmit) login()
username and password
61
Department of CSE(DS),PEC
MEANStackTechnologiesLab Manual
Theformhasa eventthatcallsthe method.
ngIf
Weusethe directivetoconditionallyrendereitherthewelcomemessageortheinvalidlogin
message.
//login.component.ts
import{Component}from'@angular/core';
62
Department of CSE(DS),PEC
MEANStackTechnologiesLab Manual
@Component({ selector:
'app-login',
templateUrl:'./login.component.html',
styleUrls:['./login.component.css'],
})
export class LoginComponent{
username: string = '';password:
string = '';
isLoggedIn:boolean=false;
login():void{
//Replacethiswithyouractualauthenticationlogic
// For simplicity,we'll consider it a successful loginif both fields are non-emptyif
(this.username&&this.password) {
this.isLoggedIn=true;
} else {
this.isLoggedIn= false;
}
}
}
Note:Inareal-worldscenario,youwouldperformactualauthentication,possiblywithaserviceorAPIcall.
//app.module.ts
import { BrowserModule } from '@angular/platform-browser'; import {
NgModule} from '@angular/core';
import{FormsModule}from'@angular/forms';
import{AppComponent}from'./app.component';
import{LoginComponent}from'./login/login.component';
@NgModule({
declarations: [AppComponent, LoginComponent],
imports: [BrowserModule,FormsModule], providers: [],
bootstrap:[AppComponent],
})
exportclassAppModule{}
63
Department of CSE(DS),PEC
MEANStackTechnologiesLab Manual
5.RuntheApplication:IfyourAngulardevelopmentserverisnotrunning,startitwiththefollowing
command:
ngserve
Openyourwebbrowserandnavigatetohttp://localhost:4200.Youshouldseetheloginform.Tryentering
somecredentials,andyou'llseeeitherthewelcomemessageortheinvalidloginmessagebasedonthelogicin
the login() method.
Thisexampledemonstratestheuseofthe ngIf directivetoconditionallyrendercontentbasedonthelogin
status.
ProblemStatement2:
@Component({ selector:
'app-root',
templateUrl: './app.component.html', styleUrls:
['./app.component.css'],
})
exportclassAppComponent{
courses:string[]=['Angular','React','Vue','Node.js','Express'];
}
2. UpdateAppComponentTemplate: Openthe app.component.html fileandusethe
ngFor directivetoiterateoverthe courses arrayandrenderitinalistformat:
<!--app.component.html-->
<h2>Courses</h2>
<ul>
<li*ngFor="letcourseofcourses">{{course}}</li>
</ul>
In this template, the and*ngFor directive is used to loop over each course inthe courses array
render it inside an <li> element.
64
Department of CSE(DS),PEC
MEANStackTechnologiesLab Manual
3. Run the Application:If your Angular development server is not running, start it with the following
command:
ngserve
Openyourwebbrowserandnavigatetohttp://localhost:4200.Youshouldsee a list of courses rendered on
the page.
65
Department of CSE(DS),PEC
MEANStackTechnologiesLab Manual
ProblemStatement3:
ModuleName:ngSwitch
DisplaythecorrectoptionbasedonthevaluepassedtongSwitchdirective.
Openthe fileanddefineavariabletocontrolthe
1.UpdateAppComponentTypeScript: app.component.ts
switch:
//app.component.t
s
import{Component}from'@angular/core';
@Component({
selector: 'app-root',
templateUrl:'./app.component.html'
, styleUrls:['./app.component.css'],
})
export class AppComponent{
selectedOption:string = 'option1';
}
<!--app.component.html-->
<h2>Options</h2>
<div[ngSwitch]="selectedOption">
<p*ngSwitchCase="'option1'">Option1isselected.</p>
<p*ngSwitchCase="'option2'">Option2isselected.</p>
<p*ngSwitchCase="'option3'">Option3isselected.</p>
<p*ngSwitchDefault>Selectanoption.</p>
</div>
66
Department of CSE(DS),PEC
MEANStackTechnologiesLab Manual
<!--Changeoption-->
<div>
<label>Selectanoption:</label>
<select[(ngModel)]="selectedOption">
<optionvalue="option1">Option1</option>
<optionvalue="option2">Option2</option>
<optionvalue="option3">Option3</option>
</select>
</div>
67
Department of CSE(DS),PEC
MEANStackTechnologiesLab Manual
In thistemplate:
<div> element,anditsvalueisboundtothe selectedOption
The ngSwitch directiveisappliedtoa
variable.
Differentcasesaredefinedusingthe *ngSwitchCase directive,andadefaultcaseisdefinedusing
*ngSwitchDefault.
ThecontentinsideeachcaseisconditionallydisplayedbasedonthevalueofselectedOption.
A <select> elementisincludedtochangethevalueof selectedOption dynamically.
3.RuntheApplication: IfyourAngulardevelopmentserverisnotrunning,startitwiththefollowing
comman
d: ng
serve
Openyourwebbrowserandnavigatetohttp://localhost:4200.Youshouldseetheoptionsdisplayedbasedon
the initial value ofselectedOption. Changing the value in the dropdown will update the displayed
option accordingly.
Thisexampledemonstrateshowtousethe ngSwitch directivetoconditionallyrenderdifferentoptionsbased
ProblemStatement4:
ModuleName:CustomStructuralDirectiveCreateacustomstructuraldirectivecalled
'repeat'whichshouldrepeat the elementgivenanumberoftimes.
1.CreatetheDirective: Runthefollowingcommandinyourterminaltogenerateanewdirective:
nggeneratedirectiverepeat
//repeat.directive.ts
68
Department of CSE(DS),PEC
MEANStackTechnologiesLab Manual
@Directive({
selector:'[appRepeat]',
})
exportclassRepeatDirective{
69
Department of CSE(DS),PEC
MEANStackTechnologiesLab Manual
constructor(
In thisdirective:
appRepeat
3.UsetheCustomDirective: Openthe app.component.html fileandusethe directivetorepeatan
elementa specifiednumber of times:
<!--app.component.html-->
<h2>RepeatDirectiveExample</h2>
<div*appRepeat="3">
<p>Thisparagraphwillberepeatedthreetimes.</p>
</div>
70
Department of CSE(DS),PEC
MEANStackTechnologiesLab Manual
//app.module.ts
71
Department of CSE(DS),PEC
MEANStackTechnologiesLab Manual
@NgModule({
bootstrap:[AppComponent],
})
exportclassAppModule{}
5.RuntheApplication: IfyourAngulardevelopmentserverisnotrunning,startitwiththefollowing
command:
ngserve
Openyourwebbrowserandnavigatetohttp://localhost:4200.Youshouldseetheparagraphrepeatedthr
ee
appRepeat
timesasspecifiedbythe directive.
Department of CSE(DS),PEC