0% found this document useful (0 votes)
3 views14 pages

MongoDB

The document provides an overview of MongoDB, Express.js, React, and Node.js, detailing their functionalities and differences. It covers CRUD operations, routing, middleware, error handling, and performance optimization techniques in a MERN stack application. Additionally, it discusses authentication methods and common challenges faced in MERN projects.

Uploaded by

Prince Singh
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)
3 views14 pages

MongoDB

The document provides an overview of MongoDB, Express.js, React, and Node.js, detailing their functionalities and differences. It covers CRUD operations, routing, middleware, error handling, and performance optimization techniques in a MERN stack application. Additionally, it discusses authentication methods and common challenges faced in MERN projects.

Uploaded by

Prince Singh
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/ 14

MongoDB

1. What is MongoDB and how does it differ from SQL databases?


MongoDB is a NoSQL database that stores data in a flexible, JSON-like
document format. Unlike SQL databases, it does not use tables, rows, or
predefined schemas. Instead, it uses collections and documents, allowing for
dynamic schema changes. SQL databases use structured query language (SQL)
for transactions, whereas MongoDB provides a flexible, schema-less approach,
making it ideal for unstructured or semi-structured data.

2. Explain the difference between find and aggregate in MongoDB.


- find() is used to retrieve documents that match specific criteria, similar to a
simple SQL SELECT statement.
- aggregate() is used for advanced data processing, including filtering,
grouping, and transforming data, similar to SQL's GROUP BY and aggregate
functions.

3. How do you perform CRUD operations in MongoDB?


- *Create*: db.collection.insertOne({name: "John", age: 25})
- *Read*: db.collection.find({age: 25})
- *Update*: db.collection.updateOne({name: "John"}, {$set: {age: 26}})
- *Delete*: db.collection.deleteOne({name: "John"})

4. What is a replica set in MongoDB and why is it important?


A replica set is a group of MongoDB instances that maintain the same data for
redundancy and failover. It ensures high availability by automatically electing a
new primary node if the main server fails.
5. How do you implement indexing in MongoDB?
Indexing improves query performance by creating a structured reference for
faster lookups. Example:
- Creating an index: db.collection.createIndex({name: 1}) (1 for ascending, -1
for descending)
- Checking indexes: db.collection.getIndexes()

Express.js

1. What is Express.js and how does it relate to Node.js?


Express.js is a web framework for Node.js that simplifies server-side
application development. It provides features like routing, middleware support,
and request handling, making backend development more efficient.

2. How do you handle routing in an Express application?


Routing in Express is done using app.get(), app.post(), app.put(), and
app.delete(). Example:
javascript
const express = require('express');
const app = express();
app.get('/home', (req, res) => {
res.send('Welcome to Home Page');
});
app.listen(3000, () => console.log('Server running'));
3. Explain middleware in Express. Can you give an example?
Middleware functions modify request and response objects and execute code
before sending a response. Example:
javascript
app.use((req, res, next) => {
console.log('Middleware executed');
next();
});

4. How do you handle errors in Express?


Express provides an error-handling middleware function with four
parameters. Example:
javascript
app.use((err, req, res, next) => {
console.error(err.stack);
res.status(500).send('Something broke!');
});

5. What are some security best practices when using Express?


- Use helmet to secure headers: app.use(require('helmet')());
- Validate user inputs to prevent injection attacks.
- Use environment variables for sensitive data.
- Implement authentication and authorization.
React

1.What is React and why would you use it over other frameworks?
React is a JavaScript library for building UI components. It offers fast
rendering through the Virtual DOM, component-based architecture, and
unidirectional data flow, making it more efficient than traditional frameworks.

2. Explain the difference between functional and class components in React.


- *Class components*: Use ES6 classes and have lifecycle methods. Example:
javascript
class MyComponent extends React.Component {
render() {
return <h1>Hello</h1>;
}
}

- *Functional components*: Use hooks instead of lifecycle methods. Example:


javascript
const MyComponent = () => <h1>Hello</h1>;

3. What is the virtual DOM and how does it work in React?


The Virtual DOM is a lightweight copy of the real DOM. React updates the
Virtual DOM first, compares changes with the previous state, and then updates
only the necessary parts of the actual DOM, improving performance.

4. How do you manage state in React?


State can be managed using:
- useState for local state:
javascript
const [count, setCount] = useState(0);

- Context API for global state.


- Redux for complex state management.

5. What are hooks in React and how are they used?


Hooks allow functional components to use state and lifecycle features.
Examples:
- useState: Manages state in functional components.
- useEffect: Handles side effects (API calls, event listeners).
javascript
useEffect(() => {
console.log("Component mounted");
}, []);

Node.js Questions

1. What is Node.js and how is it different from traditional server-side


programming?
Node.js is a runtime environment that allows developers to run JavaScript
outside the browser. It is built on *Chrome's V8 JavaScript engine* and is
commonly used for *backend development*.
Differences from traditional server-side programming:
- *Single-threaded & Event-driven:* Unlike traditional multi-threaded
architectures (e.g., Java, PHP), Node.js uses a *non-blocking* I/O model.
- *Asynchronous Execution:* Instead of waiting for tasks to complete
(blocking), Node.js can handle multiple requests simultaneously using
callbacks, promises, and async/await.
- *Uses JavaScript: Unlike PHP, Python, or Java, Node.js allows *full-stack
JavaScript* development.

