Professional Documents
Culture Documents
Unit 4_QB_FST (3)
Unit 4_QB_FST (3)
Ans:
In building RESTful APIs using Express, HTTP methods
play a crucial role in defining the operations that can be
performed on resources. For example:
Ans:
Middleware in Express enhances the functionality of the
application by allowing developers to perform additional
tasks during the request-response cycle. Middleware
functions can be used to handle tasks such as logging,
authentication, or parsing request bodies. For example, the
body-parser middleware is commonly used to parse
incoming request bodies in JSON format. This is crucial
when dealing with POST requests that contain data.
Example:
const express = require('express');
const bodyParser = require('body-parser');
Ans:
The async keyword is used to declare a function as
asynchronous in JavaScript. When a function is marked as
async, it allows the use of the await keyword within the
function body to handle asynchronous operations. The
await keyword is used to pause the execution of the async
function until the promise is resolved, simplifying
asynchronous code.
Example:
async function fetchData() {
// Asynchronous operation using 'await'
const result = await
someAsyncFunction(); return result;
}
Ans:
Callback functions in asynchronous JavaScript are
functions that are passed as arguments to other functions
and are executed after the completion of an
asynchronous operation. They help handle asynchronous
tasks by specifying what should happen once the
operation is complete.
For example:
function fetchData(callback) {
// Simulate an asynchronous operation
setTimeout(() => {
const data = 'Async data';
callback(data);
}, 1000);
}
Ans:
Mongoose is an ODM (Object-Document Mapper) for
MongoDB and Node.js. It provides a schema-based
solution to model and interact with MongoDB documents
in a more structured manner. When it comes to CRUD
operations:
Ans:
Mongoose allows developers to define schema
structures, including data types and constraints. During
the creation of documents, Mongoose automatically
validates data based on these defined schemas. This
validation ensures that the data adheres to the specified
rules, such as required fields, data types, and custom
validations. It is crucial for maintaining data integrity
and consistency, preventing the insertion of invalid or
incorrect data into the MongoDB database. Validation
in Mongoose helps to enforce a predefined structure and
enhances the reliability of the data being stored.
Ans:
Ans:
The required property in a Mongoose schema is used to
specify whether a particular field must have a value before
a document can be saved to the MongoDB collection. If
required is set to true for a field, it means that the field
must be present and non-null in the document. This helps
enforce the presence of essential data, ensuring that
documents meet specific criteria.
Ans:
Ans:
JSON Web Tokens (JWT) are a compact, URL-safe
means of representing claims to be transferred between
two parties. In the context of authentication, JWTs are
commonly used to securely transmit information about
the user between the client and the server. Once a user is
authenticated, the server issues a JWT that contains
relevant information (claims) about the user. The client
can then include this token in subsequent requests,
allowing the server to verify the user's identity and grant
access based on the information stored in the JWT.
16. What is the primary purpose of MongoDB's K1 Remember
"sharding" in a deployment?
Ans:
Sharding in MongoDB is a technique used for horizontal
scaling, which involves dividing large amounts of data
across multiple servers or clusters. The primary purpose
of sharding is to distribute the data and workload across
multiple machines, improving performance, and enabling
the system to handle large amounts of data and high
traffic.
PART B (8 QUESTIONS)
Ans:
1.Module Creation:
Example (myModule.js):
// myModule.js
const privateVariable = 'I am private';
module.exports = {
publicFunction,
};
2.Exporting Functionality:
Example (myModule.js):
// myModule.js
const myFunction = () => {
console.log('Hello from my function');
};
module.exports = myFunction;
3.Importing and Using Modules:
To use a module, you use the require function in another file,
Example (app.js):
// app.js
const myFunction = require('./myModule');
Ans:
Package Management:
Example (package.json):
json
Copy code
{
"name": "my-node-project",
"version": "1.0.0",
"description": "A description of my project",
"main": "index.js",
"scripts": {
"start": "node index.js"
},
"dependencies": {
"express": "^4.17.1"
},
"devDependencies": {
"nodemon": "^2.0.12"
},
"keywords": ["node", "npm"],
"author": "Your Name",
"license": "MIT"
}
Dependency Management:
Dependencies are specified in the dependencies or
devDependencies section of the package.json
file.Dependencies include packages required for the
application to run, while devDependencies include
packages needed for development purposes.
Example (package.json):
"dependencies": {
"express": "^4.17.1",
"mongoose": "^6.0.12"
},
"devDependencies": {
"nodemon": "^2.0.12",
"eslint": "^7.32.0"
}
These concepts allow developers to manage project
dependencies efficiently, ensuring consistency across
different environments and simplifying collaboration.
NPM's package.json plays a central role in defining project
configurations and dependencies, providing a standardized
way to structure and share Node.js projects.
3. Explain the key concepts of building RESTful APIs K2 Understand
using Express, focusing on route handling, middleware,
request/response handling, and CRUD operations.
Provide examples to illustrate these concepts.
Ans:
Route Handling:
Example (app.js):
javascript
const express = require('express');
const app = express();
Example (app.js):
javascript
const express = require('express');
const app = express();
// Route handler
app.get('/', (req, res) => {
res.send('Hello, World!');
});
Example (app.js):
javascript
const express = require('express');
const app = express();
Example (app.js):
javascript
const express = require('express');
const app = express();
user.username = username;
user.email = email;
res.json(user);
} else {
res.status(404).json({ message: 'User not found'
}); }
});
Ans:
Callback Functions:
Example (callbackExample.js):
javascript
setTimeout(() => {
callback(data);
}, 1000);
};
fetchData((result) => {
});
Promises:
Example (promiseExample.js):
javascript
setTimeout(() => {
if (success) {
resolve('Async data');
} else {
}, 1000);
});
};
fetchData()
.then((result) => {
})
.catch((error) => {
console.error(error);
});
async/await Syntax:
Example (asyncAwaitExample.js):
javascript
setTimeout(() => {
resolve('Async data');
}, 1000);
});
} catch (error) {
console.error(error);
};
fetchData();
Example (createBook.js):
const mongoose = require('mongoose');
const Book = require('./models/book'); // Assuming a
Mongoose model named 'Book'
Example (readBooks.js):
Example (updateBook.js):
Example (deleteBook.js):
Ans:
Built-in Validators:
Example (userModel.js):
module.exports = User;
Custom Validation Functions:
Example (productModel.js):
javascript
Copy code
const mongoose = require('mongoose');
javascript
Copy code
const mongoose = require('mongoose');
module.exports = User;
Example (postModel.js):
2. Establishing Relationships
Use the ref property to establish a reference between the
Post schema and the User schema.
Example (postModel.js):
// Create users
const user1 = new User({ username: 'user1', email:
'user1@example.com' });
const user2 = new User({ username: 'user2', email:
'user2@example.com' });
// Save users
user1.save();
user2.save();
// Save posts
post1.save();
post2.save();
4. Querying for Related Data:
Retrieve posts along with user details using Mongoose
population.
Example (fetchPosts.js):
javascript
Copy code
const mongoose = require('mongoose');
const Post = require('./postModel');
Ans:
1. User Authentication:
User Registration:
Create a Mongoose model for users, and implement
routes and controllers for user registration.
Example (userModel.js):
module.exports = User;
Example (authController.js):
if (!user) {
return res.status(401).json({ message: 'Invalid
credentials' });
}
module.exports = { loginUser };
Token-based Authentication:
Generate a JWT (JSON Web Token) upon successful login
for secure and stateless authentication.
Example (authMiddleware.js):
try {
const decoded = jwt.verify(token, 'secretKey');
req.userId = decoded.userId;
next();
} catch (error) {
res.status(401).json({ message: 'Unauthorized - Invalid
token' });
}
};
module.exports = { authenticateUser };
2. User Authorization:
Roles and Access Control:
Define roles for users (e.g., 'admin', 'user') and
implement middleware for role-based access control.
Example (authMiddleware.js):
javascript
Copy code
const checkUserRole = (roles) => {
return (req, res, next) => {
if (!roles.includes(req.userRole)) {
return res.status(403).json({ message: 'Forbidden -
Insufficient privileges' });
}
next();
};
};
module.exports = { checkUserRole };
Protecting Routes with Authorization Middleware:
Apply the authorization middleware to routes that require
specific roles.
Example (adminController.js):
javascript
Copy code
const getAdminData = (req, res) => {
res.json({ message: 'Admin data retrieved successfully'
});
};
module.exports = { getAdminData };
Example (routes.js):
javascript
Copy code
const express = require('express');
const authMiddleware =
require('./middlewares/authMiddleware');
const { checkUserRole } =
require('./middlewares/authMiddleware');
const adminController =
require('./controllers/adminController');
module.exports = router;
In this scenario, the provided code examples illustrate the
implementation of user authentication, including user
Ans
1. Server Setup:
Choose Deployment Environment:
use admin
db.createUser({
user: 'adminUser',
pwd: 'adminPassword',
roles: ['userAdminAnyDatabase', 'dbAdminAnyDatabase',
'readWriteAnyDatabase'],
})
Enable Encryption:
Enable SSL/TLS encryption to secure data in
transit. Example (MongoD Configuration):
yaml
Copy code
net:
port: 27017
ssl:
mode: requireSSL
PEMKeyFile: /path/to/mongodb.pem
Implement Network Security:
Configure firewalls and network security groups to
restrict access to MongoDB ports.
3. Monitoring:
Set Up Monitoring Tools:
sh.enableSharding('myDatabase')
sh.shardCollection('myDatabase.myCollection', {
shardKey: 1 })
Vertical Scaling:
javascript
Copy code
db.myCollection.find({ fieldName: 'value'
}).explain('executionStats')
7. Regular Maintenance:
Update MongoDB Version:
Keep MongoDB up-to-date with the latest stable releases
to benefit from bug fixes and improvements.
Example (Upgrade MongoDB Version):
ini
Copy code
/path/to/mongodb/logs/mongodb.log {
daily
rotate 7
compress
missingok
notifempty
}
8. Documentation and Training:
Document Deployment Processes: