Practical 1:- Create a user-friendly interface with a clean and proper design.
Practical 1 a) Creating Simple AngularJS Application.
Step - 1: Load framework - Being a pure JavaScript framework, it can be added using
<Script> tag.
<script src
—"https://aj ax.googleapis.com/aj ax/libs/angularjs/l. 3.14/angular.min.js " >
</script>
Or [ If you install AngularJS]
<script src="node_modules/angular/angular.js"> </script>
Step - 2: Define AngularJS application using ngapp directive
<div ng-app =
Step - 3: Define a model name using ng-model directive
<p>Enter your Name: <input type = "text" ng-model =
Step - 4: Bind the value of above model defined using ng-bind directive
<span ng-bind =
Complete AngularJS Example:
<html>
<title>AngularJS First Application</title>
<script src —
"https://ajax.googleapis.com/ajax/libs/angularjs/l.3.14/angular.min.js" >
</head>
<hl >AngularJS First Application </hl >
<div ng-app =
<p>Enter your Name: <input type = "text" ng-model —
<span ng-bind = "name"></span>
Output:
AngularJS First Applica on All Bookmarks
C 0 127.0.0.1:8081/FirstApplica on.html
e Examina on Manag... ARC Login North Maharashtra...
AngularJS First Application
Enter your Name: Harshal
Hello Harshal !
Practical 2:- Develop AngularJS program to create a login form, with
validation for the username and password fields.
< !DOCTYPE html>
<html ng-app="loginApp">
<title>Login Form</title>
<script src= "https ://ajax.googleapis.com/aj ax/libs/angularj s/ 1.8.2/angular.min.js
">
.error {
color: red;
</style>
<body ng-controller="LoginController">
<form name="loginForm" ng-submit="submitForm()" novalidate>
<label for="username" >Username:
<input type="text" id="username" name="username"
ngmodel="user.username" required>
<span class="error" ng-show="loginForm.username.$touched &&
loginForm.username.$invalid">
Username is required. </span>
<label for="password">Password: </label>
<input type="password" id="password" name="password"
ngmodel="user.password" required>
<span class="error" ng-show="loginForm.password.$touched &&
loginForm.password.$invalid">
Password is required. </span>
<button
</form>
angular.module('loginApp', [l)
.controller('LoginController', ['$scope', function($scope) { $scope.user
={};
$scope.submitForm = function() { if
($scope.loginForm.$valid) { alert('Form
is valid and submitted!'); // Add your
login logic here
} else { alert('Form is invalid. Please correct the
errors.');
</script>
Output:
e Login Form Swayam Prabha | 32...
x
o 127.0.O.1:8081/Pract-2.html
Examina on Manag... ARC Login North Maharashtra...
All
Bookmarks
Username: Username is required.
Password: Password is required.
Login
e
Login Form
x
e Examina on All Bookmarks
Username:
Password:
Login
e
Login Form
x
e Examina on All
Bookmarks
Username:
Password:
Login
3:- services and data bind.
Practical — 3 a) To demonstrate AngularJS One Way Data Binding.
< !DOCTYPE html>
<html>
<title>One-Way Data Binding Example</title>
<script src=
"https://ajax.googleapis.com/aj ax/libs/angularj s/
</head>
<body >
>One-Way Data Binding Example</hl >
<div ng-controller="myCtrl">
<script type="text/javascript"> var app =
angular.module("myApp", [l);
app.controller("myCtrl", function ($scope) {
$scope.titlel = "AngularJS";
$scope.title2 = "AngularJs One-Way Data Binding";
$scope.description = "Data Binding refers
+ "to the synchronization of data
+ "between the model and view";
</script>
</html>
Output:
One-Way Data Binding Example X + All
Bookmarks
Examina on Manag...
One-Way Data Binding Example
AngularJS
AngularJs One-Way Data Binding
Data Binding refers to the synchronization of data between the model and view
Practical 4:- To display tasks in a list with checkboxes for marking
completion as per user choice.
//Pract-4.html
< !DOCTYPE html>
<html lang="en">
<meta ">
<meta name="viewport" content="width=device-width,
<title>Task List</title>
Klink rel="stylesheet" href="styles.css">
</head>
<div class="container">
>Task >
<ul id="task-list">
<!-- Tasks will be dynamically inserted here -->
<input type="text" id="task-input" placeholder="Add a new task"'
<button onclick="addTask()">Add Task</button>
<script " > </script>
//Style.css
body { font-family: Arial, sans-
serif; background-color:
#f4f4f4; display: flex; justify-
content: center; align-items:
center; height: 100vh; margin:
0;
.container { background: white; padding:
20px; border-radius: 8px; box-shadow: 0
0 10px rgba(0, 0, 0, 0.1);
margin-top: 0;
ul { list-style-type:
none; padding: 0;
display: flex; align-
items: center;
padding: 10px 0;
input[type="text"] {
padding: 10px;
width: 80%;
margin-right: 10px;
button { padding: 10px 20px;
background-color: #28a745;
color: white; border: none;
border-radius: 4px; cursor:
pointer;
button:hover { background-color:
#218838;
input[type="checkbox"] { margin-right:
10px;
//Script.css
document.addEventListener('DOMContentLoaded', () { const
taskList = document.getElementById('task-list'); const
tasklnput = document.getElementById('task-input');
function addTask() { const taskText =
tasklnput.value.trim(); if (taskText = = ")
return;
// Create a new list item const li =
document.createElement('li');
// Create checkbox const checkbox =
document.createElement('input'); checkbox.type =
'checkbox';
// Create span for task text const span =
document.createElement('span');
span.textContent = taskText;
// Create span for completion status const statusSpan
= document.createElement('span');
statusSpan.textContent = ' (Completion: false)';
statusSpan.style.marginLeft — '10px';
// Handle checkbox change
checkbox.addEventListener('change', () { if
(checkbox.checked) { span.style.textDecoration =
'line-through'; statusSpan.textContent = '
(Completion: true)';
} else { span.style.textDecoration = 'none';
statusSpan.textContent = ' (Completion: false)';
// Append elements to list item
li.appendChild(checkbox);
li.appendChild(span);
li.appendChild(statusSpan);
// Append list item to task list taskList.appendChild(li);
// Clear input field tasklnput.value
=
// Make addTask function globally accessible window.addTask
— addTask•,
Output:
Task List
CD 127.0.0.1
Examina on Manao... ARC Login Maharashtra... Swayam Prabha 1 32... All Bookmarks
Task List
Add now task
Add Task
Task List All Bookmarks
O 127.0.0.1:8081/Pract-3.html
Examina on Manag ARC Login
Task List
BCA 506 Cloud Prac cal
Add Task
Task List
O 127.0.O.1:8081/Pract-3.html
Examina on Manag... ARC Login All Bookmarks
Task List
o BCA 506 Cloud Prac cal (Comple on: false)
BCA 507 (A) - Web Development Technologies - I l l (Comple on:
Prac cal false)
BCA 504 (C) - Machine Learning Prac cal
Add Task
e Task List x
0 127.0.O.1:8081/Pract-3.html
e Examina on Manag... ARC Login All Bookmarks
Task List
o BCA 506 Cloud Prac cal (Comple on: false)
(Comple on:
true)
(Comple on: true)
Add a new task
Add Task
Practical 5 a):- To use ng-controller
< !DOCTYPE html>
<head> ng-controller Directive
< script src="https ://ajax.googleapis.com/aj ax/libs/angularj s/
1.4.2/angular.min.js"
</script>
<body ng-app="app" style="text-align:center">
style="color:green"> ng-controller Directive
Example
<div > Name:
<input class="form-control" type="text"
ng-model="name">
You entered:
{name} </b>
<script> var app = angular.module('app', [l);
app.controller('hvp', function ($scope) {
$scope.name = "Purva Harshal Patil";
</script>
</html>
Output:
e ng-contollerDire,- e
C 0 127.00.1808110iredive_lhtml
Å WELCOMETOISRO- JavaScript comment-
ng-controller Directive Example
You entered: Taniva Harshal Patil
Prac cal 6:- To create database and structure in MongoDB using
Mongo Compass GUI.
Step 1 Go to the MongoDB Download Center to download the MongoDB
Compass:
MOroot* This davzbk•s thoconnectk:nto
MongoC*
Mongo08Community
(Stable)
Mong00ØShe'
Windows 64-bit (104)
Atlas
Atlas Kit—notes
Step — 2 A er installa on of MongoDB Compass Open It.
0
Welcome to MongoDB Compass
0'
Step — 3 A er Open MongoDB Compass Go to -Y Add New Connec on -Y Enter
Connec on Name like MyConnec on -Y click Connect
Step — 4 A er Click Connect.
Step — 5 A er that Click Create Database and Enter Database Name and Collec on
Name if you want then Click Create Database Bu on.
Compass Comectkms
Ed"
This collec on has no data
it only takes a few soconds to import dota from a JSON CSV
Prac cal 7:- To create collec on and insert records in collec ons.
Run MongoDB
Step-I To run MongoDb open command prompt and go to C:\Program
Step-2 A er that go to mongosh shell
mongosh mongodb://127.0.0.1 :27017/?directConnec on=true&serverSelec onTimm
C: \Program Files \tv10ngoDB
Current Mongosh Log ID: 66daba079Ø64b9db3c2710bb
Connec ng to: mongodb : / /127.0.0.1 : 27017/ ?directConnec on=true&serverSe1e
: onT imeoutMS=2ØØØ&appName=mongosh+2.3. O
Using FbngoDB: 7.0.14 Using tvbngosh: 2.3.ø mongosh 2.3. I is available for download:
h ps://vwm.mongodb.com/try/download/shell
For mongosh info see: h ps://wm.mongodb.com/docs/mongodb-shell/
The server generated these startup warnings when boo ng
30: Access control is not enabled for the database. R ead
and write access to data and configura on is unrestricted
test>
Step-3 Now you can create a new database, collec ons, and documents in your mongosh
shell.
• The use <<Database name>> command to create a new database in the
system if it does not exist, if the database exists it uses that database:
use studDB
Now your database is ready of name studDB.
• To display all database use show dbs command
• Collections are created automatically when you insert the first document.
Alternatively, you can create a collection explicitly using the createCollection()
method.
• Display all collection in Database used show collections command or
db.getCollectionNames() method.
• To delete collection use : Use the drop() method on the collection
mongosh mongodb://127.0.0.1 :2701
studDB> db. getC011ec onNames()
' student' ] studDB> db.
student. drop() true studDB> db.
getC011ec onNames()
studDB>
• The insertOne() method inserts the document in the student collection:
db.student.insertOne({name: "Purva", age: 08 })
• Insert Multiple Records: Use the insertMany() method to insert multiple
documents at once. Here's an example:
db.student.insertMany([ {
name: "Harshal", age: 38 } ,
{ name: "Bhakti", age: 08 },
{ name: "Sujata", age: 35 }
l)
This will insert three documents into the student collection.
Practical 8:- To demonstrate insert, update, delete, select operations in
MongoDB.
How to insert, update, display and remove documents in MongoDB:
Inserting a Document: To insert a document into a collection, use the insertOne() or
insertMany() methods.
Example - 1 db. student.insertOne({
name: "Purva Harshal Patil",
age: 08, city: "Talvel"
D;
Example - 2 db.
student.insertMany([
{ name: "Bhkati Harshal Patil", age: 06, city: "Talvel" } , {
name: "Malhar Yogesh Patil", age: 08, city: "Bhusawal" } ,
{ name: "Sujata Suresh Mahajan", age: 38, city: "Bhusawal"
Retrieving Documents: Show the Records: Use the find method to retrieve and
display records from the student collection:
db.student.find().pretty() find()
retrieves all documents from the student collection. pretty()
formats the output to be more readable
If you want to find a specific record, you can pass a query to the find method. For
example, to find the record where name equals Purva Harshal Patil, you can use:
db.student.find({ name: "Purva Harshal Patil" }).pretty()
Updating Documents: Use the updateOne() or updateMany() methods to update
documents.
Example — 1
Use updateOne with a query filter and update operations:
db.student.updateOne(
{ name: "Purva Harshal Patil" l, // Query filter to find the document
{ $set: { age: 25 } } // Update operation
This will update the first document where the name field is 'Purva
Harshal Patil", setting the age field to 25.
Example — 2
Use updateMany with a query filter and update operations:
db. student.updateMany(
{ city: "Talvel" }, { $set: { state: "MH" } }
Deleting Documents: To delete documents, use the deleteOne() or
deleteMany() methods.
Delete a Single Document
If you want to delete a specific document, use deleteOne with a query filter:
db.student.deleteOne({ name: "Purva Harshal Patil" })
This will delete the first document that matches the filter.
name: "Purva Harshal Pa l" } )
deletedCount: 1 } name: "Purva Harshal Pa l" .
pre y()
studDB> db. student .
acknowledged: true,
studDB> db. student .
studDB>
Delete Multiple Documents
If you want to delete multiple documents that match a certain condition, use
deleteMany:
db.student.deleteMany({ age: { $1t: 18 } })
This example deletes all documents where the age field is less than 18.
Example — 1 Use Comparison $eq - Equal Query Operators:
db.student.find({ age: { $eq: 35 } } )
Example — 2 Use Comparison $ne - Not Equal Query Operators:
db.student.find({ age: { $ne: 35 } } )
Example — 3 Use Comparison $gt - Greater Than Query Operators:
db.student.find({ age: { $gt: 35 } } )
Example — 4 Use Comparison $gte - Greater Than or Equal Query Operators:
db.student.find({ age: { $gte: 35 } } )
Example — 5 Use Comparison $1t - Less Than Query Operators:
db.student.find({ age: { $1t: 35 ) } )
Example — 6 Use Comparison $1te - Less Than or Equal Query Operators:
db.student.find({ age: { $1te: 8 } } )
Example — 7 Use Comparison $in — In Query Operators:
db.student.find({ age: { $in: [8, 25, 35] } } )
Example — 8 Use Comparison $nin - Not In Query Operators:
db.student.find({ age: { $nin: [8, 25, 35] } } )
Example — 1 Use
db.student.find({
$and - Logical AND Query Operators:
$and: [
{ age: { $gt: 6 }
{ age: { $1t: 35 } }
} ) .pretty()
studDB> db. student.
Sand: [
{ age: { $gt: 6 }
{ age: { $1t: 35 } }
} ) . pre y()
_id: Objectld( '
66dad8879Ø64b9db3c2710c1 ' ) , name:
'Purva Harshal Pa l', age: 8, city: 'Talvel' ,
grades: [ 75, 88, 92 ]
_id: Objectld( '66dad8c69064b9db3c271Øc3'),
name : 'Malhar Yogesh Pa l' , age: 8, city: •
Bhusawal• , grades: [ 95, 100, 92 ]
tudDB>
s
Example — 2 Use $or - Logical OR Query Operators:
db.student.find({
$or: [
{ age: { $gt: 35 } } ,
{ age: { $1t: 38 } }
}).pretty()
city:
grades: [ ]
Example — 1 Use Query Operators:
db.student.find({
3 $not - Logical NOT Query Operators:
age: { $not: { $gt: 8 } } }).pretty()
Example — 4 Use $nor - Logical NOR Query Operators:
db.student.find({
$nor: [
{ age: { $1te: 38 }
{ age: { $gte: 6 } }
)).pretty()
city:
grades: [ ]
Example — Use db.student.find({
This will return no documents because all age values will satisfy either age 38 or
age 6.
$exists age: { $exists: true }
}).pre y()
Example — 2 Use $exists Query Operators: db.student.find({
state: { $exists: true } }).pre y()
Example — 3 Use $exists Query Operators:
db.student.find({ state: { $exists: false } }).pre y()
Example — 1 Use Query Operators:
db.student.find({
city:
grades: [ ]
Example — Use Query Operators:
db.student.find({
4 $type age: { $type: "int" } }).pretty()
Example — 5 Find students who have an age field but do not have a state field.:
db.student.find({ age: { $exists: true }, state: { $exists: false } }).pretty()
Example — 1 Use Query Operators:
$expr
Find students whose age are greater than or equal to 35.
db.student.find({ $expr: { $gte: ["$age", 35] } }).pre y()
city:
grades: [ ]
Example — Use
Example — 2 Use $regex Query Operators:
Find students whose names start with the le er "H".
db.student.find({ name: { $regex: /AH/ } }).pre y()
Example — 3 Use $mod (Module Opera on) Query Operators:
Find students whose age is an even number.
db.student.find({ age: { $mod: [2, 0] } }).pre y()
4 $text (Perform Text Search) Query Operators:
Create a text index on the name field and find students whose names contain the word
"Purva".
db.student.createlndex({ name: "text" } ) db.student.find({
$text: { $search: "Purva" } } )
Example — 1 Use Query Operators:
Example — 5 Use $where Query Operators:
Find students whose age is greater than 25.
db.student.find({ $where: function() { return this.age > 25} }).pretty()
city:
grades: [ ]
Example — 1 Use
$all Query Operators:
Find students who have grades of 85 and 90.
db.student.find({ grades: { $all: [85, 90] } }).pretty()
Example — 2 Use $elemMatch Query Operators:
Find students who have a grade greater than 80 and less than 90.
db.student.find({ grades: { $elemMatch: { $gt: 80, $1t: 90 } } }).pretty()
Example — 3 Use $size Query Operators:
Find students who have exactly 3 grades.
db.student.find({ grades: { $size: 3 } )).pretty()
mongosh
Example — 4 Use $slice Query Operators:
Find students and return only the first 2 grades from the grades array.
db.student.find({}, { name: 1, grades: { $slice: 2 } )).pretty()
Example — 5 Use $in Query Operators:
Find students who have any of the grades 75, 85, or 95.
db.student.find({ grades: { $in: [75, 85, 95] } }).pretty()
Example — 6 Use Array Query Operators:
Find students who have exactly 3 grades, and at least one grade is greater than 90.
db.student.find({ grades: { $size: 3, $elemMatch: { $gt: 90 ) } } )
Example — 1 Use $ bitsAllClear Query Operators:
db.student.find({ flags: { $bitsAllClear: 2 } }).pre y()
mongosh
This query matches students whose flags field has the second bit clear (0).
Example — 2 Use $ bitsAllSet Query Operators:
db.student.find({ flags: { $bitsAllSet: 1 } )).pre y()
This query matches students whose flags field has the first bit set (1).
Example — 3 Use $ bitsAnyClear Query Operators:
db.student.find({ flags: { $bitsAnyClear: 8 } }).pre y()
This query matches students whose flags field has at least one bit clear (0) in the
fourth bit position.
Example — 4 Use $ bitsAnySet Query Operators:
db.student.find({ flags: { $bitsAnySet: 4 ) }).pretty()
This query matches students whose flags field has at least one bit set (1) in the third bit
position.
Example — 5 Use Bitwise Query Operators:
db.student.find({ flags: { $bitsAllSet: 1, $bitsAnySet: 4 ) }).pretty()
mongosh
This query matches students whose flags field has the first bit set (1) and at least one bit set
(1) in the third bit posi on.
Example — 1 Use $comment Query Operators:
Find students who have a grade greater than 90 and include a comment..
db.student.find( { grades: { $elemMatch: { $gt: 90 } }, $comment: "Find students with
grades greater than 90" } ) .pre y()
mongosh
Example 1: Ascending Order or ng db.student.find().sort({
age: 1 }). pre y() Example 2: Descending Order Sor ng
db.student.find().sort({age:-l }). pre y()
Example 3: Ascending Order by Student Name
db.student.find().sort({name: 1 }). pre y()
mongosh
Example 4: Ascending Order by Student Name and age
db.student.find().sort({name: l, age: I l). pretty()
mongosh
Practical 9:- Develop a task manager application using AngularJS for the
frontend and MongoDB for the backend.
Step 1: Set Up the Backend (Node.js + Express.js + MongoDB)
1. Install Node.js and MongoDB:
• Download and install Node.js from [nodejs.org](https://nodejs.org/).
• Install MongoDB by following the instructions on the [MongoDB installation page]
(https://www.mongodb.com/docs/manual/installation/).
2. Initialize a Node.js Project:
mkdir mean-simple-app
cd mean-simple-app
npm init -y
3. Install Required Dependencies:
npm install express mongoose body-parser cors
4. Create the Server:
• Create a file named and set up a basic Express server:
const express = require('express'); const
mongoose = require('mongoose'); const
bodyParser = require('body-parser'); const
cors = require('cors'); const path =
require('path'); const app = express(); const
port = 3000;
// Middleware
app.use(bodyParser.json());
app.use(cors());
// Serve static files from the 'public' directory
app.use(express.static(path.join(_dirname, 'public')));
// MongoDB connection mongoose. connect('mongodb://localhost:27017/mean_db', {
useNewUrlParser: true, useUnifiedTopology: true } )
.then(() console.log('MongoDB connected'))
.catch(err console.error(err));
// Define a simple schema and model const
ItemSchema = new mongoose.Schema({ name:
String D; const Item = mongoose.model('ltem',
ItemSchema);
// Routes app.get('/items', async (req,
res) { try { const items = await
Item.find(); res.json(items);
} catch (err) { res.status(500).send(err);
// Serve the index.html for any other routes not handled
app.get('*' (req, res) { res.sendFile(path.join(_dirname,
'public', 'index.html'));
// Start server app.listen(port, () { console.logCServer
running on http://localhost:$ {port} N );
D;
Step 2: Set Up the Frontend (AngularJS) mean-simple-
app/
1-— node_modules/
I—- public/
I index.html
I app.j s
I services.js
I controllers.js
views/
I home.html server.js
package.json
1—— package-lock.json
1. Create an AngularJS Project:
• Create a basic HTML file Cindex.htmP) for your AngularJS application:
< !DOCTYPE html>
<html ng-app= " simpleApp " >
<title>Simple AngularJS App</title>
< script src="https://aj ax.googleapis.com/aj ax/libs/angularj s/
1.8.2/angular.min.js " >
< script
src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angularroute.min.js" >
<script src="app.js" >
"
<script
< script > </script>
</head>
<div ng-view> </div>
</html>
2. Set Up AngularJS Application:
Create app.jsx for defining the AngularJS module and routes:
angular.module('simpleApp', ['ngRoute'])
.config(function($routeProvider) {
$routeProvider
.when('/', { templateUrl:
'views/home.html', controller:
'MainController'
.otherwise({
redirectTo: '/'
3. Create AngularJS Services:
• Create services.je to handle HTTP requests to the backend:
angular.module('simpleApp')
.service('ItemService', function($http) {
this.getltems = function() { return
$http.get('http://localhost:3000/items');
4. Create Controllers:
• Create to handle the interaction between the view and the backend:
angular.module('simpleApp')
.controller('MainController', function($scope, ItemService) {
$scope.items = [l;
$scope.getltems = function() {
ItemService.getItems().then(function(response) { console.log('ltems
fetched:', response.data);
$scope.items = response.data;
}).catch(function(error) { console.error('Error
fetching items:', error);
// Initial load
$scope.getltems();
l);
5. Create Views:
Create a folder named viewe and add home.htmP for the main view:
>Creating AngularJS services to interact with MongoDB</hl >
<li ng-repeat="item in { item.name } }
Step 3: Run and Test the Application
1. Start MongoDB:
X
• Ensure MongoDB is running. You can start MongoDB by running mongodN in your
terminal.
2. Start the Backend Server:
• In the root directory of your project, run the following command:
node server.js
3. Open the Frontend in a Browser:
Open h p://localhost:3000P in your browser. You should see your AngularJS
applica on running, displaying the list of items fetched from MongoDB.
Simple AngularJS App x
C @ localhost:3000/#!/
e Examina on Manag... ARC Login North Maharashtra... Swayam Prabha | 32... All Bookmarks
Crea ng AngularJS services to interact with MongoDB
• Pen Drive
• Keyboard
• CPU
• Mouse
• SSD
• DVD
• Item 2
Practical 10:- To Create Student interface to stored and update the
information.
Step 1: Set Up the Backend (Node.js + Express.js + MongoDB)
1. Install Node.js and MongoDB:
• Download and install Node.js from [nodejs.org](https://nodejs.org/).
• Install MongoDB by following the instructions on the [MongoDB installation page]
(https://www.mongodb.com/docs/manual/installation/).
Step 2: Set up a new Node.js project:
• Create a new directory for your project and navigate into it:
mkdir Interation-angularjs-mongodb cd
Interation-angularjs-mongodb Initialize a new Node.js
project: npm init —y
• Install Required Dependencies:
npm install express mongoose body-parser cors
Step 3: Create the Express server:
• Create a file named server.js in the project root: :
const express = require('express'); const
mongoose = require('mongoose'); const
bodyParser = require('body-parser'); const
cors = require('cors'); const app = express();
// Middleware
app.use(bodyParser.json());
app.use(cors());
// MongoDB connection mongoose.
.then(() console.log('MongoDB connected'))
.catch(err console.log(err));
// Define a simple schema and model const
ItemSchema = new mongoose.Schema({ name:
String, quantity: Number
const Item = mongoose.model('ltem', ItemSchema);
// Define API endpoints
app.get('/api/items', async (req, res) { try
{ const items = await Item.find();
res.json(items); } catch (err) {
res.status(500).send(err);
app.post('/api/items', async (req, res) { try {
const newltem = new Item(req.body); const
savedltem = await newltem.save();
res.json(savedltem); } catch (err) {
res.status(500).send(err);
// Serve static files from the 'public' directory app.use(express.static('public'));
// Fallback to index.html for single-page applications
// Ensure the path is correct and the file exists (req, res)
{ console.log('Serving index.html');
res.sendFile(_dirname + '/public/index.html', function(err) { if
(err) { res.status(500).send(err);
D;
const port = process.env.PORT Il 3000; app.listen(port, ()
console.logCServer running on port ${port}));
Step 4: Run the server
node server.js
Step 5: Set Up the Frontend (AngularJS)
1. Create an AngularJS Project:
If you haven't already, create an AngularJS project structure inside your
Interation-angularjs-mongodb directory:
mkdir public cd public npm init -y
npm install angular
Create the necessary files and folders:
public
app
index.html
app.module.js
app.config.js
app.controller.js Fff
2. Set Up AngularJS Application:
• Create the index.html file:
<html >
<title>AngularJS and MongoDB Integration</title> < script
s " > </script>
< script src=" app/app.module.js " > </script>
< script src=" app/app.config.js " >
<script src=" app/app.controller.js " >
<div ng-controller="MainController as ctrl ">
<form ng-submit="ctrl.addltem()">
<input type="text" ng-model="ctrl.newltem.name" placeholder="ltem
Name" required>
<input type="number" ng-model="ctrl.newltem.quantity"
placeholder="Quantity" required'
<button type="submit">Add Item</button>
</form>
<li ng-repeat="item in ctrl.items">{{ item.name } } { { item.quantity
</body>
</html>
3. Create the AngularJS application files:
app/app.module.js:
angular.module('myApp', [l);
app/app.config.js:
angular.module('myApp').config(function($httpProvider) {
// Configuration if needed
app/app.controller.js:
angular.module('myApp').controller('MainController', function($http) {
var vm = this; vm.items = [l; vm.newltem = { } ;
// Fetch items from the server vm.getltems
= function() {
$http.get('/api/items').then(function(response) { vm.items
= response.data;
}).catch(function(error) { console.error('Error
fetching items:', error);
D;
// Add a new item vm.addltem
= function() {
$http.post('/api/items', vm.newltem).then(function(response) {
vm.items.push(response.data); vm.newltem = { }; // Clear the
form
}).catch(function(error) { console.error('Error
adding item:', error); D;
// Initial fetch vm.getltems();
Step 6: Run and Test the Application
1. Start MongoDB:
• Ensure MongoDB is running. You can start MongoDB by running mongodX in your
terminal.
2. Start the Backend Server:
• In the root directory of your project, run the following command:
node server.js
3. Open the Frontend in a Browser:
• Open your browser and navigate to http://localhost:3000. You should see the AngularJS
application, and you can add and view items that are stored in the
MongoDB database.
x
WhatsApp X e AngularJS anci
localhost:3000/?
e Examina on Manag... ARC Login
C) All Bookmarks
• PenDrive- 10
• Keyboard - 12
• CPU- IO
WhatsApp X e AngularJS and
localhost:3000/? x
ARC Login
Examina on Manag...
All Bookmarks
Item Name
• PenDrive- 10
• Keyboard- 12
• CPU- IO
• Mouse - 20
Practical 12:- Implement a user interface where users can view, add, update,
and delete tasks with MongoDB Database.
Step 1: Set Up the Backend (Node.js + Express.js + MongoDB)
1. Install Node.js and MongoDB:
• Download and install Node.js from [nodejs.org](https://nodejs.org/).
• Install MongoDB by following the instructions on the [MongoDB installation page]
(https://www.mongodb.com/docs/manual/installation/).
2. Initialize a Node.js Project:
mkdir mean-stack-app
cd mean-stack-app
npm init -y
3. Install Required Dependencies:
npm install express mongoose body-parser cors
4. Create the Server:
• Create a file named and set up a basic Express server:
const express = require('express'); const
mongoose = require('mongoose'); const
bodyParser = require('body-parser'); const
cors = require('cors'); const path =
require('path'); const app = express();
const port = 3000;
// Middleware
app.use(bodyParser.json());
app.use(cors());
// Serve static files from the 'public' directory
app.use(express.static(path.join(_dirname, 'public')));
// MongoDB connection mongoose. connect('mongodb://localhost:27017/mean_db', {
useNewUrlParser: true, useUnifiedTopology: true } )
.then(() console.log('MongoDB connected'))
.catch(err console.error(err));
// Define a simple schema and model const
ItemSchema = new mongoose.Schema({ name:
String,
quantity: Number
D; const Item = mongoose.model('ltem',
ItemSchema);
// Routes app.get('/items', async (req,
res) { try { const items = await
Item.find(); res.json(items);
} catch (err) { res.status(500).send(err);
app.post('/items', async (req, res) { try {
const newltem = new Item(req.body); const
savedltem = await newltem.save();
res.json(savedltem);
} catch (err) { res.status(500).send(err);
app.put('/items/:id', async (req, res) { try { const updatedltem = await
Item.findByIdAndUpdate(req.params.id, req.body, { new: true l); res.j son(updatedltem) ;
} catch (err) { res.status(500).send(err);
app.delete('/items/:id', async (req, res) { try { await
Item.findByIdAndDelete(req.params.id);
res.json({ message: 'Item deleted' l);
} catch (err) {
res.status(500).send(err);
// Serve the index.html for any other routes not handled app.
* (req, res) { res.sendFile(path.join(_dirname, 'public',
'index.html'));
// Start server app.listen(port, () { console.logCServer
running on http://localhost:$ {port});
D;
Step 2: Set Up the Frontend (AngularJS) mean-stack-app/
node modules/
_
I—- public/
I index.html
I app.j s
1 services.js
I controllers.js
views/
I L'¯— home.html
server.js
package.json
I—- package-lock.json
1. Create an AngularJS Project:
Create a basic HTML file Cindex.htmlN ) for your AngularJS application:
< !DOCTYPE html>
<html ng-app="meanApp">
<title>MEAN Stack App</title>
< script src="https://ajax.googleapis.com/ajax/libs/angularj s/
<script
src="https://ajax.googleapis.com/ajax/libs/angularjs/l.8.2/angularroute.min.js"></script>
<script src=" app.js" >
<script "
< script > </script>
<div ng-view> </div>
</html>
2. Set Up AngularJS Application:
Create for defining the AngularJS module and routes:
angular.module('meanApp', ['ngRoute']) .config(function($routeProvider)
{
$routeProvider
.when('/', { templateUrl:
'views/home.html', controller:
'MainController'
.otherwise({
redirectTo: '/'
3. Create AngularJS Services:
Create to handle HTTP requests to the backend:
angular.module('meanApp')
.service('ItemService', function($http) {
this.getltems = function() { return
$http.get('http://localhost:3000/items');
this.addltem = function(item) { return
$http.post('http://localhost:3000/items', item);
this.updateltem = function(id, item) { return
$http.put('http://localhost:3000/items/' + id, item);
this.deleteltem = function(id) { return
$http.delete('http://localhost:3000/items/' + id);
4. Create Controllers:
Create controllers.je to handle the interaction between the view and the backend:
angular.module('meanApp')
.controller('MainController', function($scope, ItemService) {
$scope.items = [l;
$scope.newltem = {
$scope.editingltem = null;
$scope.getltems = function() {
ItemService.getItems().then(function(response) { $scope.items
= response.data;
$scope.addltem = function() {
ItemService.addItem($scope.newItem).then(function(response) {
$scope.items.push(response.data); $scope.newltem
={
$scope.updateltem = function(item) {
ItemService.updateItem(item._id, item).then(function(response) {
$scope.editingltem = null; $scope.getltems();
$scope.deleteltem = function(id) {
ItemService.deleteItem(id).then(function(response) {
$scope.getltems();
D;
$scope.startEditing = function(item) {
$scope.editingltem = angular.copy(item);
$scope.cancelEditing = function() {
$scope.editingltem = null;
// Initial load
$scope.getltems();
5. Create Views:
Create a folder named x viewsx and add home.htmlX for the main view:
Stack App</hl
<form ng-submit= " addltem() " >
<input type="text" ng-model="newltem.name" placeholder="ltem Name" required>
<input type="number" ng-model="newltem.quantity" placeholder="Quantity"
required>
<button type="submit">Add Item</button>
</form>
<li ng-repeat="item in
<span ng-if="editingltem && editingltem._id item.
<input type="text" ng-model="editingltem.name" required> <input
type="number" ng-model="editingltem.quantity" required> <button
ng-click="updateItem(editingItem)">Save</button>
<button
</span>
<span ng-if=" !editingltem I l editingltem._id . item.
{ { item.name } } - { { item.quantity } }
<button ng-click=" startEditing(item) "
<button ng-click= " deleteltem(item._id) " > Delete
Step 3: Run and Test the Application
1. Start MongoDB:
Ensure MongoDB is running. You can start MongoDB by running mongo& in your
terminal.
2. Start the Backend Server:
In the root directory of your project, run the following command:
node server.js
3. Open the Frontend in a Browser:
Open h p://localhost:3000P in your browser. You should see the MEAN stack
applica on running, where you can add items and view the list of items stored in MongoDB.
MEAN Stack App Add Item
x
localhost:3000/#!/
All Bookmarks
e Examina on Manag... ARC Login
MEAN Stack App
• Pen - 4 Edit Delete
Drive - 12 Edit Delete
Edit Delete
20 Edit Delete
Edit Delete
Keyboard
CPU - 10 • Mouse -
• SSD - 10
e MEAN Stack App C] All
localhost:3000/#!/ Bookmarks
e Examina on Manag... ARC Login
MEAN Stack App
• Pen - 4 Edit Delete Drive
- 12 Edit Delete • Keyboard
CPU- Edit Delete
20 Edit Delete
10
Edit Delete
• Mouse -
SSD - 10
x
e MEAN stack App
localhost:3000/#!/
e Examina on Manag... ARC Login
All Bookmarks
MEAN Stack App
Pen Drive - 4 Edit Delete
Keyboard - 12 Edit Delete
CPU- 10 Edit Delete
Mouse - Edit Delete
20 Edit Delete
SSD - 10
Motherboard
Item Name Add Item
•
•
•
•
•
x
e MEAN stack App
localhost:3000/#!/
e Examina on Manag... ARC Login
All Bookmarks
MEAN Stack App
- 4 Edit Delete
- 12 Edit Delete
Edit Delete
20 Edit Delete
Edit Delete
-5 Edit Delete
Item Name Add Item
• Pen Drive
• Keyboard
CPU- IO
• Mouse -
SSD - 10
• Motherboard