2. How does the event-driven architecture work in Node.js?


Node.js follows an event-driven, non-blocking architecture that enables it to
handle multiple tasks efficiently.

- *Event Loop:* The core mechanism in Node.js that listens for events (e.g.,
HTTP requests, file system operations) and executes callback functions when an
event occurs.
- *Event Emitter:* Node.js has an EventEmitter module that allows applications
to define and listen for events.

*Example:*
javascript
const EventEmitter = require('events');
const event = new EventEmitter();

event.on('greet', () => {
console.log('Hello, Welcome to Node.js!');
});

event.emit('greet'); // Output: Hello, Welcome to Node.js!


---
3. Explain the difference between require and import in Node.js.*
Both require and import are used for module loading, but they differ in several
ways:

| Feature | require (CommonJS) | import (ES Modules) |


|-----------------|---------------------|-----------------------|
| Syntax | const x = require('module') | import x from 'module' |
| Execution | Runs synchronously | Supports async execution |
| Availability | Default in Node.js | Requires "type": "module" in package.json
|
| Usage | Used in older projects | Preferred in modern JS applications |

Example of *require*:
javascript
const fs = require('fs');

Example of *import*:
javascript
import fs from 'fs';

---
4. How do you handle asynchronous operations in Node.js?
Node.js supports several ways to handle *asynchronous operations*:

1. *Callbacks (Old method)*


javascript
const fs = require('fs');
fs.readFile('file.txt', 'utf8', (err, data) => {
if (err) console.error(err);
else console.log(data);
});

2. *Promises*
javascript
const fs = require('fs').promises;
fs.readFile('file.txt', 'utf8')
.then(data => console.log(data))
.catch(err => console.error(err));

3. *Async/Await (Best approach)*


javascript
const fs = require('fs').promises;
async function readFile() {
try {
let data = await fs.readFile('file.txt', 'utf8');
console.log(data);
} catch (err) {
console.error(err);
}
}
readFile();

---

5. What is the role of the package.json file in a Node.js project?


package.json is the *configuration file* for a Node.js project. It stores:
- *Project metadata* (name, version, description)
- *Dependencies* (dependencies and devDependencies)
- *Scripts* (npm start, npm test, etc.)
- *Configuration settings*

Example:
json
{
"name": "my-node-app",
"version": "1.0.0",
"description": "A sample Node.js application",
"dependencies": {
"express": "^4.18.2"
},
"scripts": {
"start": "node index.js"
}
}

To install dependencies:

npm install

---

Full MERN Stack Questions

1. Explain how data flows from the front-end (React) to the back-end
(Express/Node) and to the database (MongoDB).
In a *MERN stack* application, data flows in the following way:

1. Front-end (React)
- React makes an API request (e.g., fetch or Axios) to the backend.
- Example:
javascript
fetch('http://localhost:5000/api/users')
.then(res => res.json())
.then(data => console.log(data));
2. *Backend (Express/Node)*
- Express receives the request and processes it.
- Example:
javascript
app.get('/api/users', async (req, res) => {
const users = await User.find(); // Fetching from MongoDB
res.json(users);
});

3. *Database (MongoDB)*
- The backend queries MongoDB using *Mongoose* and sends the result
back to the frontend.

---

### *2. How do you handle authentication in a MERN stack application?*


Authentication can be handled using *JWT (JSON Web Token)* and *bcrypt*
for password hashing.

1. *User Registration*
javascript
const bcrypt = require('bcrypt');
const hashedPassword = await bcrypt.hash(req.body.password, 10);
const newUser = new User({ username: req.body.username, password:
hashedPassword });
await newUser.save();

2. *User Login (JWT Token Generation)*


javascript
const jwt = require('jsonwebtoken');
const token = jwt.sign({ userId: user._id }, 'secret_key', { expiresIn: '1h' });
res.json({ token });

3. *Protecting Routes*
javascript
const authMiddleware = (req, res, next) => {
const token = req.header('Authorization');
if (!token) return res.status(401).send('Access Denied');
try {
const verified = jwt.verify(token, 'secret_key');
req.user = verified;
next();
} catch (err) {
res.status(400).send('Invalid Token');
}
};

---
### *3. What are some common performance optimization techniques for a
MERN stack application?*
- *Optimize MongoDB Queries:* Use indexes (.createIndex()).
- *Use Caching:* Redis or in-memory caching.
- *Pagination & Lazy Loading:* Avoid fetching large datasets.
- *Optimize React Rendering:* Use React.memo, PureComponent, and avoid
unnecessary re-renders.
- *Use Load Balancers & Clustering:* Handle multiple requests efficiently.

---

### *4. Can you describe a challenging problem you encountered in a MERN
stack project?*
One common challenge in MERN applications is *handling large data sets
efficiently*.

*Problem:*
A dashboard with *thousands of records* was taking too long to load.

*Solution:*
- Implemented *pagination* with MongoDB’s .skip() and .limit().
- Used *server-side filtering* instead of fetching all data at once.
- Applied *Redis caching* to reduce database queries.

Example:
javascript
const users = await User.find().skip((page - 1) * limit).limit(limit);
---

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy