[go: up one dir, main page]

0% found this document useful (0 votes)
84 views12 pages

Mern lab Manual

The document outlines various programming tasks including MongoDB operations for transactions, querying data, checking request headers, manipulating objects in Node.js, CRUD operations on the file system, sending data via Ajax, implementing authentication, and developing routes for prime and cube numbers. It also includes React components for user input forms, search filters, and data collection from APIs. Each program is accompanied by sample code and intended functionality.

Uploaded by

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

Mern lab Manual

The document outlines various programming tasks including MongoDB operations for transactions, querying data, checking request headers, manipulating objects in Node.js, CRUD operations on the file system, sending data via Ajax, implementing authentication, and developing routes for prime and cube numbers. It also includes React components for user input forms, search filters, and data collection from APIs. Each program is accompanied by sample code and intended functionality.

Uploaded by

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

Program 1:

Using MongoDB, create a collection called transactions in database usermanaged (drop if it already exists)
and bulk load the data from a json file, transactions.json
Upsert the record from the new file called transactions_upsert.json in Mongodb.

Transaction.js

[
{
"_id": 1,
"name": "Transaction 1",
"amount": 100
},
{
"_id": 2,
"name": "Transaction 2",
"amount": 200
},
{
"_id": 3,
"name": "Transaction 3",
"amount": 300
}
]

Transaction_upsert.js

[
{
"_id": 2,
"name": "Updated Transaction 2",
"amount": 250
},
{
"_id": 4,
"name": "New Transaction 4",
"amount": 400
}
]

Program 2:
Query MongoDB with Conditions: [Create appropriate collection with necessary documents to answer the
query]

[
{
"_id": 1,
"Name": "Somu",
"Payment": {
"Total": 600
},
"Transaction": {
"Price": 400
}
},
{
"_id": 2,
"Name": "Ravi",
"Payment": {
"Total": 500
},
"Transaction": {
"Price": 350
}
},
{
"_id": 3,
"Name": "Somu",
"Payment": {
"Total": 700
},
"Transaction": {
"Price": 450
}
},
{
"_id": 4,
"Name": "Kumar",
"Payment": {
"Total": 800
},
"Transaction": {
"Price": 550
}
}
]

a.Find any record where Name is Somu

{ "Name": "Somu" }

b.Find any record where total payment amount(Payment.Total) is 600.

{ "Payment.Total": 600 }
c.Find any record where price(Transaction.price) is between 300 to 500.

{ "Transaction.Price": { $gte: 300, $lte: 500 } }

d.Calculate the total transaction amount by adding up Payment.Total in all records.

[
{
$group: {
_id: null,
totalAmount: { $sum: "$Payment.Total" }
}
}
]
Program 3a.
Write a program to check request header for cookies.

// a. Check Request Header for Cookies:

const http = require("http");

// Create a server
const server = http.createServer((req, res) => {
// Get request headers
const headers = req.headers;
console.log(headers, ".....");
// Check if 'cookie' header exists
if (headers.cookie) {
console.log("Cookies:", headers.cookie);
} else {
console.log("No cookies found in the request header.");
}

res.end("Check console for cookies information.");


});

// Listen on port 3000


server.listen(3000, () => {
console.log("Server running at http://localhost:3000/");
});

Output:

Program 3b.
write node.js program to print the a car object properties, delete the second property and get length of the
object.

const express = require("express");


const app = express();

// Sample car object


const car = {
brand: "Toyota",
model: "Camry",
year: 2020,
color: "Black",
};

// API endpoint to get car object properties


app.get("/api/car", (req, res) => {
res.json(car);
});

// API endpoint to delete the second property and get object length
app.delete("/api/car/:propertyIndex", (req, res) => {
const propertyIndex = parseInt(req.params.propertyIndex);

if (
isNaN(propertyIndex) ||
propertyIndex < 0 ||
propertyIndex >= Object.keys(car).length
){
return res.status(400).json({ error: "Invalid property index" });
}

const propertyToDelete = Object.keys(car)[propertyIndex];


delete car[propertyToDelete];

res.json({
deletedProperty: propertyToDelete,
remainingProperties: Object.keys(car),
objectLength: Object.keys(car).length,
});
});

// Start the server


const port = 3000;
app.listen(port, () => {
console.log(`Server is running on port ${port}`);
});

Output:
Program 5.
Implement all CRUD operations on a File System using Node JS

/*
!run one function at a time
*/

const fs = require("fs");

const createFile = (fileName, data) => {


fs.writeFile(fileName, data, (err) => {
if (err) {
console.error("Error creating file:", err);
} else {
console.log("File created successfully.");
}
});
};

createFile("example.txt", "This is a sample text file.");

const readFile = (fileName) => {


fs.readFile(fileName, "utf8", (err, data) => {
if (err) {
console.error("Error reading file:", err);
} else {
console.log("File content:");
console.log(data);
}
});
};

// readFile("example.txt");

const appendFile = (fileName, newData) => {


fs.appendFile(fileName, newData, (err) => {
if (err) {
console.error("Error appending to file:", err);
} else {
console.log("Data appended to file successfully.");
}
});
};

// appendFile("example.txt", "\nAdditional data appended.");

