0% found this document useful (0 votes)
15 views65 pages

Mean Stack Technology Lab

The MEAN Stack consists of MongoDB, Express.js, Angular, and Node.js, which together enable the development of web applications using JavaScript throughout the stack. Angular is a framework for building dynamic single-page applications, offering features like custom components, data binding, and dependency injection. The document also covers Angular's forms, dependency injection, HTTP data retrieval, and routing basics, providing a comprehensive overview of Angular development practices.

Uploaded by

payakulatarun
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)
15 views65 pages

Mean Stack Technology Lab

The MEAN Stack consists of MongoDB, Express.js, Angular, and Node.js, which together enable the development of web applications using JavaScript throughout the stack. Angular is a framework for building dynamic single-page applications, offering features like custom components, data binding, and dependency injection. The document also covers Angular's forms, dependency injection, HTTP data retrieval, and routing basics, providing a comprehensive overview of Angular development practices.

Uploaded by

payakulatarun
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/ 65

MEAN STACK TECHNOLOGY LAB

MEAN Stack

Mean stack stands for Mongo DB, Express JS, Angular, and Node JS. It is a set of these technologies
that are used to develop each end of a web application. Further details about these technologies are
given as follows:

 Mongo DB : Its a database which is using BSON format to store data.

 Express JS : Its a framework of JavaScript which enables developer to establish server.

 Angular : Angular is client side framework which is used to develop User Interface.

 Node JS :Node JS is a run time environment of JavaScript which allows developer to execute
JS code directly in console

Working of MEAN Stack:

Angular handles the implementation of the user interface (UI). Whenever the UI requires data, it
sends a request to the server, prompting the server to retrieve the necessary information from
MongoDB. Once the server successfully locates the required data, it sends the response back to the
client side.

Advantages of MEAN Stack:

 Whole technologies requires only JavaScript to implement programs.

 Improved re-usability of code.

 Easy to learn.
1.ANGULAR INTRODUCTION
Angular: Angular is an open-source web application framework maintained by
Google and a community of developers. It is designed to build dynamic and
interactive single-page applications (SPAs) efficiently. With Angular, developers
can create robust, scalable, and maintainable web applications.
History:
Angular, initially released in 2010 by Google, has undergone significant
transformations over the years. The first version, AngularJS, introduced
concepts like two-way data binding and directives. However, as web
development evolved, AngularJS faced limitations in terms of performance and
flexibility.
Prerequisites:
 TypeScript
 HTML
 CSS
 JavaScript
Why Angular?
JavaScript is the most commonly used client-side scripting
language. It is written into HTML documents to enable
interactions with web pages in many unique ways.

Here are some of the features of Angular


1. Custom Components
Angular enables users to build their components that can pack functionality
along with rendering logic into reusable pieces.
2. Data Binding
Angular enables users to effortlessly move data from JavaScript code to the
view, and react to user events without having to write any code manually.
3. Dependency Injection
Angular enables users to write modular services and inject them wherever they
are needed. This improves the testability and reusability of the same services.
4. Testing
Tests are first-class tools, and Angular has been built from the ground up with
testability in mind. You will have the ability to test every part of your
application—which is highly recommended.
5. Comprehensive
Angular is a full-fledged JavaScript framework and provides out-of-the-box
solutions for server communication, routing within your application, and more.
6. Browser Compatibility
Angular works cross-platform and compatible with multiple browsers. An
Angular application can typically run on all browsers (Eg: Chrome, Firefox) and
operating systems, such as Windows, macOS, and Linux.

2. GETTING STRATED WITH ANGULAR


Step 1: Download the NodeJS
Downloading the Node.js ‘.msi’ installer the first step to install Node.js on
Windows is to download the installer. Visit the official Node.js website
i.e) https://nodejs.org/en/download/
Creating an Angular Application
Step 1: Install Angular CLI: Angular CLI (Command Line Interface) is a
powerful tool for scaffolding and managing Angular applications. Install it
globally using npm:
npm install -g @angular/cli

Step 2: Create a New Angular Project: Use Angular CLI to create a new Angular
project. Navigate to the desired directory and run:
ng new my-angular-app
Step 3: Navigate to the Project Directory: Move into the newly created project
directory:
Folder Structure:
cd my-angular-app
Step 4: Serve the Application: Launch the development server to see your app
in action:
ng serve

