0% found this document useful (0 votes)
8 views

Assignment Mfd

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)
8 views

Assignment Mfd

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/ 20

Assignment - 3

Q:-1

1. Purpose of the HTTP module in Node.js: The HTTP module in Node.js allows
developers to create and manage web servers and handle HTTP requests and
responses. It is used to build web applications and APIs by enabling communication
between clients and servers.
2. What is React and why it is used in web development? React is a JavaScript library
developed by Facebook for building user interfaces, particularly for single-page
applications. It is used in web development for creating interactive, reusable UI
components, and efficiently updating the view with changes in the data using a virtual
DOM.
3. What is the use of Node.js? Node.js is a JavaScript runtime built on Chrome’s V8
JavaScript engine that allows developers to run JavaScript code on the server-side. It
is used for building fast, scalable, and real-time network applications, especially for
handling I/O operations like web servers and APIs.
4. Different data types in Node.js: Node.js supports various data types similar to
JavaScript. The common data types are:
o String: Represents textual data.
o Number: Represents numeric values (integers or floating-point numbers).
o Boolean: Represents true or false values.
o Object: Represents a collection of key-value pairs.
o Array: Represents an ordered list of values.
o Null: Represents an empty or non-existent value.
o Undefined: Represents a variable that has been declared but not assigned a
value.
o Buffer: Represents binary data in Node.js (mainly used for I/O operations).

Q:2

1. Create a simple Node.js web server that responds with "Hello, World!"

Here’s a simple example of a Node.js web server:

Code:

javascript
Copy code
// Load the http module to create an HTTP server
const http = require('http');

// Create an HTTP server and handle requests


const server = http.createServer((req, res) => {
// Set the response HTTP header to indicate the type of content
res.writeHead(200, { 'Content-Type': 'text/plain' });

// Send a response with "Hello, World!"


res.end('Hello, World!\n');
});

// The server listens on port 3000, and when it's ready, logs a message
server.listen(3000, () => {
console.log('Server running at http://localhost:3000/');
});

Explanation:

• require('http'): Loads the HTTP module that allows us to create an HTTP server.
• http.createServer(): Creates a server that listens for requests and sends a
response. The callback function takes two arguments: req (request) and res
(response).
• res.writeHead(200, { 'Content-Type': 'text/plain' }): Sends an HTTP
response with status code 200 (OK) and specifies that the response content type is
plain text.
• res.end('Hello, World!\n'): Ends the response and sends the message "Hello,
World!" to the client.
• server.listen(3000): Makes the server listen for incoming requests on port 3000.

2. Explain what middleware is in the context of Node.js and provide an


example of a simple middleware function that logs request details

Middleware in Node.js, especially in frameworks like Express, refers to functions that have
access to the request (req), response (res), and the next middleware function in the request-
response cycle. Middleware functions can modify the request, the response, or end the
request-response cycle.

Example of a simple middleware function in Express that logs request details:

javascript
Copy code
const express = require('express');
const app = express();

// Middleware function to log request details


app.use((req, res, next) => {
console.log(`${req.method} request made to: ${req.url}`);
next(); // Pass control to the next middleware or route handler
});

// A simple route to test the middleware


app.get('/', (req, res) => {
res.send('Hello, World!');
});

// Start the server


app.listen(3000, () => {
console.log('Server running on http://localhost:3000');
});
3. List and discuss features of Node.js

Some key features of Node.js include:

• Non-blocking, Asynchronous I/O: Node.js uses an event-driven, non-blocking I/O


model, which allows handling multiple requests without waiting for previous ones to
complete. This makes it highly efficient for I/O-bound operations like database
queries or file system access.
• Single-Threaded Event Loop: Node.js runs on a single thread using an event loop,
which allows it to handle multiple concurrent connections without the overhead of
managing multiple threads.
• Fast Execution with V8 Engine: Node.js uses Google Chrome's V8 JavaScript
engine, which compiles JavaScript directly to machine code, making it extremely fast
for server-side applications.
• Cross-Platform: Node.js is cross-platform and can run on Windows, macOS, and
Linux.
• Built-in Libraries and Modules: Node.js comes with a wide range of built-in
libraries (e.g., HTTP, File System, Path, etc.) for developing various types of
applications.
• NPM (Node Package Manager): Node.js includes NPM, which is a package
manager for installing and managing dependencies. It has a vast ecosystem of open-
source libraries available.
• Scalability: Node.js is well-suited for building scalable applications due to its
asynchronous nature and ability to handle a large number of simultaneous connections
efficiently.