const updateFile = (fileName, newData) => {


fs.writeFile(fileName, newData, (err) => {
if (err) {
console.error("Error updating file:", err);
} else {
console.log("File updated successfully.");
}
});
};
// updateFile("example.txt", "This is updated content.");

const deleteFile = (fileName) => {


fs.unlink(fileName, (err) => {
if (err) {
console.error("Error deleting file:", err);
} else {
console.log("File deleted successfully.");
}
});
};

// deleteFile("example.txt");

Output :

Program 6.
Develop the application that sends fruit name and price data from client side to Node.js server using Ajax
import React, { useState } from "react";
import axios from "axios";

function App() {
const [name, setName] = useState("");
const [price, setPrice] = useState("");
const url = "http://localhost:5000";
const handleSubmit = async (e) => {
e.preventDefault();
try {
await axios.post(`${url}/api/fruits`, { name, price });
console.log("Data sent successfully");
// Optionally, you can reset the form fields here
} catch (error) {
console.error("Error sending data:", error);
}
};

return (
<div>
<h1>Fruit Data Form</h1>
<form onSubmit={handleSubmit}>
<label>
Fruit Name:
<input
type="text"
value={name}
onChange={(e) => setName(e.target.value)}
/>
</label>
<br />
<label>
Price:
<input
type="text"
value={price}
onChange={(e) => setPrice(e.target.value)}
/>
</label>
<br />
<button type="submit">Submit</button>
</form>
</div>
);
}

export default App;

Output:

Program 7:
Develop an authentication mechanism with email_id and password using HTML and Express JS (POST
method)

import React, { useState } from "react";


import axios from "axios";

function App() {
const [registerData, setRegisterData] = useState({ email: "", password: "" });
const [loginData, setLoginData] = useState({ email: "", password: "" });
const [message, setMessage] = useState("");
const handleRegister = async (e) => {
e.preventDefault();
try {
await axios.post("http://localhost:3000/register", registerData);
setMessage("User registered successfully");
} catch (error) {
setMessage("Error registering user");
console.error("Error registering user:", error);
}
};

const handleLogin = async (e) => {


e.preventDefault();
try {
await axios.post("http://localhost:3000/login", loginData);
setMessage("Login successful");
} catch (error) {
setMessage("Invalid credentials");
console.error("Error logging in user:", error);
}
};

return (
<div>
<h2>User Registration</h2>
<form onSubmit={handleRegister}>
<label>Email:</label>
<input
type="email"
value={registerData.email}
onChange={(e) =>
setRegisterData({ ...registerData, email: e.target.value })
}
required
/>
<br />
<label>Password:</label>
<input
type="password"
value={registerData.password}
onChange={(e) =>
setRegisterData({ ...registerData, password: e.target.value })
}
required
/>
<br />
<button type="submit">Register</button>
</form>

<h2>User Login</h2>
<form onSubmit={handleLogin}>
<label>Email:</label>
<input
type="email"
value={loginData.email}
onChange={(e) =>
setLoginData({ ...loginData, email: e.target.value })
}
required
/>
<br />
<label>Password:</label>
<input
type="password"
value={loginData.password}
onChange={(e) =>
setLoginData({ ...loginData, password: e.target.value })
}
required
/>
<br />
<button type="submit">Login</button>
</form>

{message && <p>{message}</p>}


</div>
);
}

export default App;

Output:

Program 8:
Develop two routes: find_prime_100 and find_cube_100 which prints prime numbers less than 100 and
cubes less than 100 using Express JS routing mechanism

const express = require("express");


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

// Route to find prime numbers less than 100


app.get("/find_prime_100", (req, res) => {
const primes = findPrimes(100);
res.json({ primes });
});

// Route to find cubes less than 100


app.get("/find_cube_100", (req, res) => {
const cubes = findCubes(100);
res.json({ cubes });
});

// Function to find prime numbers less than n


function findPrimes(n) {
const primes = [];
for (let i = 2; i < n; 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 to find cubes less than n


function findCubes(n) {
const cubes = [];
for (let i = 1; i < n; i++) {
const cube = i * i * i;
if (cube < n) {
cubes.push(cube);
} else {
break;
}
}
return cubes;
}

// Start the server


app.listen(PORT, () => {
console.log(`Server is running on http://localhost:${PORT}`);
});
Output :
Program 9 :
Develop a React code to build a simple search filter functionality to display a filtered list based on the
search query entered by the user.

import React from "react";


import SearchFilter from "./SearchFilter";

function App() {
return (
<div>
<SearchFilter />
</div>
);
}

export default App;

Output :

Program 10:
Develop a React code to collect data from rest API.
import React, { useState, useEffect } from "react";
import axios from "axios";

function DataCollector() {
const [data, setData] = useState([]);

useEffect(() => {
fetchData();
}, []);

const fetchData = async () => {


try {
const response = await axios.get(
"https://dummy.restapiexample.com/api/v1/employees"
);
setData(response.data.data);
} catch (error) {
console.error("Error fetching data:", error);
}
};

return (
<div>
<h2>Data Collection</h2>
<button onClick={fetchData}>Fetch Data</button>
<ul>
{data.map((item, index) => (
<li key={index}>{item.employee_name}</li>
))}
</ul>
</div>
);
}

export default DataCollector;

You might also like