OUTPUT :
3.INTRODUCTION TO COMPONENTS
Angular components are the building blocks of a UI in an Angular application.
These components are associated with a template and are a subset of
directives. The above image shows the classification tree structure. A root
component, the App Component, branches out into other components,
creating a hierarchy.
Creating a Component in Angular 10:
To create a component in any angular application, follow the below steps:
 Get to the angular app via your terminal.
 Create a component using the following command:
 ng g c <component_name>
 OR
 ng generate component <component_name>
Using a component in Angular :
 Go to the component.html file and write the necessary HTML code.
 Go to the component.css file and write the necessary CSS code.
 Write the corresponding code in component.ts file.
 Run the Angular app using ng serve –open

OUTPUT :
4. TEMPLATES ,INTERPOLATION ,AND DIRECTIVES
A) TEMPLATES: Introduction to components and templates
A component controls a patch of screen called a view. It consists of a TypeScript
class, an HTML template, and a CSS style sheet. The TypeScript class defines
the interaction of the HTML template and the rendered DOM structure, while
the style sheet describes its appearance.

OUTPUT :
B)INTERPOLATION:
Interpolation is a way to transfer the data from a TypeScript code to an HTML
template (view), i.e. it is a method by which we can put an expression in
between some text and get the value of that expression. Interpolation basically
binds the text with the expression value
Syntax: {{expression}}
STEP1: manu.component.html

Manu.component.ts
OUTPUT :

C)DIRECTIVES:
Directives are markers in the Document Object Model(DOM). Directives can be
used with any controller or HTML tag which will tell the compiler what exact
operation or behaviour is expected. There are some directives present that are
predefined but if a developer wants he can create new directives (custom-
directive).
1. Component Directives
2. Attribute Directives(ngClass ,ngStyle ,ngModel)
3. Structural Directives(ngIf,ngSwitch,ngFor)
1.Component Directives :
Example:

2.Structural Directives:
i)ngFor:
Component2.component.ts :

Component2.component.html :
Component2.component.css:

OUTPUT :
ii)ngIf :
app.component.ts :

App.component.html:
OUTPUT :

iii)ngIf-else :
component1.component.ts :
Component1.component.html :

OUTPUT :
iv)ngSwitch :
component1.component.ts :
Component1.component.html :

OUTPUT :

3.Attribute Directives :
ngClass and ngStyle :
component2.component.ts :
Component2.component.html :

OUTPUT :

5. DATA BINDING & PIPES


A) DATA BINDING:
Data binding is the process that establishes a connection between the
app UI and the data it displays. If the binding has the correct settings and
the data provides the proper notifications, when the data changes its
value, the elements that are bound to the data reflect changes
automatically.

Types of Data Binding in Angular


1)One-Way Data Binding.
Interpolation.
Property Binding.
Event Binding.
2)Two-Way Data Binding.( Property Binding + Event Binding)
Property Binding:
Property binding is used to bind a property of an element t a component
property.It allows you to set the Dom properties dynamically.
SYNTAX : [elementProperty]=”ComponentProperty”
Event Binding:
It allows you to bind events (sUch as click,input,keyup)to methods in the
component class. This way you can handle user interactions in the view.
SYNTAX : (elementEvent)=”ComponentMethod()”
Example:
.ts :

.html :

OUTPUT :
B)PIPES: The pipe() function in Angular is used to chain multiple operators
together to transform data. It receives an input value works on it and gives
back a modified result. You can recognize pipes in your template expressions by
the pipe symbol ( | ).
1. Built-in Pipes
Angular comes equipped with built in pipes that handle a variety of common
formatting duties.
<p>Today's date: {{ today | date:'mediumDate' }}</p>
 DatePipe-The DatePipe is utilized for date formatting. It enables us to
present dates, in styles like short, medium and full. For example we can
utilize to exhibit the form of the date.
{{ myDate | date: "short" }}
 UpperCasePipe - This tool changes a text to capital letters. It requires a
text, as input. Gives back the text in all capital letters.
{{ myString | uppercase }}
 LowerCasePipe - This particular pipe is utilized for changing a string to
lowercase. Its functionality resembles that of the UpperCasePipe except
it changes the string to lowercase instead.
{{ myString | lowercase }}
 CurrencyPipe - This tool helps to convert numbers into currency values.