4. Discuss NPM (Node Package Manager) in Node.js

NPM (Node Package Manager) is a package manager for JavaScript and is the default
package manager for Node.js. It simplifies the management of project dependencies, allows
developers to easily share and reuse code, and makes it easy to install libraries and tools for
Node.js projects.

Key features of NPM:

• Package Management: NPM allows developers to easily install, update, and manage
third-party libraries (called packages) that are used in their Node.js applications. This
is done using the npm install command.
• Dependency Management: NPM automatically resolves and installs dependencies
required by a package. It ensures that the correct versions of libraries are installed for
compatibility.
• Publishing and Sharing Packages: Developers can publish their own packages to
the NPM registry, making it easy for others to install and use them in their projects.
To publish a package, developers use npm publish.
• NPM Scripts: NPM allows defining custom scripts in a package.json file, such as
build, test, or start scripts, making it easy to automate tasks.
• NPM Registry: The NPM registry is a large collection of open-source packages
available for use. It is the largest ecosystem of open-source libraries in the world.
Basic commands in NPM:

• npm install <package>: Installs a package.


• npm init: Initializes a new Node.js project and creates a package.json file.
• npm update: Updates the installed packages to their latest versions.
• npm list: Lists all installed packages and their dependencies.

Overall, NPM plays a crucial role in the Node.js ecosystem by simplifying the process of
managing and using packages.

Q-3

1. Node.js Application to Serve an HTML File and Inspect Request Headers

Here’s a Node.js application that serves an HTML file and logs request headers.

Code:

const http = require('http');


const fs = require('fs');
const path = require('path');

// Create an HTTP server


const server = http.createServer((req, res) => {
// Log the request headers
console.log('Request Headers:', req.headers);

// Serve the HTML file


if (req.url === '/') {
const filePath = path.join(__dirname, 'index.html');

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


if (err) {
res.writeHead(500, { 'Content-Type': 'text/plain' });
res.end('Internal Server Error');
} else {
res.writeHead(200, { 'Content-Type': 'text/html' });
res.end(data);
}
});
} else {
res.writeHead(404, { 'Content-Type': 'text/plain' });
res.end('Not Found');
}
});

// Start the server


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

Explanation:

• http.createServer(): Creates an HTTP server that listens for incoming requests.


• req.headers: Logs the headers of the incoming HTTP request. The headers property of
the req object contains all the HTTP headers sent by the client.
• Serving HTML file: The code checks if the request URL is / (root). If so, it reads the HTML file
(index.html) from the file system and serves it as a response. If there's an error reading
the file, a 500 Internal Server Error is returned.
• 404 Response: If the requested URL doesn't match /, a 404 Not Found response is sent.
• Logging Request Headers: The request headers are logged using
console.log(req.headers).

You will need an index.html file in the same directory as this Node.js script for the server to
serve it.

2. How to Create an HTTPS Server in Node.js with Self-Signed Certificates

To create an HTTPS server, you need an SSL/TLS certificate. In the case of a self-signed
certificate, you can generate one using tools like OpenSSL. Here's how to create an HTTPS
server with self-signed certificates.

Step 1: Generate a Self-Signed Certificate

You can generate a self-signed certificate with OpenSSL using the following commands:

openssl genpkey -algorithm RSA -out private.key -pkeyopt


rsa_keygen_bits:2048
openssl req -new -key private.key -out server.csr
openssl x509 -req -days 365 -in server.csr -signkey private.key -out
server.crt

This will generate private.key (private key) and server.crt (certificate).

Step 2: Code for HTTPS Server


