0% found this document useful (0 votes)
23 views18 pages

Unit3 4 Notes

This document provides a comprehensive guide for creating a Node.js application for an e-commerce platform and a student management system using MongoDB. It includes step-by-step instructions for setting up the environment, defining schemas, implementing API endpoints, and creating an Angular component for managing student data. The document also covers code explanations and testing procedures for both applications.

Uploaded by

bhuvana19072005
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)
23 views18 pages

Unit3 4 Notes

This document provides a comprehensive guide for creating a Node.js application for an e-commerce platform and a student management system using MongoDB. It includes step-by-step instructions for setting up the environment, defining schemas, implementing API endpoints, and creating an Angular component for managing student data. The document also covers code explanations and testing procedures for both applications.

Uploaded by

bhuvana19072005
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

1. Create a Node.

js application for a simple e-commerce platform connected to


MongoDB.
Step 1: Set up MongoDB and install necessary packages
1. Install MongoDB and start it on your local machine or use MongoDB Atlas for cloud-
based access.
2. Create a new directory for the project.
3. In the terminal, navigate to the project directory and run:
npm init -y
npm install express mongoose body-parser
Step 2: Create the [Link] file (main file)
const express = require("express");
const mongoose = require("mongoose");
const bodyParser = require("body-parser");
const app = express();
[Link]([Link]());
// Connect to MongoDB
[Link]("mongodb://localhost:27017/ecommerce", { useNewUrlParser:
true, useUnifiedTopology: true })
.then(() => [Link]("Connected to MongoDB"))
.catch((err) => [Link]("Error connecting to MongoDB", err));
// Define a Product Schema
const productSchema = new [Link]({
name: String,
price: Number,
description: String
});
// Define the Product Model
const Product = [Link]("Product", productSchema);
// Add a new product
[Link]("/add-product", async (req, res) => {
const product = new Product([Link]);
await [Link]();
[Link]("Product added successfully");
});
// Get all products
[Link]("/products", async (req, res) => {
const products = await [Link]();
[Link](products);
});
// Add item to cart
let cart = [];
[Link]("/add-to-cart", (req, res) => {
const productId = [Link];
[Link](productId);
[Link]("Product added to cart");
});
// View cart items
[Link]("/cart", async (req, res) => {
const cartItems = await [Link]({ _id: { $in: cart } });
[Link](cartItems);
});
// Start the server
[Link](3000, () => {
[Link]("Server is running on [Link]
});
Step 3: Run the Application
1. Start MongoDB on your system.
2. Run the following command in your terminal:
node [Link]

Code Explanation:
const express = require("express");
const mongoose = require("mongoose");
const bodyParser = require("body-parser");
 Purpose: These lines import necessary libraries.
o express: Simplifies handling HTTP requests (like GET and POST).
o mongoose: Connects and interacts with MongoDB, making database work
easier.
o body-parser: Allows us to access data from the client (like form data) in a
simple format.
const app = express();
[Link]([Link]());
 Purpose:
o app: Initializes an Express application, letting us set up routes and handle
requests.
o [Link]([Link]()): Configures the application to automatically
convert JSON-formatted data sent in requests (like product information) so it
can be easily read.
[Link]("mongodb://localhost:27017/ecommerce", { useNewUrlParser:
true, useUnifiedTopology: true })
.then(() => [Link]("Connected to MongoDB"))
.catch((err) => [Link]("Error connecting to MongoDB", err));
 Purpose: Connects to a MongoDB database.
o "mongodb://localhost:27017/ecommerce": Connection string for MongoDB.
localhost:27017 is the default address for MongoDB on a local machine, and
ecommerce is the database name.
o { useNewUrlParser: true, useUnifiedTopology: true }: Options that ensure a
stable and modern connection.
o .then(): Runs if the connection is successful, logging "Connected to
MongoDB."
o .catch(): Catches and logs errors if the connection fails.
const productSchema = new [Link]({
name: String,
price: Number,
description: String
});
 Purpose: Defines a schema (template) for a Product.
o name, price, and description: Fields that each product should have, with their
data types (String for text, Number for numerical values).
o Schemas ensure each product follows a consistent format, making it easier to
work with data in MongoDB.
const Product = [Link]("Product", productSchema);
 Purpose: Creates a model (Product) based on productSchema.
o Models act as a bridge between the application and the MongoDB database,
allowing us to perform actions like adding or retrieving products easily.
[Link]("/add-product", async (req, res) => {
const product = new Product([Link]);
await [Link]();
[Link]("Product added successfully");
});
 Purpose: Defines an API endpoint to add a new product.
o [Link]("/add-product"): Sets up a route that listens for POST requests to
/add-product.
o [Link]: Holds the data sent by the client (like product details).
o new Product([Link]): Creates a new product with the data received.
o await [Link](): Saves the product to MongoDB.
o [Link](): Sends a response back to the client confirming the addition.
[Link]("/products", async (req, res) => {
const products = await [Link]();
[Link](products);
});
 Purpose: Defines an API endpoint to view all products.
o [Link]("/products"): Sets up a route for GET requests to /products.
o [Link](): Fetches all products from MongoDB.
o [Link](products): Sends all products back to the client as a response.
let cart = [];
 Purpose: Creates a simple cart to store product IDs.
o let cart = [];: Initializes an empty array to store items a user wants to add to the
cart. This example does not save cart data in MongoDB for simplicity.
javascript
Copy code
[Link]("/add-to-cart", (req, res) => {
const productId = [Link];
[Link](productId);
[Link]("Product added to cart");
});
 Purpose: Defines an API endpoint to add items to the cart.
o [Link]("/add-to-cart"): Sets up a route that listens for POST requests to /add-
to-cart.
o [Link]: Extracts the product ID from the client’s request.
o [Link](productId): Adds the product ID to the cart array.
o [Link](): Confirms that the product has been added to the cart.
[Link]("/cart", async (req, res) => {
const cartItems = await [Link]({ _id: { $in: cart } });
[Link](cartItems);
});
 Purpose: Defines an API endpoint to view items in the cart.
o [Link]("/cart"): Sets up a route that listens for GET requests to /cart.
o [Link]({ _id: { $in: cart } }): Finds all products in MongoDB whose _id
is in the cart array.
o [Link](cartItems): Sends the list of cart items back to the client.
[Link](3000, () => {
[Link]("Server is running on [Link]
});
 Purpose: Starts the server and makes it accessible at a specified port.
o [Link](3000): Starts the server on port 3000.
o [Link]("Server is running..."): Logs a message confirming the server is up
and running.

Create a [Link] application to manage a student database for an university using


MongoDB. Define schemas for students, including fields for name, age, class and
subjects. Implement endpoints to register new students, update student information,
retrieve student details and delete student records.

Step 1: Set up MongoDB and install necessary packages


1. Make sure MongoDB is installed and running on your machine or use MongoDB
Atlas.
2. In a new project directory, initialize npm and install necessary packages:
npm init -y
npm install express mongoose body-parser
Step 2: Create the [Link] file
const express = require("express");
const mongoose = require("mongoose");
const bodyParser = require("body-parser");
const app = express();
[Link]([Link]());
// Connect to MongoDB
[Link]("mongodb://localhost:27017/universityDB", { useNewUrlParser:
true, useUnifiedTopology: true })
.then(() => [Link]("Connected to MongoDB"))
.catch((err) => [Link]("Error connecting to MongoDB", err));
// Define the Student Schema
const studentSchema = new [Link]({
name: String,
age: Number,
class: String,
subjects: [String]
});
// Define the Student Model
const Student = [Link]("Student", studentSchema);
// Register a new student
[Link]("/register", async (req, res) => {
const student = new Student([Link]);
await [Link]();
[Link]("Student registered successfully");
});
// Retrieve student details
[Link]("/students/:id", async (req, res) => {
try {
const student = await [Link]([Link]);
if (student) {
[Link](student);
} else {
[Link](404).send("Student not found");
}
} catch (error) {
[Link](400).send("Invalid student ID");
}
});
// Update student information
[Link]("/students/:id", async (req, res) => {
try {
const student = await [Link]([Link], [Link], { new:
true });
if (student) {
[Link]("Student information updated");
} else {
[Link](404).send("Student not found");
}
} catch (error) {
[Link](400).send("Invalid student ID");
}
});
// Delete a student record
[Link]("/students/:id", async (req, res) => {
try {
const student = await [Link]([Link]);
if (student) {
[Link]("Student record deleted");
} else {
[Link](404).send("Student not found");
}
} catch (error) {
[Link](400).send("Invalid student ID");
}
});
// Start the server
[Link](3000, () => {
[Link]("Server is running on [Link]
});
Code Explanation
1. Student Schema: Defines a template for student data with fields for name, age, class,
and an array of subjects.
2. Register Endpoint (/register): Accepts student data in JSON format and saves it to
the database.
3. Retrieve Endpoint (/students/:id): Finds a student by their unique ID and returns
their details.
4. Update Endpoint (/students/:id): Updates student data based on the ID and provided
information.
5. Delete Endpoint (/students/:id): Deletes a student record by ID.
Testing the Application
1. Start MongoDB on your system.
2. Run the application with:
node [Link]
3. Use tools like Postman to test each endpoint:
o Register a new student: Send a POST request to [Link]
with JSON data:
json
Copy code
{
"name": "John Doe",
"age": 20,
"class": "Computer Science",
"subjects": ["Math", "Physics", "Computer Science"]
}
o Retrieve student details: Send a GET request to
[Link]
o Update student information: Send a PUT request to
[Link] with updated JSON data.
o Delete a student: Send a DELETE request to
[Link]

Create a typescript class for student with properties for name, age and grade. Implement an
angular component that maintains a list of students. Use ngFor method to display the list of
students. Implement a form to add new students to the list using two-way data binding.
Step 1: Create the Student TypeScript Class
1. Create a file [Link] in your Angular project.
// [Link]
export class Student {
constructor(
public name: string,
public age: number,
public grade: string
) {}
}
This Student class has three properties: name, age, and grade, all of which are set in the
constructor when creating a new Student object.
Step 2: Create the Angular Component
1. Generate a new component using Angular CLI:
ng generate component student-list
2. Inside the [Link] file, define an array of Student objects and
methods to add new students.
// [Link]
import { Component } from '@angular/core';
import { Student } from '../[Link]';
@Component({
selector: 'app-student-list',
templateUrl: './[Link]',
styleUrls: ['./[Link]']
})
export class StudentListComponent {
students: Student[] = [
new Student('Alice', 20, 'A'),
new Student('Bob', 21, 'B'),
new Student('Charlie', 22, 'C')
];
// Model for the new student form
newStudent: Student = new Student('', 0, '');
// Method to add a new student to the list
addStudent() {
[Link](new Student([Link], [Link],
[Link]));
// Reset the form after adding the student
[Link] = new Student('', 0, '');
}
}
Step 3: Create the Template for Displaying the Student List and Adding New Students
1. In the [Link] file, use *ngFor to display the list of students
and create a form for adding new students.
<!-- [Link] -->
<div>
<h2>Student List</h2>
<ul>
<li *ngFor="let student of students">
Name: {{ [Link] }}, Age: {{ [Link] }}, Grade: {{ [Link] }}
</li>
</ul>
<h3>Add New Student</h3>
<form (ngSubmit)="addStudent()">
<label for="name">Name:</label>
<input type="text" id="name" [(ngModel)]="[Link]" name="name"
required />
<label for="age">Age:</label>
<input type="number" id="age" [(ngModel)]="[Link]" name="age"
required />
<label for="grade">Grade:</label>
<input type="text" id="grade" [(ngModel)]="[Link]" name="grade"
required />

<button type="submit">Add Student</button>


</form>
</div>
Step 4: Import FormsModule for Two-Way Binding
To enable two-way binding in the form, ensure FormsModule is imported in your
Angular module.
1. Open [Link] and add FormsModule to the imports array.
// [Link]
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms'; // Import FormsModule
import { AppComponent } from './[Link]';
import { StudentListComponent } from './student-list/[Link]';
@NgModule({
declarations: [
AppComponent,
StudentListComponent
],
imports: [
BrowserModule,
FormsModule // Add FormsModule here
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
Explanation of the Code
1. Student Class: This defines the structure of a Student object with properties name,
age, and grade.
2. StudentListComponent:
o students: An array of Student objects that holds the current list of students.
o newStudent: An instance of Student used as a model for the form. Initially,
it’s an empty student.
o addStudent(): A method that adds newStudent to the students array and
resets the newStudent model to empty values.
3. Template (HTML):
o The *ngFor directive loops over students and displays each student’s
details.
o The form uses [(ngModel)] for two-way data binding, allowing changes in
the form fields to update newStudent.
o The ngSubmit directive calls addStudent() when the form is submitted.
Step 5: Run the Application
Start your Angular application:
ng serve

Create a [Link] application to perform basic CRUD operations on a MongoDB


collection of user profiles.

// [Link]
const mongoose = require("mongoose");
const userSchema = new [Link]({
name: { type: String, required: true },
age: { type: Number, required: true },
email: { type: String, required: true, unique: true },
});
const User = [Link]("User", userSchema);
[Link] = User;

// [Link]
const express = require("express");
const mongoose = require("mongoose");
const bodyParser = require("body-parser");
const User = require("./[Link]");
const app = express();
[Link]([Link]());
// Connect to MongoDB
[Link]("mongodb://localhost:27017/userDB", { useNewUrlParser: true,
useUnifiedTopology: true })
.then(() => [Link]("Connected to MongoDB"))
.catch((error) => [Link]("Failed to connect to MongoDB", error));
// Create a new user
[Link]("/users", async (req, res) => {
try {
const newUser = new User([Link]);
await [Link]();
[Link](201).send("User created successfully");
} catch (error) {
[Link](400).send([Link]);
}
});
// Read all users
[Link]("/users", async (req, res) => {
try {
const users = await [Link]();
[Link](users);
} catch (error) {
[Link](500).send([Link]);
}
});
// Read a single user by ID
[Link]("/users/:id", async (req, res) => {
try {
const user = await [Link]([Link]);
if (!user) return [Link](404).send("User not found");
[Link](user);
} catch (error) {
[Link](400).send("Invalid user ID");
}
});
// Update a user by ID
[Link]("/users/:id", async (req, res) => {
try {
const user = await [Link]([Link], [Link], { new: true });
if (!user) return [Link](404).send("User not found");
[Link]("User updated successfully");
} catch (error) {
[Link](400).send("Invalid user ID");
}
});
// Delete a user by ID
[Link]("/users/:id", async (req, res) => {
try {
const user = await [Link]([Link]);
if (!user) return [Link](404).send("User not found");
[Link]("User deleted successfully");
} catch (error) {
[Link](400).send("Invalid user ID");
}
});
// Start the server
[Link](3000, () => {
[Link]("Server is running on [Link]
});

Create a dynamic form component that allows users to enter their personal information. The
form should include fields for name, email and phone number. Use data binding and form
directives to handle user input. Display an error message conditionally using ‘ngIf’ when the
form fields are invalid.

Step 1: Set Up the Angular Form Component


1. Generate a new component in your Angular project:
ng generate component user-form
2. In the generated [Link], import FormBuilder, FormGroup, and
Validators from @angular/forms to create a reactive form with validation.
// [Link]
import { Component } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';

@Component({
selector: 'app-user-form',
templateUrl: './[Link]',
styleUrls: ['./[Link]']
})
export class UserFormComponent {
userForm: FormGroup;
constructor(private formBuilder: FormBuilder) {
[Link] = [Link]({
name: ['', [[Link], [Link](3)]],
email: ['', [[Link], [Link]]],
phone: ['', [[Link], [Link]('^\\d{10}$')]]
});
}
// Method to check if a form control is invalid and touched
isFieldInvalid(field: string): boolean {
return (
[Link](field)?.invalid &&
([Link](field)?.dirty || [Link](field)?.touched)
);
}
// Submit method for the form
onSubmit(): void {
if ([Link]) {
[Link]('Form submitted successfully', [Link]);
[Link](); // Reset the form after submission
} else {
[Link]('Form is invalid');
}
}
}
Step 2: Create the Form Template
1. In the [Link] file, create the form layout with fields for name,
email, and phone number.
2. Use ngIf to conditionally display error messages when form fields are invalid.
<!-- [Link] -->
<div>
<h2>User Information Form</h2>
<form [formGroup]="userForm" (ngSubmit)="onSubmit()">
<!-- Name Field -->
<div>
<label for="name">Name:</label>
<input id="name" formControlName="name" type="text" />
<div *ngIf="isFieldInvalid('name')" class="error">
Name is required and must be at least 3 characters long.
</div>
</div>
<!-- Email Field -->
<div>
<label for="email">Email:</label>
<input id="email" formControlName="email" type="email" />
<div *ngIf="isFieldInvalid('email')" class="error">
Enter a valid email address.
</div>
</div>
<!-- Phone Field -->
<div>
<label for="phone">Phone Number:</label>
<input id="phone" formControlName="phone" type="text" />
<div *ngIf="isFieldInvalid('phone')" class="error">
Phone number must be 10 digits.
</div>
</div>
<button type="submit" [disabled]="[Link]">Submit</button>
</form>
</div>
Step 3: Add Basic Styles for Error Messages
1. Open [Link] and style the error messages for better visibility.
/* [Link] */
.error {
color: red;
font-size: 0.9em;
}
Step 4: Import ReactiveFormsModule in the App Module
Ensure that ReactiveFormsModule is imported in [Link] for using reactive forms.
// [Link]
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { ReactiveFormsModule } from '@angular/forms';
import { AppComponent } from './[Link]';
import { UserFormComponent } from './user-form/[Link]';
@NgModule({
declarations: [
AppComponent,
UserFormComponent
],
imports: [
BrowserModule,
ReactiveFormsModule // Import ReactiveFormsModule here
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }

You might also like