You input a number. It gives back a string showing the number, in the
desired currency format.
{{ myNumber | currency: "USD" }}
App.component.html :

App.component.ts :

2.Customized Pipes:
Creating custom pipes in angularis useful when you need to apply custom
data transformations that aren’t covered by the built-in pipes .
i)Reverse String Pipe :
reverse.pipe.ts :
export class ReversePipe implements PipeTransform{
transform(value:string):string{
return value.split(‘’).reverse().join(‘ ‘);
}}
App.component.html :
<p> {{‘Angular’ |reverse}}</p>
ii)Mask String Pipe :
mask.pipe.ts :
export class MaskPipe implements PipeTransform{
transform(value :string,visibleDigits:number):string{
const masked =value.slice(0,-visibleDigits).replace(/./g,’*’);
const masked +visible;
}}
App.component.html:
<p>{{‘12345678123456778’ | mask:4}}</p>

OUTPUT :
6.MORE ON COMPONENTS
In Angular,communication between parent and child components can be
achieved using different methods,depending on the direction of
communication.
Create two components name them as parent component and child
component.
1)Communication from Parent to Child:
parent.component.ts
Convert ParentComponent to a standalone component:
import { Component } from '@angular/core';
import { CommonModule } from '@angular/common';
import { ChildComponent } from '../child/child.component';

@Component({
selector: 'app-parent',
standalone: true,
imports: [CommonModule, ChildComponent], // Import ChildComponent
templateUrl: './parent.component.html',
styleUrls: ['./parent.component.css']
})
export class ParentComponent {
parentMessage: string = 'Hello from Parent Of Neelima Hima Bindu';
message: string = '';

receiveMessage(message: string) {
this.message = message;
}
}
parent.component.html
<app-child [rakiBhai]="parentMessage"
(messageEmitter)="receiveMessage($event)"></app-child>
<p>{{ message }}</p>
child.component.ts
import { Component, Input, Output, EventEmitter } from '@angular/core';
@Component({
selector: 'app-child',
standalone: true,
templateUrl: './child.component.html',
styleUrls: ['./child.component.css']
})
export class ChildComponent {
@Input() rakiBhai: string = '';
@Output() messageEmitter = new EventEmitter<string>();

sendMessage() {
this.messageEmitter.emit('Neelima Hima Bindu from Child!');
}
}
child.component.html
<h2>{{ binnu }}</h2>
<button (click)="sendMessage()">Send Message to Parent</button>
2)Communication from Child to Parent:
To send data from the child component to the parent component,Angular
uses @Output() along with EventEmitter.
Child.component.ts :
Export class ChildComponent{
@Input() fromparent:string=”;
@Output() messageEvent=new EventEmitter<string>();
sendMessage()
{
this.messageEvent.emit(“this is from child”);
}}
Child.component.html :
<p>child works!</p>
<h1>{{fromparent}}</h1>
<button (click)=”SendMessage()”>click me</button>
Parent.component.ts :
export class ParentComponent{
parentmsg:string=”hi csd from parent”:
message:string=’ ‘;
receiveMessage(message:string){
this.message=message;
}}
Parent.component.html :
<p>parent works !</p>
<app-child
(messageEvent)=”receiveMessage($event)”[fromparent]=”parentmsg”></app-
child>
<h2>{{message}}</h2>
OUTPUT :

8.ANGULAR FORMS
Forms:
 Angular provides two approaches for handling forms: Template-driven
forms and Reactive forms. Both approaches offer powerful validation
and custom control support.
OUTPUT :
Reactive forms:
OUTPUT :
9.DEPENDENCY INJECTION(DI)
Services
Services are classes that provide reusable functionality and can be injected
into other components, directives, or services.
Dependency Injection (DI) is the mechanism Angular uses to inject instances of
services into components or other services automatically.
Steps:
1. Create a Service.
2. Inject the Service into a Component using Angular's DI system.
ng generate service auto

First we have to import Service in App.Component.ts


import { AutoService } from './auto.service';
OUTPUT :
10. Retrieving Data Using HTTP
Retrieving Data Using HTTP, Navigation, and Routing are fundamental parts of
creating dynamic and interactive web applications. These concepts are widely
used in frameworks like Angular, React, and Vue, but let’s focus on Angular for
this explanation
hen developing a web application, it’s common to need data from a backend
server or an external API. Angular provides a built-in service called HttpClient
to make HTTP requests like GET, POST, PUT, and DELETE.
Here’s how you can retrieve data from an API using Angular’s HttpClient:
a. Set Up HTTP Client
1. Import the HttpClientModule: First, ensure that the HttpClientModule is
imported in your Angular app module (app.module.ts).
import { HttpClientModule } from '@angular/common/http';

@NgModule({
declarations: [AppComponent],
imports: [HttpClientModule],
bootstrap: [AppComponent]
})
export class AppModule {}
Inject HttpClient: In the service or component where you want to fetch data,
inject HttpClient and use it to make HTTP requests.
b. Making a GET Request
Here’s an example of a simple service that fetches data from an API using a GET
request.
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class DataService {

private apiUrl = 'https://jsonplaceholder.typicode.com/posts'; // Example API

constructor(private http: HttpClient) { }

// Method to retrieve data from the API


getPosts(): Observable<any> {
return this.http.get(this.apiUrl);
}
}
 http.get(): Makes an HTTP GET request to the provided URL.
 Observable: HttpClient returns an Observable that will emit the result
once the data is fetched.
c. Subscribing to the Observable
In your component, subscribe to the Observable returned by the service to get
the data:
import { Component, OnInit } from '@angular/core';
import { DataService } from './data.service';

@Component({
selector: 'app-root',
template: `<ul><li *ngFor="let post of posts">{{ post.title }}</li></ul>`
})
export class AppComponent implements OnInit {
posts: any[] = [];

constructor(private dataService: DataService) {}

ngOnInit(): void {
// Subscribe to the observable to fetch data
this.dataService.getPosts().subscribe((data) => {
this.posts = data;
});
}
}
2. Navigation and Routing Basics
Angular provides Routing for navigation between different views in your
application. With routing, you can navigate between different components
based on the URL.
a. Setting Up Routing
To use routing in Angular:
1. Import RouterModule: You need to configure the routes in the app-
routing.module.ts.
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { HomeComponent } from './home/home.component';
import { PostComponent } from './post/post.component';

const routes: Routes = [


{ path: '', component: HomeComponent }, // Home route
{ path: 'post/:id', component: PostComponent }, // Dynamic route with
parameter
];

@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule {}
 The HomeComponent will be displayed when the user navigates to the
root (/).
 The PostComponent will display when the user visits /post/:id, where id
is a dynamic parameter (e.g., /post/1)
2. Using RouterLink for Navigation: Use routerLink in your template to
navigate between components.
<!-- In a component template -->
<a routerLink="/post/1">Go to Post 1</a>
b. Using the ActivatedRoute to Retrieve Route Parameters
To retrieve the dynamic parameter (id) from the route, use ActivatedRoute in
your component.
import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';

@Component({
selector: 'app-post',
template: `<h2>Post ID: {{ postId }}</h2>`
})
export class PostComponent implements OnInit {
postId: number;

constructor(private route: ActivatedRoute) {}

ngOnInit(): void {
// Retrieve the route parameter using ActivatedRoute
this.route.paramMap.subscribe(params => {
this.postId = +params.get('id'); // Get 'id' as a number
});
}
}
c. Navigating Programmatically with Router
You can also navigate programmatically in your component using Angular’s
Router.
import { Component } from '@angular/core';
import { Router } from '@angular/router';

@Component({
selector: 'app-home',
template: `<button (click)="goToPost()">Go to Post 1</button>`
})
export class HomeComponent {

constructor(private router: Router) {}

goToPost() {
this.router.navigate(['/post', 1]); // Navigate to /post/1
}
}
3. Handling Navigation Events
You can listen to route changes and take action based on the navigation
lifecycle using Router.events.
import { Component, OnInit } from '@angular/core';
import { Router, NavigationStart } from '@angular/router';

@Component({
selector: 'app-root',
template: `<h1>App</h1>`
})
export class AppComponent implements OnInit {

constructor(private router: Router) {}

ngOnInit(): void {
// Subscribe to router events
this.router.events.subscribe(event => {
if (event instanceof NavigationStart) {
console.log('Navigation started:', event.url);
}
});
}
}
11. NODEJS INTRODUCTION
Express.js (Framework for Node.js):
o While Node.js itself is just a runtime, you’ll often use frameworks like
Express.js to simplify building web applications. Express makes routing,
middleware, and request handling more straightforward.
Example with Express.js
Express.js is a minimal web framework that runs on top of Node.js, simplifying
web server development.
1. Install Express:
o First, you’ll need to initialize a Node.js project by running npm init in
your project folder.
o
Then, install Express:
npm install express
Create a basic Express server: const express = require('express'); const app =
express();

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


});

app.listen(3000, () => { console.log('Server is running on


http://localhost:3000');
});
Run the server: node app.js
Access the server:
Visit http://localhost:3000 in your browser, and you should see Hello, Express!
Common Use Cases for Node.js
1. Real-Time Applications: Chat apps, live updates, collaborative
tools (like Google Docs).
2. API Servers: Build RESTful APIs or GraphQL APIs.
3. Single Page Applications (SPAs): Serve dynamic web applications
that interact with a backend.
4. Microservices: Node.js is lightweight and works well for building
scalable microservices architectures.
5. Web Servers: Handle HTTP requests and serve web pages, using
frameworks like Express.

12. Exploring Language additions to the v8


javascript engine
The V8 JavaScript engine is continuously evolving, and with it, JavaScript itself
is being updated with new features and capabilities. V8 is the engine used by
Google Chrome and Node.js, and its updates often introduce new language
features, optimizations, and tools to make JavaScript faster and more powerful.
Here are some recent and upcoming language additions and features that have
been added to JavaScript via V8:
1. Top-level Await (ECMAScript 2022)
• What it is: This feature allows you to use await at the top level of a
module, without needing to wrap it in an async function. Prior to this,
await could only be used within async functions, but now you can
directly use it at the module level.
• Why it's useful: Makes asynchronous programming in modules
simpler and cleaner. // With Top-level await const data = await
fetchData(); console.log(data);
Supported in V8: Introduced in V8 10.2 (Node.js 16.x).
Logical Assignment Operators (ECMAScript 2021)
• What it is: JavaScript added three new logical assignment
operators: &&=, ||=, and ??=. These operators combine logical
operations with assignment.
• Why it's useful: Simplifies common patterns where you check a
value before assignment.
let a = null; a ||= 'default'; // equivalent to if (!a) a = 'default'; console.log(a); //
'default'
WeakRefs (ECMAScript 2021)
• What it is: WeakRefs allow you to hold a weak reference to an
object. This means that the garbage collector can collect the object even
if it has a reference in a WeakRef.
Why it's useful: Useful for cases where you want to hold references to objects,
but don't want those references to prevent garbage collection (like in caching
or lifecycle management).
let obj = { name: 'Weak Reference' }; const weakRef = new WeakRef(obj);

console.log(weakRef.deref()); // Returns the object obj = null; // Now the


object can be garbage collected

13. Understanding Node.js


Node.js is a powerful, open-source, server-side runtime environment built on
Chrome's V8 JavaScript engine. It enables developers to use JavaScript for both
front-end and back-end development, which was traditionally limited to just
the front-end. Here’s a breakdown of key concepts to help you understand it
better:
1. JavaScript on the Server:
• Node.js allows you to run JavaScript code on the server-side,
which means you can use JavaScript not just for client-side scripting in
web browsers, but also for handling server requests, accessing
databases, and processing data.
2. Event-Driven Architecture:
• Node.js is built around an event-driven, non-blocking I/O
(input/output) model. This means that Node.js can handle many
operations simultaneously (like handling multiple network requests)
without waiting for any of them to complete before moving on to the
next one. This makes it ideal for I/O-heavy applications such as web
servers, real-time services, and data streaming.
3. Non-Blocking I/O:
• In traditional server-side environments (like PHP or Java), I/O
operations like reading from a database or a file can block the entire
process. In contrast, Node.js allows these operations to run
asynchronously, which means they don't block the execution of other
code. As a result, Node.js can handle many operations concurrently,
which makes it highly scalable.
4. Single-Threaded:
• Node.js uses a single-threaded event loop. This means it doesn't
rely on multiple threads to handle concurrent requests. Instead, the
event loop is responsible for managing the execution of multiple
operations asynchronously. This is a key part of Node’s non-blocking,
high-performance model.
5. npm (Node Package Manager):
• Node.js has a robust ecosystem of libraries and tools thanks to
npm. npm is the default package manager for Node.js, and it provides
access to thousands of reusable packages and modules. These modules
allow developers to add functionality (like database connectivity,
authentication, etc.) without having to write everything from scratch.
6. Use Cases of Node.js:
Real-Time Applications: Node.js is great for applications like chat applications,
collaborative tools, and live data feeds, where low latency and fast responses
are essential.
• APIs and Web Servers: Many modern web apps use Node.js for
building RESTful APIs or handling HTTP requests due to its fast
processing and non-blocking capabilities.
• Microservices: Its scalability makes it ideal for a microservices
architecture, where different services can communicate over the
network.
• Streaming Applications: Node.js works well for applications that
require real-time streaming of data, like video or music streaming
services.
Example of a Basic Node.js Server:
const http = require('http'); // Import the HTTP module