const https = require('https');
const fs = require('fs');

// Read the self-signed certificate and private key


const options = {
key: fs.readFileSync('private.key'),
cert: fs.readFileSync('server.crt')
};

// Create an HTTPS server


const server = https.createServer(options, (req, res) => {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('Hello, Secure World!\n');
});

// Start the server on port 3000


server.listen(3000, () => {
console.log('HTTPS server running at https://localhost:3000/');
});

Explanation:
• https.createServer(): Creates an HTTPS server using the provided options (key and
cert).
• fs.readFileSync(): Reads the self-signed certificate and private key from files
(server.crt and private.key).
• res.writeHead(): Sets the response status code and headers.
• server.listen(): Starts the server on port 3000, which can now handle HTTPS requests
securely.

When you visit https://localhost:3000/, your browser may show a warning about the
self-signed certificate, but you can proceed with the connection.

3. Write a Node.js Code to Create a Server

Here’s the simplest way to create a server in Node.js using the built-in HTTP module:

Code:

const http = require('http');

// Create a simple HTTP server


const server = http.createServer((req, res) => {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('Hello, World!\n');
});

// Start the server on port 3000


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

Explanation:

• http.createServer(): Creates an HTTP server that listens for incoming requests.


• server.listen(3000): Tells the server to listen on port 3000 for incoming requests.
• res.writeHead(): Sends the response status and content type.
• res.end(): Ends the response and sends the message "Hello, World!" to the client.

4. Create a Simple Server in Node.js that Returns "Hello World"

The simplest way to create a server in Node.js is:

Code:

const http = require('http');

// Create a server that responds with "Hello World"


http.createServer((req, res) => {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('Hello World');
}).listen(3000, () => {
console.log('Server running at http://localhost:3000/');
});

Explanation:

• http.createServer(): Creates the server that listens for HTTP requests.


• res.writeHead(): Sets the HTTP status code to 200 (OK) and the content type to
"text/plain."
• res.end('Hello World'): Sends the "Hello World" message as the response and ends it.
• listen(3000): Starts the server on port 3000.

When the server is running, visiting http://localhost:3000/ will display "Hello World"
in the browser.
Assignment : 4

Que 1: Answer the following Questions. (2 Marks)

1. What is Express.js, and why is it commonly used in Node.js applications?

Express.js is a fast, minimalist, and flexible web application framework for Node.js. It
simplifies the process of building web applications and APIs by providing a set of features
and tools, such as routing, middleware support, and easy handling of HTTP requests. It is
commonly used in Node.js applications because it simplifies the creation of robust, scalable
web servers and allows developers to focus more on building features rather than dealing
with low-level HTTP requests and responses.

2. Define the following for the Express framework:

• Serving static pages: In Express, static files such as images, CSS, and JavaScript
files can be served using the built-in express.static() middleware. This
middleware allows the app to serve files from a specified directory.

Example:

app.use(express.static('public'));

• Listing directory contents: Express does not natively list directory contents, but you
can implement this functionality using the fs module from Node.js to read and return
the contents of a directory.
• Handling cookies: Express allows handling cookies with the help of the cookie-
parser middleware. This middleware parses cookies attached to the incoming
requests and makes them available in req.cookies.

Example:

app.use(cookieParser());

• Cookie-based sessions: Express can handle sessions using the express-session


middleware, which enables session management using cookies to store session data
on the client side.

Example:

app.use(session({ secret: 'my-secret-key', resave: false,


saveUninitialized: true }));
• Compression: Express supports response compression using the compression
middleware, which reduces the size of the response body and speeds up the transfer of
data over the network.

Example:

app.use(compression());

• Time-out requests: Express supports request timeouts using middleware like


timeout to set a maximum time for request processing.

Example:

app.use(timeout('5s'));

• Express response object: The response object (res) in Express is used to send back
the HTTP response to the client. It provides methods like res.send(), res.json(),
res.status(), and res.redirect() to handle the response.

Que 2: Answer the following Questions. (4 Marks)

1. Write a simple Express application that serves a static HTML page from a directory called "public".
Include the code and explain how static files are served.

Code:

const express = require('express');


const path = require('path');
const app = express();

// Serve static files from the "public" directory


app.use(express.static(path.join(__dirname, 'public')));

// Start the server


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

Explanation:

• express.static() middleware is used to serve static files like HTML, CSS, and JavaScript
from the public directory.
• path.join(__dirname, 'public') generates the absolute path to the public
directory, ensuring platform compatibility (e.g., Windows vs Linux file paths).
• The server will respond to requests with files from the public directory (e.g.,
index.html).
2. Explain how to use middleware to handle cookies in an Express application. Provide an example of
setting and reading cookies.

Code Example:

const express = require('express');


const cookieParser = require('cookie-parser');
const app = express();

// Use cookie-parser middleware


app.use(cookieParser());

// Route to set a cookie


app.get('/set-cookie', (req, res) => {
res.cookie('username', 'john_doe', { maxAge: 900000, httpOnly: true });
res.send('Cookie has been set!');
});

// Route to read a cookie


app.get('/get-cookie', (req, res) => {
const username = req.cookies.username;
if (username) {
res.send(`Hello, ${username}`);
} else {
res.send('No cookie found!');
}
});

// Start the server


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

Explanation:

• cookie-parser middleware is used to parse cookies sent in requests, making them


available via req.cookies.
• In the /set-cookie route, the res.cookie() method is used to set a cookie named
username with the value john_doe.
• The /get-cookie route retrieves the username cookie using req.cookies.username
and sends a response based on its value.

Que 3: Answer the following Questions. (6 Marks)

1. Create an Express application that accepts JSON requests and HTML form inputs, handling both
types of data. Include the code and explain how to parse these inputs.

Code:

const express = require('express');


const bodyParser = require('body-parser');
const app = express();
// Middleware to parse JSON requests
app.use(bodyParser.json());

// Middleware to parse URL-encoded form data


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

// Route to handle JSON input


app.post('/json', (req, res) => {
const data = req.body; // Parse JSON data
res.send(`Received JSON data: ${JSON.stringify(data)}`);
});

// Route to handle HTML form input


app.post('/form', (req, res) => {
const name = req.body.name; // Access form data
res.send(`Received form data: Hello, ${name}`);
});

// Start the server


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

Explanation:

• body-parser.json() middleware is used to parse incoming JSON data in the request


body.
• body-parser.urlencoded({ extended: true }) middleware parses data from HTML
form submissions.
• In the /json route, JSON data is parsed and accessed via req.body.
• In the /form route, form input is accessed using req.body.name, where name is the field
in the HTML form.

2. Discuss the concept of REST in the context of Express.js and create a simple RESTful API with routes
for GET and POST methods.

Explanation of REST in Express.js:

• REST (Representational State Transfer) is an architectural style for designing networked


applications. It uses a stateless communication model, where resources (data) are identified
by URLs, and operations are performed using standard HTTP methods like GET, POST, PUT,
DELETE.
• In Express.js, RESTful APIs can be created by defining routes for different HTTP methods
(GET, POST, etc.) and performing actions on resources like databases.

Code:

const express = require('express');


const app = express();

app.use(express.json());

// Sample in-memory data store


let users = [{ id: 1, name: 'John Doe' }];
// GET route to fetch users
app.get('/users', (req, res) => {
res.json(users);
});

// POST route to add a new user


app.post('/users', (req, res) => {
const newUser = req.body;
newUser.id = users.length + 1;
users.push(newUser);
res.status(201).json(newUser);
});

// Start the server


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

Explanation:

• GET /users: Retrieves a list of users from the in-memory data store and sends it as JSON.
• POST /users: Accepts a new user (in JSON format) via a POST request and adds it to the
users array. The new user is then returned with a status code of 201 (Created).

3. Define REST Architecture in Node.js.

REST Architecture in Node.js:

