0% found this document useful (0 votes)
12 views11 pages

MERN Progress

The document is a laboratory manual for a MERN course (MongoDB, Express.js, React.js, Node.js) that includes course objectives, practical experiments, and code samples. It covers various topics such as working with MongoDB collections, querying data, Node.js integration, file system operations, Ajax data submission, authentication, routing, and building React components. Each experiment provides objectives, tasks, instructions, and sample code to facilitate hands-on learning.

Uploaded by

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

MERN Progress

The document is a laboratory manual for a MERN course (MongoDB, Express.js, React.js, Node.js) that includes course objectives, practical experiments, and code samples. It covers various topics such as working with MongoDB collections, querying data, Node.js integration, file system operations, Ajax data submission, authentication, routing, and building React components. Each experiment provides objectives, tasks, instructions, and sample code to facilitate hands-on learning.

Uploaded by

locomode01
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 11

MERN (MongoDB, Express.js, React.

js,
Node.js) Laboratory Manual
Course Information
Course Code: BDSL456C
Teaching Hours/Week (L:T:P: S): 0:0:2:0
Credits: 01
CIEMarks: 50
SEEMarks: 50
ExamHours: 02
Examination Type (SEE): Practical

Course Objectives
1. Understand and apply critical web development languages and tools to create
dynamic and responsive web applications.
2. Build server-side applications using Node.js and Express.
3. Develop user interfaces with React.js.
4. Manage data using MongoDB and integrate these technologies to create full stack
applications.
5. Understand APIs and routing.

Experiments
Experiment 1: Working with MongoDB Collections

Objective:

● To create and manage collections in MongoDB.

Tasks:

1. Create a collection called transactions in the database usermanaged. Drop the


collection if it already exists.
2. Bulk load data from a JSON file transactions.json into the transactions
collection.
3. Upsert the records from a new file transactions_upsert.json into the
transactions collection.

Instructions:

1. Connect to the MongoDB server.


2. Drop the existing transactions collection if it exists.
3. Use the bulkWrite method to load data from transactions.json.
4. Perform an upsert operation using the data from transactions_upsert.json.

Code Sample:

// Assuming MongoDB Node.js Driver is installed


const { MongoClient } = require('mongodb');
const fs = require('fs');

async function run() {


const uri = "your_mongodb_connection_string";
const client = new MongoClient(uri);

try {
await client.connect();
const db = client.db('usermanaged');
const collection = db.collection('transactions');

// Drop the collection if it exists


await collection.drop();

// Read and insert the bulk data


const bulkData = JSON.parse(fs.readFileSync('transactions.json',
'utf8'));
await collection.insertMany(bulkData);

// Read and upsert the data


const upsertData =
JSON.parse(fs.readFileSync('transactions_upsert.json', 'utf8'));
for (let record of upsertData) {
await collection.updateOne({ _id: record._id }, { $set: record
}, { upsert: true });
}

console.log("Data loaded and upserted successfully.");


} finally {
await client.close();
}
}

run().catch(console.dir);

Experiment 2: Querying MongoDB

Objective:

● To perform various queries on MongoDB collections.

Tasks:

1. Create the necessary collections with documents to perform the following queries:
o Find any record where Name is Somu.
o Find any record where the total payment amount (Payment.Total) is 600.
o Find any record where price (Transaction.price) is between 300 to 500.
o Calculate the total transaction amount by adding up Payment.Total in all
records.

Instructions:

1. Use MongoDB's find and aggregation methods to perform the queries.


2. Create appropriate indexes if needed for faster querying.

Code Sample:

async function runQueries() {


const uri = "your_mongodb_connection_string";
const client = new MongoClient(uri);

try {
await client.connect();
const db = client.db('usermanaged');
const collection = db.collection('transactions');

// a. Find any record where Name is Somu


const recordSomu = await collection.findOne({ Name: 'Somu' });
console.log('Record with Name Somu:', recordSomu);

// b. Find any record where Payment.Total is 600


const payment600 = await collection.findOne({ 'Payment.Total': 600
});
console.log('Record with Payment.Total 600:', payment600);

// c. Find any record where Transaction.price is between 300 to 500


const priceRange = await collection.find({ 'Transaction.price': {
$gte: 300, $lte: 500 } }).toArray();
console.log('Records with Transaction.price between 300 and 500:',
priceRange);

// d. Calculate the total transaction amount by adding up


Payment.Total in all records
const totalTransactionAmount = await collection.aggregate([
{ $group: { _id: null, total: { $sum: '$Payment.Total' } } }
]).toArray();
console.log('Total transaction amount:',
totalTransactionAmount[0].total);
} finally {
await client.close();
}
}