const server = http.createServer((req, res) => { res.statusCode = 200; // Set the


HTTP status code res.setHeader('Content-Type', 'text/plain'); res.end('Hello,
Node.js!\n'); // Send a response
});

server.listen(3000, '127.0.0.1', () => { console.log('Server running at


http://127.0.0.1:3000/');
});

14. Http and File System


1. HTTP Module (Creating a Simple Server)
The http module allows you to create an HTTP server and handle requests.
Basic Server Creation
Output :

2. File System Module (fs)


The fs module allows you to work with the file system, including reading,
writing, and deleting files.
OUTPUT :

15.BUFFERS,STREAMS,EVENTS
1. Buffers (Handling Binary Data)
Buffers are used to handle raw binary data directly in memory, making them
useful for working with files, network sockets, and streams.
Buffers store binary data and can be converted to a string using .toString().
2. Streams (Handling Large Data Efficiently)
Streams allow you to process data in chunks instead of loading everything into
memory, making them ideal for handling large files or network requests.
Types of Streams
 Readable (e.g., reading a file)
 Writable (e.g., writing to a file)
 Duplex (both readable & writable, e.g., sockets)
 Transform (modifies data, e.g., compression)
Example: Reading a File Using Streams
OUTPUT :

3.Events (Event-Driven Programming)


Node.js uses the EventEmitter module to handle custom events
asynchronously.
Example: Creating an EventEmitter
16.Steps to Install Express in a Node Project

Step 1: Open the terminal or command prompt on your computer, and


navigate to the root directory of your project.
cd path-to-your-porject

Step 2: Initialize a NodeJS project using the following command.


npm init –y
Step 3: Install the express package using the following command.
npm install express
Project Structure:
OUTPUT :

17. Models ,Views, and Routes


Express follows the MVC (Model-View-Controller) pattern to organize code
efficiently. This guide will walk you through how to implement Models, Views,
and Routes in an Express.js application using MongoDB (Mongoose).
 express → Web framework
 mongoose → MongoDB ORM
 ejs → Templating engine for views
 dotenv → Environment variables
 body-parser → Parses request bodies
 cors → Enables cross-origin requests
express-mvc-app/
│── models/ # Database models
│ ├── User.js
│── controllers/ # Business logic
│ ├── userController.js
│── routes/ # Routing
│ ├── userRoutes.js
│── views/ # Frontend templates (EJS)
│ ├── index.ejs
│── config/ # Database configuration
│ ├── db.js
│── server.js # Main Express server
│── .env # Environment variables
│── package.json

Step:1
Open VSCODE--- create a new folder KK----select the folder myapp ---- In myapp
folder create another folder named as models.
Inside models folder create a file named as User.js
Step2:
Inside models folder create another folder named as views----- In views folder
create a two files
1. newUser.ejs
2. users.ejs
Step 3:
Create another folder in myapp i.e., routes -- inside routes folder create a
file userRoutes.js
Step 4:
Inside myapp folder create a file i.e., .env
Step 5:
In myapp folder create another file named as app.js
Create a .env file in the root directory:

Create app.js
Output:
18. Installing the mongodb in the sytem and set the
path
In Visual Studio Code: Install Mongodb using the following command:

We have to create a New Folder- myapp- In myapp create a file


Create a db.js file and add this code:
Perform CRUD Operations: Create a index.js file and use the following:

Run the script in the terminal using the command


 node index.js

You might also like