• REST (Representational State Transfer) is a software architectural style that is based on a set
of principles and constraints, which guide the design of stateless client-server
communication over HTTP.
• Resources: Each resource (e.g., user, product) is identified by a unique URL.
• HTTP Methods: Standard HTTP methods (GET, POST, PUT, DELETE) are used to perform
CRUD (Create, Read, Update, Delete) operations on resources.
• Stateless Communication: Each request from the client to the server must contain all the
information needed to understand and process the request. The server does not store any
state between requests.
• JSON: Data is typically exchanged in the form of JSON, making it easy to parse and work
with.

Node.js, with frameworks like Express, makes it easy to build RESTful APIs by defining
routes for HTTP methods and performing actions on resources. The RESTful API can be
extended by adding additional routes, using middleware, and interacting with databases to
persist data.
Assignment:5

Que 1: Answer the following Questions. (2 Marks)

1. Explain the difference between SQL and NoSQL databases.

SQL Databases (Relational Databases) are based on a structured schema that defines tables
with predefined columns. They use the SQL (Structured Query Language) for managing and
manipulating data. Data is stored in rows, and relationships between different tables are
established using foreign keys. Examples of SQL databases include MySQL, PostgreSQL,
and SQLite.

NoSQL Databases, on the other hand, are non-relational databases that do not require a fixed
schema. They store data in various formats such as key-value pairs, documents, wide-column
stores, or graphs. NoSQL databases are more flexible in terms of schema and are highly
scalable. Examples include MongoDB, Cassandra, and CouchDB.

Key Differences:

• Structure: SQL uses a fixed schema with tables, whereas NoSQL uses flexible schema types
like documents or key-value pairs.
• Scalability: NoSQL is typically horizontally scalable (distributed), while SQL is vertically
scalable.
• Transactions: SQL databases follow ACID properties, ensuring strong consistency, while
NoSQL databases may use eventual consistency for scalability and performance.

2. Write a note on MongoDB.

MongoDB is a popular NoSQL document-oriented database that stores data in JSON-like


format (BSON - Binary JSON). It is designed for scalability, flexibility, and performance.
MongoDB allows developers to store and retrieve large volumes of unstructured data
efficiently, which is ideal for applications that require high availability and speed. Unlike
relational databases, MongoDB does not require a predefined schema, which allows for
dynamic and rapid application development. It also supports horizontal scaling through
sharding, making it well-suited for big data and real-time applications.

3. Explain the basic concepts of MongoDB. Include definitions for Document, Collection, and Database.

• Document: A document in MongoDB is a basic unit of data, similar to a row in a


relational database. It is represented in BSON (Binary JSON) format and stores data
in key-value pairs. A document can store nested data structures like arrays and
objects, making MongoDB flexible for complex data models.
Example:

{
"_id": ObjectId("507f1f77bcf86cd799439011"),
"name": "Alice",
"age": 25,
"email": "[email protected]"
}

• Collection: A collection in MongoDB is a group of documents. It is similar to a table


in a relational database but does not enforce a schema, meaning documents in the
same collection can have different structures. Collections are used to organize and
store related documents.

Example: A users collection might contain documents representing different users.

• Database: A database in MongoDB is a container for collections. It can hold multiple


collections, and each collection can store a large number of documents. MongoDB
allows the creation of multiple databases within the same instance.

Example: A usersDB database might contain collections like users, orders, and
products.

4. What is a MongoDB document?

A MongoDB document is a set of key-value pairs stored in BSON (Binary JSON) format. It
represents a single data record and can contain nested data structures such as arrays or other
documents. Unlike rows in SQL, MongoDB documents are schema-less, meaning each
document can have different fields and data types.

Example Document:

{
"_id": ObjectId("507f1f77bcf86cd799439011"),
"name": "John",
"email": "[email protected]",
"age": 30,
"addresses": [
{ "type": "home", "address": "123 Street Name" },
{ "type": "work", "address": "456 Business Rd." }
]
}

5. What is the purpose of the _id field in MongoDB?

In MongoDB, the _id field is a unique identifier for each document in a collection. If you
don't explicitly provide an _id when inserting a document, MongoDB will automatically
generate a unique ObjectId for it. The _id field is used to ensure the uniqueness of each
document in a collection and is indexed by default for fast retrieval.
Example:

