MongoDB Query -
Requirement: Write a query to find all documents in a collection where a specific field has a
value greater than a certain value.
[Link]({ fieldName: { $gt: value } });
Explanation:
[Link]: Replace collectionName with the name of our MongoDB collection.
fieldName: Replace this with the name of the field to be checked.
$gt: Stands for "greater than".
value: Replace this with the value want to compare.
Example Use Case:
Suppose, there is a collection named products, and need to find all documents with a price
greater than 100.
[Link]({ price: { $gt: 100 } });
This query returns all documents in the products collection with a price field greater than 100.
[Link] Route -
Requirement: Create a simple [Link] route that takes a parameter from the URL and
returns it as a response.
Code Example:
const express = require('express');
const app = express();
const port = 3000;
// Defined a route with a URL parameter
[Link]('/getParam/:param', (req, res) => {
const param = [Link]; // Access the parameter from the URL
[Link](`You sent: ${param}`); // Send the parameter as the response
});
// Starting the server
[Link](port, () => {
[Link](`Server is running on [Link]
});
Explanation:
1. Route Definition:
'/getParam/:param': The :param part represents a dynamic URL parameter.
The value in :param will be captured and accessible via [Link].
2. Accessing the Parameter:
[Link] extracts the parameter from the URL.
3. Response:
[Link]() sends the extracted parameter back to the client
4. Run the server with node [Link] .,
5. Open a browser or use a tool like Postman and navigate to
[Link] we will see the response:
You sent: someValue.
React Component -
Requirement: Create a React component that fetches a list of items from an API and renders
them.
Code Example:
import React, { useEffect, useState } from 'react';
const ItemList = () => {
const [items, setItems] = useState([]);
const [loading, setLoading] = useState(true);
// Fetch data from API
useEffect(() => {
const fetchData = async () => {
try {
const response = await fetch('[Link]
const data = await [Link]();
setItems(data); // Update state with fetched items
} catch (error) {
[Link]('Error fetching data:', error);
} finally {
setLoading(false);
};
fetchData();
}, []);
// Render loading state or list of items
return (
<div>
<h1>Item List</h1>
{loading ? (
<p>Loading...</p>
):(
<ul>
{[Link](item => (
<li key={[Link]}>
<strong>{[Link]}</strong>
<p>{[Link]}</p>
</li>
))}
</ul>
)}
</div>
);
};
export default ItemList;
Explanation:
1. State Management:
items: Stores the list of items fetched from the API.
loading: Tracks whether the data is being loaded.
2. useEffect Hook:
Fetches data from the API when the component mounts.
Uses async/await for API calls and handles errors.
3. API Used:
[Link] is a sample API that provides placeholder
posts.
4. Conditional Rendering:
Displays "Loading..." while fetching data.
Renders the list of items after data is loaded.
5. List Rendering:
Uses map() to iterate over items and renders each as a list item.
[Link] Script -
Requirement: Create a script to read a file, process its data, and write the result to another
file.
Code Example:
const fs = require('fs');
// Input and output file paths
const inputFile = '[Link]';
const outputFile = '[Link]';
// Function to process data
const processData = (data) => {
// Example: Convert all text to uppercase
return [Link]();
};
// Read the input file
[Link](inputFile, 'utf8', (err, data) => {
if (err) {
[Link](`Error reading file: ${[Link]}`);
return;
[Link]('File read successfully.');
// Process the data
const processedData = processData(data);
// Write the processed data to the output file
[Link](outputFile, processedData, (err) => {
if (err) {
[Link](`Error writing file: ${[Link]}`);
return;
[Link]('Processed data written to output file.');
});
});
Explanation:
1. File Reading:
[Link] reads the content of the [Link] file.
The utf8 encoding ensures the file is read as text.
2. Data Processing:
The processData function modifies the data. In this example, it converts the text to
uppercase. We can replace this logic with any desired operation.
3. File Writing:
[Link] writes the processed data to [Link].
4. Error Handling:
Ensures that errors during reading or writing are logged for debugging.
HTML with CSS -
Requirement: Create an HTML form with a styled text input field and a submit button.
Code Example:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Styled Form</title>
<style>
body {
font-family: Arial, sans-serif;
background-color: #f4f4f4;
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
margin: 0;
form {
background: #fff;
padding: 20px;
border-radius: 8px;
box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
width: 300px;
h2 {
margin-bottom: 15px;
text-align: center;
color: #333;
input[type="text"] {
width: 100%;
padding: 10px;
margin-bottom: 15px;
border: 1px solid #ccc;
border-radius: 4px;
font-size: 16px;
input[type="text"]:focus {
border-color: #007bff;
outline: none;
box-shadow: 0 0 4px rgba(0, 123, 255, 0.5);
button {
width: 100%;
padding: 10px;
background-color: #007bff;
color: white;
border: none;
border-radius: 4px;
font-size: 16px;
cursor: pointer;
button:hover {
background-color: #0056b3;
</style>
</head>
<body>
<form action="#" method="post">
<h2>Styled Form</h2>
<input type="text" name="username" placeholder="Enter your name" required>
<button type="submit">Submit</button>
</form>
</body>
</html>
Explanation:
1. HTML Structure:
A form element with a text input field and a submit button.
The placeholder attribute provides a hint in the input field.
The required attribute ensures the input field is filled before submission.
2. CSS Styling:
Body Styling: Centered the form using flexbox.
Form Styling:
Added padding, border-radius, and a shadow for a clean design.
Input Field:
Styled with padding, border, and hover effects for focus.
Button:
Styled with a primary color and hover effect.
3. Responsive Design:
Ensures the form looks good on all devices using relative widths and flexbox.