runQueries().catch(console.dir);

Experiment 3: Working with Node.js and Objects

Objective:

● To interact with HTTP request headers and manage object properties in Node.js.
Tasks:

1. Write a program to check request header for cookies.


2. Write a Node.js program to:
o Print the properties of a car object.
o Delete the second property.
o Get the length of the object.

Instructions:

1. Use Node.js modules like http to create a server and access request headers.
2. Manage object properties using standard object manipulation techniques.

Code Sample:

const http = require('http');

// Part a: Check request header for cookies


http.createServer((req, res) => {
const cookies = req.headers.cookie;
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end(`Cookies: ${cookies}`);
}).listen(8080, () => console.log('Server running at
http://127.0.0.1:8080/'));

// Part b: Object manipulation


const car = {
make: 'Toyota',
model: 'Corolla',
year: 2018,
color: 'Blue'
};

console.log('Car properties:', car);

delete car.model;

console.log('Car properties after deletion:', car);

const objectLength = Object.keys(car).length;


console.log('Object length:', objectLength);

Experiment 4: Node.js and MongoDB Integration

Objective:

● To read and store student data using Node.js and MongoDB.

Tasks:

1. Read the data of a student containing usn, name, sem, and year of admission from
Node.js and store it in MongoDB.
2. For a partial name given in Node.js, search all the names from MongoDB student
documents created in Task (a).

Instructions:

1. Use MongoDB's insertOne and find methods to store and search data.

Code Sample:

async function manageStudentData() {


const uri = "your_mongodb_connection_string";
const client = new MongoClient(uri);

try {
await client.connect();
const db = client.db('school');
const collection = db.collection('students');

// Part a: Read and store student data


const student = {
usn: '1RV18CS001',
name: 'John Doe',
sem: 4,
year_of_admission: 2018
};
await collection.insertOne(student);
console.log('Student data inserted:', student);

// Part b: Search for partial name


const partialName = 'John';
const searchResults = await collection.find({ name: { $regex:
partialName, $options: 'i' } }).toArray();
console.log('Search results for partial name:', searchResults);
} finally {
await client.close();
}
}

manageStudentData().catch(console.dir);

Experiment 5: File System CRUD Operations with Node.js

Objective:

● To implement CRUD operations on a file system using Node.js.

Tasks:

1. Create a file, read its content, update the content, and delete the file.

Instructions:

1. Use Node.js fs module to perform file system operations.


Code Sample:

const fs = require('fs');

// Create a file
fs.writeFile('example.txt', 'Hello, world!', (err) => {
if (err) throw err;
console.log('File created.');

// Read the file


fs.readFile('example.txt', 'utf8', (err, data) => {
if (err) throw err;
console.log('File content:', data);

// Update the file


fs.appendFile('example.txt', ' This is an update.', (err) => {
if (err) throw err;
console.log('File updated.');

// Delete the file


fs.unlink('example.txt', (err) => {
if (err) throw err;
console.log('File deleted.');
});
});
});
});

Experiment 6: Sending Data from Client to Server using Ajax

Objective:

● To develop an application that sends fruit name and price data from client-side to
Node.js server using Ajax.

Tasks:

1. Create a simple HTML form to input fruit name and price.


2. Use Ajax to send the data to the server.
3. Node.js server should receive and log the data.

Instructions:

1. Use HTML, jQuery (or vanilla ), and Node.js http or express module.

Code Sample:

html

<!-- HTML Form -->


<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Fruit Form</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
<form id="fruitForm">
<label for="name">Fruit Name:</label>
<input type="text" id="name" name="name">
<label for="price">Price:</label>
<input type="text" id="price" name="price">
<button type="submit">Submit</button>
</form>

<script>
$('#fruitForm').on('submit', function(e) {
e.preventDefault();
const fruitData = {
name: $('#name').val(),
price: $('#price').val()
};
$.ajax({
type: 'POST',
url: '/submit-fruit',
data: JSON.stringify(fruitData),
contentType: 'application/json',
success: function(response) {
console.log('Data sent to server:', response);
}
});
});
</script>
</body>
</html>

// Node.js Server
const express = require('express');
const app = express();
const port = 3000;

app.use(express.json());

app.post('/submit-fruit', (req, res) => {


console.log('Received fruit data:', req.body);
res.send('Fruit data received.');
});

app.listen(port, () => {
console.log(`Server running at http://localhost:${port}/`);
});

Experiment 7: Authentication Mechanism using HTML and Express.js

Objective:

● To develop an authentication mechanism using email_id and password with POST


method.

Tasks:
1. Create a simple HTML form for login.
2. Use Express.js to handle the POST request and validate the credentials.

Instructions:

1. Use HTML for the form and Express.js for server-side validation.

Code Sample:

html

<!-- HTML Form -->


<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Login</title>
</head>
<body>
<form action="/login" method="post">
<label for="email">Email:</label>
<input type="email" id="email" name="email">
<label for="password">Password:</label>
<input type="password" id="password" name="password">
<button type="submit">Login</button>
</form>
</body>
</html>

// Express.js Server
const express = require('express');
const app = express();
const port = 3000;

app.use(express.urlencoded({ extended: true }));

app.post('/login', (req, res) => {


const { email, password } = req.body;
if (email === '[email protected]' && password === 'password123') {
res.send('Login successful.');
} else {
res.send('Invalid credentials.');
}
});

app.listen(port, () => {
console.log(`Server running at http://localhost:${port}/`);
});

Experiment 8: Express.js Routing

Objective:

● To develop routes that handle specific functionalities using Express.js.

Tasks:
1. Develop two routes:
o find_prime_100 to print prime numbers less than 100.
o find_cube_100 to print cubes of numbers less than 100.

Instructions:

1. Use Express.js to define and handle routes.

Code Sample:

const express = require('express');


const app = express();
const port = 3000;

function findPrimes(limit) {
const primes = [];
for (let i = 2; i < limit; i++) {
let isPrime = true;
for (let j = 2; j <= Math.sqrt(i); j++) {
if (i % j === 0) {
isPrime = false;
break;
}
}
if (isPrime) primes.push(i);
}
return primes;
}

function findCubes(limit) {
const cubes = [];
for (let i = 1; i * i * i < limit; i++) {
cubes.push(i * i * i);
}
return cubes;
}

app.get('/find_prime_100', (req, res) => {


res.send(findPrimes(100));
});

app.get('/find_cube_100', (req, res) => {


res.send(findCubes(100));
});

app.listen(port, () => {
console.log(`Server running at http://localhost:${port}/`);
});

Experiment 9: React Search Filter

Objective:

● To build a simple search filter functionality in React.

Tasks:
1. Create a React component that displays a list of items.
2. Implement a search filter to display a filtered list based on user input.

Instructions:

1. Use React hooks for state management and filtering logic.

Code Sample:

import React, { useState } from 'react';

const SearchFilter = () => {


const [search, setSearch] = useState('');
const items = ['Apple', 'Banana', 'Cherry', 'Date', 'Elderberry',
'Fig', 'Grape'];

const handleSearch = (event) => {


setSearch(event.target.value);
};

const filteredItems = items.filter(item =>


item.toLowerCase().includes(search.toLowerCase()));

return (
<div>
<input type="text" placeholder="Search..." value={search}
onChange={handleSearch} />
<ul>
{filteredItems.map((item, index) => (
<li key={index}>{item}</li>
))}
</ul>
</div>
);
};

export default SearchFilter;

Experiment 10: Fetching Data from REST API with React

Objective:

● To collect and display data from a REST API using React.

Tasks:

1. Create a React component that fetches data from a REST API.


2. Display the fetched data in a list or table format.

Instructions:

1. Use useEffect hook to fetch data on component mount.


2. Use fetch or axios for making API calls.
Code Sample:

import React, { useState, useEffect } from 'react';

const DataFetcher = () => {


const [data, setData] = useState([]);
const [loading, setLoading] = useState(true);

useEffect(() => {
fetch('https://api.example.com/data')
.then(response => response.json())
.then(data => {
setData(data);
setLoading(false);
})
.catch(error => console.error('Error fetching data:', error));
}, []);

if (loading) {
return <div>Loading...</div>;
}

return (
<div>
<ul>
{data.map((item, index) => (
<li key={index}>{item.name}</li>
))}
</ul>
</div>
);
};

export default DataFetcher;

You might also like