{
"_id": ObjectId("507f1f77bcf86cd799439011"),
"name": "Alice"
}

6. What is the role of Mongoose in MongoDB development?

Mongoose is an Object Data Modeling (ODM) library for MongoDB and Node.js. It provides
a higher-level abstraction over the native MongoDB driver by offering a schema-based
solution to model data, allowing developers to define how the data should be structured,
validated, and queried. Mongoose helps with data validation, casting, business logic, and
more, making it easier to interact with MongoDB in Node.js applications.

Benefits of Mongoose:

• Schema-based data modeling


• Built-in validation and type casting
• Middleware support (for hooks like pre/post save, etc.)
• Query building with built-in functions

Que 2: Answer the following Questions. (4 Marks)

1. Describe the advantages of using MongoDB over traditional relational databases.

Advantages of MongoDB over SQL Databases:

• Schema Flexibility: MongoDB is schema-less, which allows for dynamic and flexible data
storage. You don’t need to define the schema upfront, and documents in a collection can
have different structures.
• Scalability: MongoDB provides built-in horizontal scaling through sharding, making it
suitable for applications with large datasets or traffic.
• Performance: MongoDB stores data in memory-mapped files and can quickly index large
volumes of data. It is optimized for high throughput and real-time applications.
• High Availability: MongoDB supports replication (master-slave) for redundancy and fault
tolerance, ensuring high availability.
• Ease of Use: MongoDB is developer-friendly, with simple JSON-based queries and flexible
data types, unlike SQL databases that require complex joins and predefined schemas.

2. What is "callback hell" in JavaScript, and how does it relate to MongoDB operations? Provide an
example.

Callback hell refers to the situation where multiple nested callbacks are used in
asynchronous programming, leading to code that is difficult to read, maintain, and debug.
In MongoDB operations, callback hell occurs when performing multiple asynchronous
operations, such as querying, inserting, or updating documents, with each operation relying
on a callback function.

Example:

db.collection('users').findOne({ name: 'Alice' }, function(err, user) {


if (err) throw err;
db.collection('orders').findOne({ userId: user._id }, function(err,
order) {
if (err) throw err;
db.collection('payments').findOne({ orderId: order._id }, function(err,
payment) {
if (err) throw err;
console.log(payment);
});
});
});

This results in deeply nested callbacks, leading to hard-to-manage code.

Solution: Using Promises or async/await can eliminate callback hell and make the code
more readable and maintainable.

3. Explain the CRUD operations in MongoDB and give an example of each operation using the
MongoDB shell.

CRUD Operations in MongoDB:

• Create: Add a new document to a collection.


• db.users.insertOne({ name: "Alice", age: 25, email:
"[email protected]" });
• Read: Retrieve documents from a collection.
• db.users.find({ name: "Alice" });
• Update: Modify existing documents in a collection.
• db.users.updateOne({ name: "Alice" }, { $set: { age: 26 } });
• Delete: Remove documents from a collection.
• db.users.deleteOne({ name: "Alice" });

4. Explain the concept of Promises in JavaScript. How do Promises improve the management of
asynchronous code in MongoDB? Provide a simple example.

A Promise is an object in JavaScript that represents the eventual completion or failure of an


asynchronous operation. Promises provide a cleaner and more manageable way to handle
asynchronous operations compared to callbacks, avoiding callback hell.

Advantages of Promises:

• Promises allow chaining (.then()), making code more readable.


• They improve error handling using .catch() for promise rejection.
• Promises handle asynchronous operations in a more structured and predictable way.

Example:

const MongoClient = require('mongodb').MongoClient;

MongoClient.connect('mongodb://localhost:27017', { useNewUrlParser: true })


.then(client => {
const db = client.db('mydb');
return db.collection('users').findOne({ name: 'Alice' });
})
.then(user => {
console.log(user);
})
.catch(err => {
console.log('Error:', err);
});

Promises improve the readability and maintainability of asynchronous code compared to


traditional callbacks.

