Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
5 views

MongoDB Query

The document provides examples of MongoDB queries, Express.js routes, React components, Node.js scripts, and HTML with CSS. Each section includes a requirement, code example, and explanation of how the code works. The examples cover various functionalities such as querying a database, creating a web server, fetching data from an API, reading and writing files, and styling a form.

Uploaded by

asvikashpat01
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)
5 views

MongoDB Query

The document provides examples of MongoDB queries, Express.js routes, React components, Node.js scripts, and HTML with CSS. Each section includes a requirement, code example, and explanation of how the code works. The examples cover various functionalities such as querying a database, creating a web server, fetching data from an API, reading and writing files, and styling a form.

Uploaded by

asvikashpat01
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/ 9

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.

db.collectionName.find({ fieldName: { $gt: value } });

Explanation:

db.collectionName: 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.

db.products.find({ price: { $gt: 100 } });

This query returns all documents in the products collection with a price field greater than 100.

Express.js Route -

Requirement: Create a simple Express.js 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

app.get('/getParam/:param', (req, res) => {

const param = req.params.param; // Access the parameter from the URL

res.send(`You sent: ${param}`); // Send the parameter as the response

});

// Starting the server

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

});

Explanation:

1. Route Definition:
'/getParam/:param': The :param part represents a dynamic URL parameter.
The value in :param will be captured and accessible via req.params.param.

2. Accessing the Parameter:


req.params.param extracts the parameter from the URL.

3. Response:
res.send() sends the extracted parameter back to the client

4. Run the server with node server.js .,

5. Open a browser or use a tool like Postman and navigate to


http://localhost:3000/getParam/someValue., 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('https://jsonplaceholder.typicode.com/posts');

const data = await response.json();

setItems(data); // Update state with fetched items

} catch (error) {

console.error('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>

{items.map(item => (

<li key={item.id}>

<strong>{item.title}</strong>

<p>{item.body}</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:
https://jsonplaceholder.typicode.com/posts 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.

Node.js 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 = 'input.txt';

const outputFile = 'output.txt';

// Function to process data

const processData = (data) => {

// Example: Convert all text to uppercase

return data.toUpperCase();

};

// Read the input file

fs.readFile(inputFile, 'utf8', (err, data) => {

if (err) {

console.error(`Error reading file: ${err.message}`);

return;

console.log('File read successfully.');

// Process the data

const processedData = processData(data);

// Write the processed data to the output file

fs.writeFile(outputFile, processedData, (err) => {

if (err) {
console.error(`Error writing file: ${err.message}`);

return;

console.log('Processed data written to output file.');

});

});

Explanation:

1. File Reading:
fs.readFile reads the content of the input.txt 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:
fs.writeFile writes the processed data to output.txt.

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.

You might also like