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

unit 1

Routing in web applications defines how endpoints respond to client requests, using methods like Application Instance and Router class in Express. Route handlers are functions that process requests and send responses, utilizing request and response objects. Mongoose is an ODM library for MongoDB that enforces data structure, provides automatic type casting, validation, and simplifies database operations, while session management techniques like cookies and session stores help maintain user state across requests.

Uploaded by

Navya
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

unit 1

Routing in web applications defines how endpoints respond to client requests, using methods like Application Instance and Router class in Express. Route handlers are functions that process requests and send responses, utilizing request and response objects. Mongoose is an ODM library for MongoDB that enforces data structure, provides automatic type casting, validation, and simplifies database operations, while session management techniques like cookies and session stores help maintain user state across requests.

Uploaded by

Navya
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 7

1.a) Define routing.

List various routing methods

Defining the endpoints of an application and the way the application responds to the incoming client
requests are referred to as routing. A route is nothing but a mixture of a URI, HTTP request method,
and some handlers for that particular path.

Routing can be defined using two ways

 Application Instance

 Router class of Express

Application Instance (Method 1): Routes are defined directly on the app object using methods like
app.get(), app.post(), etc. It's simple and straightforward but can become less manageable in large
applications.

Router Class (Method 2): Routes are grouped together in a modular Router instance. This makes it
easier to organize and maintain routes for different sections of the application. It also allows you to
reuse route modules across different parts of your application.
1. b) Explain about handling routes.
Handling Routes: Route handler can be defined as functions that get executed every time the
server receives a request for a particular URL path and HTTP method.

The route handler function needs at least two parameters:

request object and response object.

 Request object The HTTP request object is created when a client makes a request to the
server. The variable named req is used to represent this object.
 The request object in Express provides many properties and methods to access the
request related information sent by the client to the server.

commonly used methods of the request object :

Response object
The HTTP response object has information about the response sent from the server to
the client.
 The response object is created along with the request object and is commonly
represented by a variable named res.
 The route handler function sends a response using res.send() method whenever a GET
request is received.
res.send('About us page');
 The response object in Express also supports many methods for sending different types of
responses.
commonly used methods of the response object:

2. Write about introduction to mongoose and explain the need of


mongoose.
Mongoose is an Object Data Modeling (ODM) library for MongoDB and Node.js. It provides a
structure for MongoDB collections, offering an easy way to interact with the database by using
JavaScript objects. Mongoose is designed to work in an asynchronous MongoDB environment,
allowing developers to model data, perform validations, and handle database operations like
querying, adding, modifying, and deleting documents with ease.

Why Do We Need Mongoose?

1. Data Structure Enforcement:

o MongoDB is schema-less by default, which can lead to inconsistent or unstructured


data. Mongoose imposes a schema, ensuring data integrity by defining structure and
constraints for the data stored in MongoDB collections.

2. Automatic Data Type Casting:

o Mongoose automatically type-casts data according to the schema. If data does not
match the defined schema types, Mongoose handles the casting or rejects the data,
ensuring consistency.

3. Data Validation:

o Mongoose provides built-in validation mechanisms to ensure data integrity before


data is saved to the database. You can specify validation rules for each field, ensuring
that only valid data is persisted in your collections.

4. Middleware Support:
o Mongoose allows the use of pre and post hooks (middleware) to run functions
before or after certain actions (e.g., saving, updating). This helps to integrate
additional logic in the application lifecycle.

5. Simplified Database Operations:

o With Mongoose, database operations such as creating, querying, updating, and


deleting documents become easier to manage through the use of schemas and
models.

Common Terminologies in Mongoose

1. Schema:

o The schema defines the structure of the document. It is essentially a blueprint that
describes the fields in the document, their types, and validation rules.

o Example:

const empSchema = new mongoose.Schema({

empId: Number,

empName: String,

address: {

doorNo: String,

lane: String,

pincode: Number

});

2. Model:

o A model in Mongoose is a wrapper around a schema. It provides an interface to


interact with MongoDB and performs CRUD operations (Create, Read, Update,
Delete) on the documents in the collection.

o Example:

const Employee = mongoose.model('Employee', empSchema);

3. Data Validation & Types:

o Mongoose supports a variety of data types (e.g., String, Number) and validation
rules (e.g., required, min, max).

o Example of adding validation:

const schema = mongoose.Schema({

name: {
type: String,

required: true

},

age: {

type: Number,

min: 18

}};

4. Default Values:

o You can set default values for fields in the schema, which will be applied when the
field is not provided during document creation.

o Example:

const schema = mongoose.Schema({

status: { type: String, default: "active" }

});

5. Custom Validators:

o Mongoose allows you to define custom validation rules for fields if built-in validators
are insufficient.

o Example:

const schema = mongoose.Schema({

email: {

type: String,

validate: {

validator: function(v) {

return /.+@.+\..+/.test(v);

},

message: props => `${props.value} is not a valid email!`

});
10. What are sessions. Explain about session management techniques cookies and session store

 A session is a way to store information (in variables) to be used across multiple pages
(requests) of a web application.

 It helps identify the same user between requests.

 Sessions typically store user login details, cart items, or any data that should persist during a
visit.

Session Management Techniques

Session Management is a technique used by the webserver to store a particular user's session
information. The Express framework provides a consistent interface to work with the session-related
data. The framework provides two ways of implementing sessions:  By using cookies  By using the
session store

(i) Cookies:

 A cookie is a small piece of data stored on the client-side (browser).

 It is sent back and forth with every request/response between client and server.

 Cookies can store user ID, session token, etc.

Types:

 Session Cookies: Deleted when the browser is closed.

 Persistent Cookies: Stored until a set expiration date.

Advantages:

 Lightweight

 Easy to implement

Limitations:

 Can be modified by users

 Size limit (~4KB)

(ii) Session Store:

 Session data is stored on the server-side.

 The client gets a session ID stored in a cookie, and the server maps that ID to the session
data.
 A session store can be used to store the session data in the back-end.

 Using this approach, a large amount of data can be stored, and also the data will be hidden
from the user, unlike a cookie.

 Configuration: Express provides a middleware called express-session for storing session


data on the server-side.

Session Store Types:

 In-Memory (like MemoryStore) – for dev/testing

 File-based

 Database-backed (MongoDB, Redis) – for production

Example using express-session:

const session = require('express-session');

app.use(session({

secret: 'yourSecret',

resave: false,

saveUninitialized: true

}));

Advantages:

 More secure (data not exposed to client)

 Can store more data than cookies

Feature Cookies Session Store

Stored at Client-side (browser) Server-side

Security Less secure More secure

Size limit ~4 KB No practical limit

Data access Accessible by client Accessible only by server

Usage Small, simple data Login state, sensitive data

You might also like