Que 3: Answer the following Questions. (6 Marks)

1. Create a simple Node.js application that uses Mongoose to connect to a MongoDB database,
defines a schema, and performs CRUD operations (Create, Read, Update, Delete) on a collection.

Code Example:

const mongoose = require('mongoose');

// Connect to MongoDB
mongoose.connect('mongodb://localhost:27017/testdb', { useNewUrlParser:
true, useUnifiedTopology: true })
.then(() => console.log('Connected to MongoDB'))
.catch(err => console.error('Error connecting to MongoDB', err));

// Define a schema
const userSchema = new mongoose.Schema({
name: String,
age: Number,
email: String
});

// Create a model
const User = mongoose.model('User', userSchema);

// CRUD Operations:

// Create
const createUser = async () => {
const user = new User({ name: 'Alice', age: 25, email:
'[email protected]' });
await user.save();
console.log('User created:', user);
};
// Read
const getUser = async () => {
const user = await User.findOne({ name: 'Alice' });
console.log('User found:', user);
};

// Update
const updateUser = async () => {
const user = await User.findOneAndUpdate({ name: 'Alice' }, { age: 26 });
console.log('User updated:', user);
};

// Delete
const deleteUser = async () => {
const result = await User.deleteOne({ name: 'Alice' });
console.log('User deleted:', result);
};

// Execute CRUD operations


createUser();
getUser();
updateUser();
deleteUser();

2. Explain in detail the process of setting up Mongoose in a Node.js application. Include the steps for
creating a schema, defining models, and performing CRUD operations. Provide an example where a
"User" schema is created and basic CRUD operations are performed.

1. Install Mongoose:
2. npm install mongoose
3. Connect to MongoDB: In the application, use mongoose.connect() to connect to
the MongoDB instance.
4. Define a Schema: A schema defines the structure of documents in a collection. Use
new mongoose.Schema() to define the schema.
5. Create a Model: A model is a wrapper for the schema. Use mongoose.model() to
define a model that you will interact with for CRUD operations.
6. CRUD Operations: Use model methods like create(), find(), update(), and
delete() to perform CRUD operations.

Example (CRUD with User schema):

const mongoose = require('mongoose');


mongoose.connect('mongodb://localhost:27017/mydb', { useNewUrlParser: true,
useUnifiedTopology: true });

const userSchema = new mongoose.Schema({


name: String,
age: Number,
email: String
});

const User = mongoose.model('User', userSchema);

// Create
const createUser = async () => {
const user = new User({ name: 'John', age: 30, email: '[email protected]'
});
await user.save();
console.log('User Created:', user);
};

// Read
const getUser = async () => {
const user = await User.findOne({ name: 'John' });
console.log('User Found:', user

); };

// Update const updateUser = async () => { const user = await User.findOneAndUpdate({


name: 'John' }, { age: 31 }); console.log('User Updated:', user); };

// Delete const deleteUser = async () => { const result = await User.deleteOne({ name: 'John'
}); console.log('User Deleted:', result); };

createUser(); getUser(); updateUser(); deleteUser();

---

#### 3. **Discuss the importance of indexes in MongoDB. How does MongoDB


handle indexing, and how would you create an index on a specific field in
MongoDB?**

**Importance of Indexes in MongoDB**:


- **Performance**: Indexes improve the speed of query operations by
allowing the database to quickly locate documents based on field values,
rather than scanning the entire collection.
- **Efficiency**: Indexes are particularly beneficial for large collections
with frequent query operations, significantly reducing query time.

**How MongoDB Handles Indexing**:


- By default, MongoDB creates an index on the **_id** field for every
collection.
- Developers can create custom indexes on other fields to optimize query
performance.

**Creating an Index**:
```javascript
// Create an index on the "name" field
db.users.createIndex({ name: 1 });

The { name: 1 } indicates an ascending order index. For descending order, you can use {
name: -1 }.

Indexes improve query speed, but they come with a tradeoff in terms of memory usage and
write performance since indexes need to be updated whenever a document is inserted or
updated.

You might also like