0% found this document useful (0 votes)
48 views66 pages

Unit 4 - Part 1 Notes

Node.js is a JavaScript runtime used for building scalable back-end services like APIs and web servers, favored by companies such as PayPal and Netflix. It offers advantages such as easy scalability, real-time web app capabilities, and a rich ecosystem with tools like npm and Express.js for efficient development. The document also covers basic concepts, examples of creating web servers, and RESTful API development using Express.js.

Uploaded by

famoxev442
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
48 views66 pages

Unit 4 - Part 1 Notes

Node.js is a JavaScript runtime used for building scalable back-end services like APIs and web servers, favored by companies such as PayPal and Netflix. It offers advantages such as easy scalability, real-time web app capabilities, and a rich ecosystem with tools like npm and Express.js for efficient development. The document also covers basic concepts, examples of creating web servers, and RESTful API development using Express.js.

Uploaded by

famoxev442
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 66

Node.

JS
Node.js is used to build back-end services like APIs like Web App, Mobile
App or Web Server. A Web Server will open a file on the server and return
the content to the client. It’s used in production by large companies such
as Paypal, Uber, Netflix, Walmart, and so on.
Reasons to Choose Node.js
 Easy to Get Started: Node.js is beginner-friendly and ideal for
prototyping and agile development.
 Scalability: It scales both horizontally and vertically.
 Real-Time Web Apps: Node.js excels in real-time synchronization.
 Fast Suite: It handles operations quickly (e.g., database access,
network connections).
 Unified Language: JavaScript everywhere—frontend and backend.
 Rich Ecosystem: Node.js boasts a large open-source library and
supports asynchronous, non-blocking programming.

PHP and ASP handling file requests:


Send Task -> Waits -> Returns -> Ready for Next Task
Node.js handling file request:
Send Task -> Returns -> Ready for Next Task
Node.js takes requests from users, processes those requests, and returns
responses to the corresponding users, there is no Wait for open and read
file phase in Node.js.
Basic Concepts of Node.JS
The following diagram depicts some important parts of Node.js that are
useful and help us understand it better.

Node.js Example to Create Web Server


It is the basic code example to create node.js server.
JavaScript
Explain

1
// Importing the http module
2
const http = require('http');
3

4
// Creating a server
5
const server = http.createServer((req, res) => {
6
// Setting the content type to HTML
7
res.writeHead(200, {
8
'Content-Type': 'text/html'
9
});
10

11
// Sending the HTML response
12
res.end('<h1>Hello GFG</h1>');
13
});
14

15
// Listening on port 3000
16
const PORT = 3000;
17
server.listen(PORT, () => {
18
console.log(`Server running at http://localhost:${PORT}/`);
19
});
Output:
Example of Node.js Server Output

Code Explaination:
 We use the HTTP module to create an HTTP server.
 The server listens on the specified port and hostname.
 When a new request arrives, the callback function handles it by setting
the response status, headers, and content.
How Node.JS Works?
Node.js accepts the request from the clients and sends the response, while
working with the request node.js handles them with a single thread. To
operate I/O operations or requests node.js use the concept of threads.
Thread is a sequence of instructions that the server needs to perform. It
runs parallel on the server to provide the information to multiple clients.
Node.js is an event loop single-threaded language. It can handle concurrent
requests with a single thread without blocking it for one request.
Advantages of Node.JS
 Easy Scalability: Easily scalable the application in both horizontal and
vertical directions.
 Real-time web apps: Node.js is much more preferable because of
faster synchronization. Also, the event loop avoids HTTP overloaded
for Node.js development.
 Fast Suite: NodeJS acts like a fast suite and all the operations can be
done quickly like reading or writing in the database, network
connection, or file system
 Easy to learn and code: NodeJS is easy to learn and code because it
uses JavaScript.
 Advantage of Caching: It provides the caching of a single module.
Whenever there is any request for the first module, it gets cached in
the application memory, so you don’t need to re-execute the code.

What is Node.JS file?


Node.js files contain tasks that handle file operations
like creating, reading, deleting, etc., Node.js provides an inbuilt module
called FS (File System).

Application of Node.JS
Node.js is suitable for various applications, including:
 Real-time chats
 Complex single-page applications
 Real-time collaboration tools
 Streaming apps
 JSON APIs
Common Use Cases of Node.JS
Node.js is versatile and finds applications in various domains:
1. Web Servers: Node.js excels at building lightweight and efficient web
servers. Its non-blocking I/O model makes it ideal for handling
concurrent connections.
2. APIs and Microservices: Many companies use Node.js to create
RESTful APIs and microservices. Express.js simplifies API
development.
3. Real-Time Applications: Node.js shines in real-time scenarios like
chat applications, live notifications, and collaborative tools. Socket.io
facilitates real-time communication.
4. Single-Page Applications (SPAs): SPAs benefit from Node.js for
server-side rendering (SSR) and handling API requests.
5. Streaming Services: Node.js is well-suited for streaming data,
whether it’s video, audio, or real-time analytics.
Node.JS Ecosystem
Node.js has a vibrant ecosystem with a plethora of libraries, frameworks,
and tools. Here are some key components:
1. npm (Node Package Manager): npm is the default package manager
for Node.js. It allows developers to install, manage, and share reusable
code packages (called modules). You can find thousands of open-
source packages on the npm registry.
2. Express.js: Express is a popular web application framework for
Node.js. It simplifies routing, middleware handling, and
request/response management. Many developers choose Express for
building APIs, web servers, and single-page applications.
3. Socket.io: For real-time communication, Socket.io is a go-to library. It
enables bidirectional communication between the server and clients
using WebSockets or fallback mechanisms.
4. Mongoose: If you’re working with MongoDB (a NoSQL database),
Mongoose provides an elegant way to model your data and interact
with the database. It offers schema validation, middleware, and query
building.

NodeJS NPM
NPM (Node Package Manager) is a package manager
for Node.js modules. It helps developers manage project dependencies,
scripts, and third-party libraries. By installing Node.js on your system,
NPM is automatically installed, and ready to use.
 It is primarily used to manage packages or modules—these are pre-
built pieces of code that extend the functionality of your Node.js
application.
 The NPM registry hosts millions of free packages that you can
download and use in your project.
 NPM is installed automatically when you install Node.js, so you don’t
need to set it up manually.
To master NPM and streamline your full-stack development workflow,
the Full Stack Development with Node JS course offers detailed
lessons on managing packages, scripts, and dependencies for full-stack
applications
How to Use NPM with Node.js?
To start using NPM in your project, follow these simple steps
Step 1: Install Node.js and NPM
First, you need to install Node.js. NPM is bundled with the Node.js
installation. You can follow our article to Install the Node and NPM- How
to install Node on your system
Step 2: Verify the Installation
After installation, verify Node.js and NPM are installed by running the
following commands in your terminal:
node -v
npm -v
These commands will show the installed versions of Node.js and NPM.

NodeJS NPM Version

Step 3: Initialize a New Node.js Project


In the terminal, navigate to your project directory and run:
npm init -y
This will create a package.json file, which stores metadata about your
project, including dependencies and scripts.
Step 4: Install Packages with NPM
To install a package, use the following command
npm install <package-name>
For example, to install the Express.js framework
npm install express
This will add express to the node_modules folder and automatically
update the package.json file with the installed package information.
Step 5: Install Packages Globally
To install packages that you want to use across multiple projects, use the
-g flag:
npm install -g <package-name>
Step 6: Run Scripts
You can also define custom scripts in the package.json file under the
“scripts” section. For example:
{
"scripts": {
"start": "node app.js"
}
}
Then, run the script with
npm start
Using NPM Package in the project
Create a file named app.js in the project directory to use the package
JavaScript

1
//app.js
2

3
const express = require('express');//import the required package
4
const app = express();
5

6
app.get('/', (req, res) => {
7
res.send('Hello, World!');
8
});
9

10
app.listen(3000, () => {
11
console.log('Server running at http://localhost:3000');
12
});
 express() creates an instance of the Express app.
 app.get() defines a route handler for HTTP GET requests to the root (/)
URL.
 res.send() sends the response “Hello, World!” to the client.
 app.listen(3000) starts the server on port 3000, and console.log()
outputs the server URL.
Now run the application with
node app.js
Visit http://localhost:3000 in your browser, and you should see the
message: Hello, World!
Managing Project Dependencies
1. Installing All Dependencies
In a Node.js project, dependencies are stored in a package.json file. To
install all dependencies listed in the file, run:
npm install
This will download all required packages and place them in the
node_modules folder.
2. Installing a Specific Package
To install a specific package, use:
npm install <package-name>
You can also install a package as a development dependency using:
npm install <package-name> --save-dev
Development dependencies are packages needed only during
development, such as testing libraries.
To install a package and simultaneously save it in package.json file (in
case using Node.js), add –save flag. The –save flag is default in npm
install command so it is equal to npm install package_name command.
Example:
npm install express --save
Usage of Flags:
 –save: flag one can control where the packages are to be installed.
 –save-prod : Using this packages will appear in Dependencies which
is also by default.
 –save-dev : Using this packages will get appear in devDependencies
and will only be used in the development mode.
Note: If there is a package.json file with all the packages mentioned as
dependencies already, just type npm install in terminal
3. Updating Packages
You can easily update packages in your project using the following
command
npm update
This will update all packages to their latest compatible versions based on
the version constraints in the package.json file.
To update a specific package, run
npm update <package-name>
4. Uninstalling Packages
To uninstall packages using npm, follow the below syntax:
npm uninstall <package-name>
For uninstall Global Packages
npm uninstall package_name -g
Popular NPM Packages
NPM has a massive library of packages. Here are a few popular packages
that can enhance your Node.js applications:
 Express: A fast, minimal web framework for building APIs and web
applications.
 Mongoose: A MongoDB object modeling tool for Node.js.
 Lodash: A utility library delivering consistency, customization, and
performance.
 Axios: A promise-based HTTP client for making HTTP requests.
 React: A popular front-end library used to build user interfaces.

Versioning in NPM
NPM allows you to manage package versions. This is important when you
want to ensure that a specific version of a library is used across all
environments.

Install a Specific Version


To install a specific version of a package, use:
npm install <package-name>@<version>

For example
npm install [email protected]
This will install version 4.17.1 of Express, regardless of the latest version.
Using Semantic Versioning to manage packages
RESTful APIs are a popular way of creating web applications that exchange
data over the internet in a standardized manner. These APIs follow specific
principles such as using resource-based URLs and HTTP methods to
perform various operations like creating, reading, updating, and deleting
data. ExpressJS is a powerful framework that allows developers to easily
create routes, handle requests, and send responses, making it a versatile
choice for building APIs that are robust and scalable.
Understanding the concept of RESTful APIs in
Express JS:
 REST Architecture: REST, which stands for Representational State
Transfer, is an architectural style for designing networked applications.
 Resource-Based: RESTful APIs in ExpressJS are designed around
resources, which are identified by unique URLs. These resources
represent the entities (e.g., users, products, articles) that the API
manipulates.
 HTTP Methods: RESTful APIs use standard HTTP methods to
perform CRUD (Create, Read, Update, Delete) operations on
resources:
o GET: Retrieves data from a resource.
o POST: Creates a new resource.
o PUT: Updates an existing resource.
o DELETE: Deletes a resource.
 Statelessness: RESTful APIs are stateless, meaning that each
request from a client contains all the information needed to process the
request. Servers do not maintain a session state between requests.
 Uniform Interface: RESTful APIs have a uniform interface, which
simplifies communication between clients and servers. This interface
typically involves the use of standard HTTP methods, resource
identifiers (URLs), and representations (e.g., JSON, XML).
 ExpressJS and Routing: In ExpressJS, you define routes to handle
incoming requests for specific resources and HTTP methods. Each
route specifies a callback function to process the request and send an
appropriate response.
 Middleware Integration: ExpressJS middleware can be used to
handle tasks such as request validation, authentication, and response
formatting, enhancing the functionality and security of RESTful APIs.
 Response Codes: RESTful APIs use standard HTTP status codes to
indicate the success or failure of a request. Common status codes
include 200 (OK), 201 (Created), 400 (Bad Request), 404 (Not
Found), and 500 (Internal Server Error).
Example: Below are the example of RESTful APIs in ExpressJS.
 Install the necessary package in your application using the following
command.
npm install express
Example: Below is the basic example of the RESTful API in ExpressJS.
JavaScript

1
// server.js
2
const express = require('express');
3
const app = express();
4
const PORT = 3000;
5

6
// To define the sample data
7
let books = [
8
{
9
id: 1,
10
title: 'The Great Gatsby',
11
author: 'F. Scott Fitzgerald'
12
},
13
{
14
id: 2,
15
title: 'To Kill a Mockingbird',
16
author: 'Harper Lee'
17
},
18
];
19

20
// Define routes for handling GET requests
21
app.get('/api/books',
22
(req, res) =&gt; {
23
res.json(books);
24
});
25

26
app.get('/api/books/:id',
27
(req, res) =&gt; {
28
const id =
29
parseInt(req.params.id);
30
const book =
31
books.find(book =&gt; book.id === id);
32
if (book) {
33
res.json(book);
34
} else {
35
res.status(404)
36
.json({ message: 'Book not found' });
37
}
38
});
39

40
app.listen(PORT,
41
() =&gt; {
42
console.log(`Server is running on port ${PORT}`);
43
});
Start your application using the following command.

node server.js
Node.js - Express Framework
Express.js is a minimal and flexible web application framework that provides
a robust set of features to develop Node.js based web and mobile
applications. Express.js is one of the most popular web frameworks in the
Node.js ecosystem. Express.js provides all the features of a modern web
framework, such as templating, static file handling, connectivity with SQL
and NoSQL databases.

Node.js has a built-in web server. The createServer() method in its http
module launches an asynchronous http server. It is possible to develop a
web application with core Node.js features. However, all the low level
manipulations of HTTP request and responses have to be tediously handled.
The web application frameworks take care of these common tasks, allowing
the developer to concentrate on the business logic of the application. A web
framework such as Express.js is a set of utilities that facilitates rapid, robust
and scalable web applications.

Following are some of the core features of Express framework −

 Allows to set up middlewares to respond to HTTP Requests.


 Defines a routing table which is used to perform different actions based on
HTTP Method and URL.
 Allows to dynamically render HTML Pages based on passing arguments to
templates.

The Express.js is built on top of the connect middleware, which in turn is


based on http, one of the core modules of Node.js API.
Installing Express
The Express.js package is available on npm package repository. Let us install
express package locally in an application folder named ExpressApp.

D:\expressApp> npm init


D:\expressApp> npm install express --save

The above command saves the installation locally in the node_modules


directory and creates a directory express inside node_modules.

Hello world Example


Following is a very basic Express app which starts a server and listens on
port 5000 for connection. This app responds with Hello World! for requests to
the homepage. For every other path, it will respond with a 404 Not Found.

var express = require('express');


var app = express();

app.get('/', function (req, res) {


res.send('Hello World');
})

var server = app.listen(5000, function () {


console.log("Express App running at http://127.0.0.1:5000/");
})

Save the above code as index.js and run it from the command-line.
D:\expressApp> node index.js
Express App running at http://127.0.0.1:5000/

Visit http://localhost:5000/ in a browser window. It displays the Hello World


message.

Explore our latest online courses and learn new skills at your own pace. Enroll
and become a certified expert to boost your career.

Application object
An object of the top level express class denotes the application object. It is
instantiated by the following statement −

var express = require('express');


var app = express();

The Application object handles important tasks such as handling HTTP


requests, rendering HTML views, and configuring middleware etc.

The app.listen() method creates the Node.js web server at the specified host
and port. It encapsulates the createServer() method in http module of
Node.js API.

app.listen(port, callback);
Basic Routing
The app object handles HTTP requests GET, POST, PUT and DELETE with
app.get(), app.post(), app.put() and app.delete() method respectively. The
HTTP request and HTTP response objects are provided as arguments to these
methods by the NodeJS server. The first parameter to these methods is a
string that represents the endpoint of the URL. These methods are
asynchronous, and invoke a callback by passing the request and response
objects.

GET method
In the above example, we have provided a method that handles the GET
request when the client visits '/' endpoint.

app.get('/', function (req, res) {


res.send('Hello World');
})
 Request Object − The request object represents the HTTP request and has
properties for the request query string, parameters, body, HTTP headers, and
so on.
 Response Object − The response object represents the HTTP response that an
Express app sends when it gets an HTTP request. The send() method of the
response object formulates the server's response to the client.

You can print request and response objects which provide a lot of information
related to HTTP request and response including cookies, sessions, URL, etc.

The response object also has a sendFile() method that sends the contents of
a given file as the response.

res.sendFile(path)

Save the following HTML script as index.html in the root folder of the express
app.

<html>
<body>
<h2 style="text-align: center;">Hello World</h2>
</body>
</html>

Change the index.js file to the code below −

var express = require('express');


var app = express();
var path = require('path');

app.get('/', function (req, res) {


res.sendFile(path.join(__dirname,"index.html"));
})

var server = app.listen(5000, function () {

console.log("Express App running at http://127.0.0.1:5000/");


})

Run the above program and visit http://localhost:5000/, the browser shows
Hello World message as below:

Let us use sendFile() method to display a HTML form in the index.html file.

<html>
<body>

<form action = "/process_get" method = "GET">


First Name: <input type = "text" name = "first_name"> <br>
Last Name: <input type = "text" name = "last_name"> <br>
<input type = "submit" value = "Submit">
</form>

</body>
</html>

The above form submits the data to /process_get endpoint, with GET
method. Hence we need to provide a app.get() method that gets called when
the form is submitted.
app.get('/process_get', function (req, res) {
// Prepare output in JSON format
response = {
first_name:req.query.first_name,
last_name:req.query.last_name
};
console.log(response);
res.end(JSON.stringify(response));
})

The form data is included in the request object. This method retrieves the
data from request.query array, and sends it as a response to the client.

The complete code for index.js is as follows −

var express = require('express');


var app = express();
var path = require('path');

app.use(express.static('public'));

app.get('/', function (req, res) {


res.sendFile(path.join(__dirname,"index.html"));
})

app.get('/process_get', function (req, res) {


// Prepare output in JSON format
response = {
first_name:req.query.first_name,
last_name:req.query.last_name
};
console.log(response);
res.end(JSON.stringify(response));
})

var server = app.listen(5000, function () {


console.log("Express App running at http://127.0.0.1:5000/");
})

Visit http://localhost:5000/.
Now you can enter the First and Last Name and then click submit button to
see the result and it should return the following result −

{"first_name":"John","last_name":"Paul"}

POST method
The HTML form is normally used to submit the data to the server, with its
method parameter set to POST, especially when some binary data such as
images is to be submitted. So, let us change the method parameter in
index.html to POST, and action parameter to "process_POST".

<html>
<body>

<form action = "/process_POST" method = "POST">


First Name: <input type = "text" name = "first_name"> <br>
Last Name: <input type = "text" name = "last_name"> <br>
<input type = "submit" value = "Submit">
</form>

</body>
</html>

To handle the POST data, we need to install the body-parser package from
npm. Use the following command.

npm install body-parser –save

This is a node.js middleware for handling JSON, Raw, Text and URL encoded
form data.

This package is included in the JavaScript code with the following require
statement.
var bodyParser = require('body-parser');

The urlencoded() function creates application/x-www-form-urlencoded parser

// Create application/x-www-form-urlencoded parser


var urlencodedParser = bodyParser.urlencoded({ extended: false })

Add the following app.post() method in the express application code to


handle POST data.

app.post('/process_post', urlencodedParser, function (req, res) {


// Prepare output in JSON format
response = {
first_name:req.body.first_name,
last_name:req.body.last_name
};
console.log(response);
res.end(JSON.stringify(response));
})

Here is the complete code for index.js file

var express = require('express');


var app = express();
var path = require('path');

var bodyParser = require('body-parser');


// Create application/x-www-form-urlencoded parser
var urlencodedParser = bodyParser.urlencoded({ extended: false })

app.use(express.static('public'));

app.get('/', function (req, res) {


res.sendFile(path.join(__dirname,"index.html"));
})

app.get('/process_get', function (req, res) {


// Prepare output in JSON format
response = {
first_name:req.query.first_name,
last_name:req.query.last_name
};
console.log(response);
res.end(JSON.stringify(response));
})
app.post("/process_post", )
var server = app.listen(5000, function () {
console.log("Express App running at http://127.0.0.1:5000/");
})

Run index.js from command prompt and visit http://localhost:5000/.

Now you can enter the First and Last Name and then click the submit button
to see the following result −

{"first_name":"John","last_name":"Paul"}

Serving Static Files


Express provides a built-in middleware express.static to serve static files,
such as images, CSS, JavaScript, etc.

You simply need to pass the name of the directory where you keep your
static assets, to the express.static middleware to start serving the files
directly. For example, if you keep your images, CSS, and JavaScript files in a
directory named public, you can do this −

Callbacks and Events in Node.js


Callback Concept: A Callback is a function that is called automatically
when a particular task is completed. The Callback function allows the
program to run other code until a certain task is not completed. The
callback function is heavily used in nodeJS. The callback function allows
you to perform a large number of I/O operations that can be handled by
your OS without waiting for any I/O operation to finish. It makes nodeJS
highly scalable.
For example: In Node.js, when a function starts reading a file, It’s
obviously going to take some time so without waiting for that function to
complete, it returns control to the execution environment immediately an
executes the succeeding instruction. Once file I/O gets completed, the
callback function will be automatically called hence there will be no waiting
or blocking for file I/O.
Note: The callback function is being replaced by async/await these days.
Syntax: Let’s see the syntax of the callback function.
const fs = require("fs");

fs.readFile("file_path", "utf8", function (err, data) {


if (err) {
// Handle the error
} else {
// Process the file text given with data
}
});
Example 1: Code for reading a file synchronously in Node.js. Create a
text file input.txt with the following text:
Welcome to GFG.
Learn NodeJS with GeeksforGeeks
Now, create a javascript file name main.js with the following code.

 Javascript

const fs = require("fs");

const filedata = fs.readFileSync('input.txt');

console.log(filedata.toString());

console.log("End of Program execution");

Now run the main.js to see the result with the following command:
node main.js
Explanation: In this example, we have an fs module of nodeJS that
provides the functionality of File I/O operations. With the help of the
readFileSync() function, we are able to use the Synchronous approach
here, which is also called the blocking function as it waits for each
instruction to be complete first before going to the next one. Hence in this
example, the function blocks the program until it reads the file and then
went ahead with the end of the program.
Output:

GFG

Example 2: Code for reading a file asynchronously in Node.js. Keep the


“input.txt” file the same as before. Here is the code of main.js:
 Javascript

const fs = require("fs");

fs.readFile('input.txt', function (err, data) {

if (err) return console.error(err);

console.log(data.toString());

});

console.log("End of Program execution");

Now run the main.js to see the result with the following command:
node main.js
Explanation: With the help of the readFile() function, we are able to use
the Asynchronous approach here, which is also called a non-blocking
function as it never waits for each instruction to complete, rather it
executes all operations in the first go itself. Hence in this example, the
function runs in the background, and the control is returned to the next
instruction. When the background task is completed callback function is
called.
Output:
GFG

Events: Each action on the computer is called an event. In nodeJS


objects can fire events. According to the official documentation of Node.js,
it is an asynchronous event-driven JavaScript runtime. Node.js has an
event-driven architecture that can perform asynchronous tasks. Node.js
has an ‘events’ module that emits named events that can cause
corresponding functions or callbacks to be called. Functions(Callbacks)
listen or subscribe to a particular event to occur and when that event
triggers, all the callbacks subscribed to that event are fired one by one in
order to which they were registered.
The EventEmmitter class: All objects that emit events are instances of
the EventEmitter class. The event can be emitted or listened to an event
with the help of EventEmitter.
Syntax:
const EventEmitter=require('events');
var eventEmitter=new EventEmitter();
The following table lists all the important methods of the EventEmitter
class:

EventEmitter Methods Description

eventEmmitter.on(event, listener) and


eventEmitter.addListener(event, listener)
are pretty much similar. It adds the
listener at the end of the listener’s array
eventEmitter.addListener(event,
for the specified event. Multiple calls to
listener) && eventEmitter.on(event,
the same event and listener will add the
listener)
listener multiple times and
correspondingly fire multiple times. Both
functions return an emitter, so calls can be
chained.

It fires at most once for a particular event


and will be removed from the listeners and
eventEmitter.once(event, listener)
events array after it has listened once.
Returns emitter, so calls can be chained.
Every event is named an event in nodeJS.
We can trigger an event by emit(event,
eventEmitter.emit(event, [arg1],
[arg1], [arg2], […]) function. We can pass
[arg2], […])
an arbitrary set of arguments to the
listener functions.

It takes two argument events and a listener


eventEmitter.removeListener(event, and removes that listener from the
listener) listener’s array that is subscribed to that
event

It removes all the listeners from the array


eventEmitter.removeAllListeners() who are subscribed to the mentioned
event.

It will return the max listeners value set by


eventEmitter.getMaxListeners(n)
setMaxListeners() or default value 10.

By default, a maximum of 10 listeners can


be registered for any single event. To
EventEmitter.defaultMaxListeners change the default value for all
EventEmitter instances this property can
be used.

It returns an array of listeners for the


eventEmitter.listeners(event)
specified event.

It returns the number of listeners listening


eventEmitter.listenerCount()
to the specified event.

It will add the one-time listener to the


eventEmitter.prependOnceListener()
beginning of the array.

It will add the listener to the beginning of


eventEmitter.prependListener()
the array.

Example 1: Code for creating a program of a simple event:


 Javascript

const EventEmitter = require('events');


// Initializing event emitter instances

const eventEmitter = new EventEmitter();

// Create an event handler:

const EventHandler = function () {

console.log('Learn nodejs!');

// Assign the event handler to an event:

eventEmitter.on('event1', EventHandler);

// Fire the 'scream' event:

eventEmitter.emit('event1');

Now run the main.js to see the result with the following command:
node main.js
Output:

Example 2: This example, shows the creating and removing of the


listener. The EventEmitter instance will emit its own ‘newListener’ event.
The ‘removeListener’ event is emitted after a listener is removed.
 Javascript

// Importing events
const EventEmitter = require('events');

// Initializing event emitter instances

const eventEmitter = new EventEmitter();

// Register to newListener

eventEmitter.on('newListener', (event, listener) => {

console.log(`The listener is added to ${event}`);

});

// Register to removeListener

eventEmitter.on('removeListener', (event, listener) => {

console.log(`The listener is removed from ${event}`);

});

// Declaring listener fun1 to myEvent1

const fun1 = (msg) => {

console.log("Message from fun1: " + msg);

};

// Declaring listener fun2 to myEvent2


const fun2 = (msg) => {

console.log("Message from fun2: " + msg);

};

// Listening to myEvent with fun1 and fun2

eventEmitter.on('myEvent', fun1);

eventEmitter.on('myEvent', fun2);

// Removing listener

eventEmitter.off('myEvent', fun1);

// Triggering myEvent

eventEmitter.emit('myEvent', 'Event occurred');

Now run the main.js to see the result with the following command:
node main.js
Output:

Callback Concept: A Callback is a function that is called automatically


when a particular task is completed. The Callback function allows the
program to run other code until a certain task is not completed. The
callback function is heavily used in nodeJS. The callback function allows
you to perform a large number of I/O operations that can be handled by
your OS without waiting for any I/O operation to finish. It makes nodeJS
highly scalable.
For example: In Node.js, when a function starts reading a file, It’s
obviously going to take some time so without waiting for that function to
complete, it returns control to the execution environment immediately an
executes the succeeding instruction. Once file I/O gets completed, the
callback function will be automatically called hence there will be no waiting
or blocking for file I/O.
Note: The callback function is being replaced by async/await these days.
Syntax: Let’s see the syntax of the callback function.
const fs = require("fs");

fs.readFile("file_path", "utf8", function (err, data) {


if (err) {
// Handle the error
} else {
// Process the file text given with data
}
});
Example 1: Code for reading a file synchronously in Node.js. Create a
text file input.txt with the following text:
Welcome to GFG.
Learn NodeJS with GeeksforGeeks
Now, create a javascript file name main.js with the following code.

 Javascript

const fs = require("fs");

const filedata = fs.readFileSync('input.txt');

console.log(filedata.toString());

console.log("End of Program execution");

Now run the main.js to see the result with the following command:
node main.js
Explanation: In this example, we have an fs module of nodeJS that
provides the functionality of File I/O operations. With the help of the
readFileSync() function, we are able to use the Synchronous approach
here, which is also called the blocking function as it waits for each
instruction to be complete first before going to the next one. Hence in this
example, the function blocks the program until it reads the file and then
went ahead with the end of the program.
Output:

GFG

Example 2: Code for reading a file asynchronously in Node.js. Keep the


“input.txt” file the same as before. Here is the code of main.js:
 Javascript

const fs = require("fs");

fs.readFile('input.txt', function (err, data) {

if (err) return console.error(err);

console.log(data.toString());

});

console.log("End of Program execution");

Now run the main.js to see the result with the following command:
node main.js
Explanation: With the help of the readFile() function, we are able to use
the Asynchronous approach here, which is also called a non-blocking
function as it never waits for each instruction to complete, rather it
executes all operations in the first go itself. Hence in this example, the
function runs in the background, and the control is returned to the next
instruction. When the background task is completed callback function is
called.
Output:

GFG
Events: Each action on the computer is called an event. In nodeJS
objects can fire events. According to the official documentation of Node.js,
it is an asynchronous event-driven JavaScript runtime. Node.js has an
event-driven architecture that can perform asynchronous tasks. Node.js
has an ‘events’ module that emits named events that can cause
corresponding functions or callbacks to be called. Functions(Callbacks)
listen or subscribe to a particular event to occur and when that event
triggers, all the callbacks subscribed to that event are fired one by one in
order to which they were registered.
The EventEmmitter class: All objects that emit events are instances of
the EventEmitter class. The event can be emitted or listened to an event
with the help of EventEmitter.
Syntax:
const EventEmitter=require('events');
var eventEmitter=new EventEmitter();
The following table lists all the important methods of the EventEmitter
class:

EventEmitter Methods Description

eventEmmitter.on(event, listener) and


eventEmitter.addListener(event, listener)
are pretty much similar. It adds the
listener at the end of the listener’s array
eventEmitter.addListener(event,
for the specified event. Multiple calls to
listener) && eventEmitter.on(event,
the same event and listener will add the
listener)
listener multiple times and
correspondingly fire multiple times. Both
functions return an emitter, so calls can be
chained.

It fires at most once for a particular event


and will be removed from the listeners and
eventEmitter.once(event, listener)
events array after it has listened once.
Returns emitter, so calls can be chained.

Every event is named an event in nodeJS.


We can trigger an event by emit(event,
eventEmitter.emit(event, [arg1],
[arg1], [arg2], […]) function. We can pass
[arg2], […])
an arbitrary set of arguments to the
listener functions.
It takes two argument events and a listener
eventEmitter.removeListener(event, and removes that listener from the
listener) listener’s array that is subscribed to that
event

It removes all the listeners from the array


eventEmitter.removeAllListeners() who are subscribed to the mentioned
event.

It will return the max listeners value set by


eventEmitter.getMaxListeners(n)
setMaxListeners() or default value 10.

By default, a maximum of 10 listeners can


be registered for any single event. To
EventEmitter.defaultMaxListeners change the default value for all
EventEmitter instances this property can
be used.

It returns an array of listeners for the


eventEmitter.listeners(event)
specified event.

It returns the number of listeners listening


eventEmitter.listenerCount()
to the specified event.

It will add the one-time listener to the


eventEmitter.prependOnceListener()
beginning of the array.

It will add the listener to the beginning of


eventEmitter.prependListener()
the array.

Example 1: Code for creating a program of a simple event:


 Javascript

const EventEmitter = require('events');

// Initializing event emitter instances

const eventEmitter = new EventEmitter();


// Create an event handler:

const EventHandler = function () {

console.log('Learn nodejs!');

// Assign the event handler to an event:

eventEmitter.on('event1', EventHandler);

// Fire the 'scream' event:

eventEmitter.emit('event1');

Now run the main.js to see the result with the following command:
node main.js
Output:

Example 2: This example, shows the creating and removing of the


listener. The EventEmitter instance will emit its own ‘newListener’ event.
The ‘removeListener’ event is emitted after a listener is removed.
 Javascript

// Importing events

const EventEmitter = require('events');

// Initializing event emitter instances


const eventEmitter = new EventEmitter();

// Register to newListener

eventEmitter.on('newListener', (event, listener) => {

console.log(`The listener is added to ${event}`);

});

// Register to removeListener

eventEmitter.on('removeListener', (event, listener) => {

console.log(`The listener is removed from ${event}`);

});

// Declaring listener fun1 to myEvent1

const fun1 = (msg) => {

console.log("Message from fun1: " + msg);

};

// Declaring listener fun2 to myEvent2

const fun2 = (msg) => {

console.log("Message from fun2: " + msg);

};
// Listening to myEvent with fun1 and fun2

eventEmitter.on('myEvent', fun1);

eventEmitter.on('myEvent', fun2);

// Removing listener

eventEmitter.off('myEvent', fun1);

// Triggering myEvent

eventEmitter.emit('myEvent', 'Event occurred');

Now run the main.js to see the result with the following command:
node main.js

Output:

What is MongoDB
MongoDB is an open-source document database that provides high performance, high
availability, and automatic scaling.
In simple words, you can say that - Mongo DB is a document-oriented database. It is an
open source product, developed and supported by a company named 10gen.

MongoDB is available under General Public license for free, and it is also available under
Commercial license from the manufacturer.

The manufacturing company 10gen has defined MongoDB as:

"MongoDB is a scalable, open source, high performance, document-oriented database."


- 10gen

MongoDB was designed to work with commodity servers. Now it is used by the company
of all sizes, across all industry.

History of MongoDB
The initial development of MongoDB began in 2007 when the company was building a
platform as a service similar to window azure.

Window azure is a cloud computing platform and infrastructure, created by Microsoft,


to build, deploy and manage applications and service through a global network.
MongoDB was developed by a NewYork based organization named 10gen which is now
known as MongoDB Inc. It was initially developed as a PAAS (Platform as a Service).
Later in 2009, it is introduced in the market as an open source database server that was
maintained and supported by MongoDB Inc.

The first ready production of MongoDB has been considered from version 1.4 which was
released in March 2010.

MongoDB2.4.9 was the latest and stable version which was released on January 10, 2014.

Purpose of Building MongoDB


It may be a very genuine question that - "what was the need of MongoDB although there
were many databases in action?"

There is a simple answer:

All the modern applications require big data, fast features development, flexible
deployment, and the older database systems not competent enough, so the MongoDB
was needed.

The primary purpose of building MongoDB is:

o Scalability
o Performance
o High Availability
o Scaling from single server deployments to large, complex multi-site
architectures.
o Key points of MongoDB
o Develop Faster
o Deploy Easier
o Scale Bigger
First of all, we should know what is document oriented database?

Example of Document-Oriented Database


MongoDB is a document-oriented database. It is a key feature of MongoDB. It offers a
document-oriented storage. It is very simple you can program it easily.

MongoDB stores data as documents, so it is known as document-oriented database.

1. FirstName = "John",

2. Address = "Detroit",
3. Spouse = [{Name: "Angela"}].

4. FirstName ="John",
5. Address = "Wick"
There are two different documents (separated by ".").

Storing data in this manner is called as document-oriented database.

Mongo DB falls into a class of databases that calls Document Oriented Databases. There
is also a broad category of database known as No SQL Databases.

Features of MongoDB
These are some important features of MongoDB:

1. Support ad hoc queries

In MongoDB, you can search by field, range query and it also supports regular expression
searches.

2. Indexing

You can index any field in a document.

3. Replication

MongoDB supports Master Slave replication.

A master can perform Reads and Writes and a Slave copies data from the master and
can only be used for reads or back up (not writes)

4. Duplication of data
MongoDB can run over multiple servers. The data is duplicated to keep the system up and
also keep its running condition in case of hardware failure.

5. Load balancing

It has an automatic load balancing configuration because of data placed in shards.

6. Supports map reduce and aggregation tools.

7. Uses JavaScript instead of Procedures.

8. It is a schema-less database written in C++.

9. Provides high performance.

10. Stores files of any size easily without complicating your stack.

11. Easy to administer in the case of failures.

12. It also supports:

o JSON data model with dynamic schemas


o Auto-sharding for horizontal scalability
o Built in replication for high availability
o Now a day many companies using MongoDB to create new types of
applications, improve performance and availability.

MongoDB Query and Projection Operator


The MongoDB query operator includes comparison, logical, element, evaluation,
Geospatial, array, bitwise, and comment operators.

MongoDB Comparison Operators

$eq
The $eq specifies the equality condition. It matches documents where the value of a field
equals the specified value.

Syntax:

1. { <field> : { $eq: <value> } }


Example:

1. db.books.find ( { price: { $eq: 300 } } )


The above example queries the books collection to select all documents where the value
of the price filed equals 300.

$gt
The $gt chooses a document where the value of the field is greater than the specified
value.

Syntax:

1. { field: { $gt: value } }


Example:

1. db.books.find ( { price: { $gt: 200 } } )

$gte
The $gte choose the documents where the field value is greater than or equal to a
specified value.

Syntax:

1. { field: { $gte: value } }


Example:

1. db.books.find ( { price: { $gte: 250 } } )

$in
The $in operator choose the documents where the value of a field equals any value in the
specified array.

Syntax:

1. { filed: { $in: [ <value1>, <value2>, ……] } }


Example:

1. db.books.find( { price: { $in: [100, 200] } } )

$lt
The $lt operator chooses the documents where the value of the field is less than the
specified value.

Syntax:

1. { field: { $lt: value } }


Example:

1. db.books.find ( { price: { $lt: 20 } } )

$lte
The $lte operator chooses the documents where the field value is less than or equal to a
specified value.
Syntax:

1. { field: { $lte: value } }


Example:

1. db.books.find ( { price: { $lte: 250 } } )

$ne
The $ne operator chooses the documents where the field value is not equal to the
specified value.

Syntax:

1. { <field>: { $ne: <value> } }


Example:

1. db.books.find ( { price: { $ne: 500 } } )

$nin
The $nin operator chooses the documents where the field value is not in the specified
array or does not exist.

Syntax:

1. { field : { $nin: [ <value1>, <value2>, .... ] } }


Example:

1. db.books.find ( { price: { $nin: [ 50, 150, 200 ] } } )

MongoDB Logical Operator

$and
The $and operator works as a logical AND operation on an array. The array should be of
one or more expressions and chooses the documents that satisfy all the expressions in
the array.

Syntax:

1. { $and: [ { <exp1> }, { <exp2> }, ....]}


Example:

1. db.books.find ( { $and: [ { price: { $ne: 500 } }, { price: { $exists: true } } ] } )

$not
The $not operator works as a logical NOT on the specified expression and chooses the
documents that are not related to the expression.

Syntax:

1. { field: { $not: { <operator-expression> } } }


Example:

1. db.books.find ( { price: { $not: { $gt: 200 } } } )

$nor
The $nor operator works as logical NOR on an array of one or more query expression and
chooses the documents that fail all the query expression in the array.

Syntax:

1. { $nor: [ { <expression1> } , { <expresion2> } , ..... ] }


Example:

1. db.books.find ( { $nor: [ { price: 200 }, { sale: true } ] } )

$or
It works as a logical OR operation on an array of two or more expressions and chooses
documents that meet the expectation at least one of the expressions.

Syntax:

1. { $or: [ { <exp_1> }, { <exp_2> }, ... , { <exp_n> } ] }


Example:

1. db.books.find ( { $or: [ { quantity: { $lt: 200 } }, { price: 500 } ] } )

MongoDB Element Operator

$exists
The exists operator matches the documents that contain the field when Boolean is true. It
also matches the document where the field value is null.

Syntax:

1. { field: { $exists: <boolean> } }


Example:

1. db.books.find ( { qty: { $exists: true, $nin: [ 5, 15 ] } } )

$type
The type operator chooses documents where the value of the field is an instance of the
specified BSON type.

Syntax:

1. { field: { $type: <BSON type> } }


Example:

1. db.books.find ( { "bookid" : { $type : 2 } } );

MongoDB Evaluation Operator

$expr
The expr operator allows the use of aggregation expressions within the query language.

Syntax:

1. { $expr: { <expression> } }
Example:

1. db.store.find( { $expr: {$gt: [ "$product" , "price" ] } } )

$jsonSchema
It matches the documents that satisfy the specified JSON Schema.

Syntax:

1. { $jsonSchema: <JSON schema object> }

$mod
The mod operator selects the document where the value of a field is divided by a divisor
has the specified remainder.

Syntax:

1. { field: { $mod: [ divisor, remainder ] } }


Example:

1. db.books.find ( { qty: { $mod: [ 200, 0] } } )

$regex
It provides regular expression abilities for pattern matching strings in queries. The
MongoDB uses regular expressions that are compatible with Perl.

Syntax:
1. { <field>: /pattern/<options> }
Example:

1. db.books.find( { price: { $regex: /789$/ } } )

$text
The $text operator searches a text on the content of the field, indexed with a text index.

Syntax:

1. {
2. $text:
3. {
4. $search: <string>,
5. $language: <string>,
6. $caseSensitive: <boolean>,
7. $diacriticSensitive: <boolean>
8. }
9. }
Example:

1. db.books.find( { $text: { $search: "Othelo" } } )

$where
The "where" operator is used for passing either a string containing a JavaScript expression
or a full JavaScript function to the query system.

Example:

1. db.books.find( { $where: function() {


2. return (hex_md5(this.name)== "9b53e667f30cd329dca1ec9e6a8")
3. } } );

MongoDB Geospatial Operator

$geoIntersects
It selects only those documents whose geospatial data intersects with the given GeoJSON
object.

Syntax:

1. {
2. <location field>: {
3. $geoIntersects: {
4. $geometry: {
5. type: "<object type>" ,
6. coordinates: [ <coordinates> ]
7. }
8. }
9. }
10. }
Example:

1. db.places.find(
2. {
3. loc: {
4. $geoIntersects: {
5. $geometry: {
6. type: "Triangle" ,
7. coordinates: [
8. [ [ 0, 0 ], [ 3, 6 ], [ 6, 1 ] ]
9. ]
10. }
11. }
12. }
13. }

$geoWithin
The geoWithin operator chooses the document with geospatial data that exists entirely
within a specified shape.

Syntax:

1. {
2. <location field>: {
3. $geoWithin: {
4. $geometry: {
5. type: <"Triangle" or "Rectangle"> ,
6. coordinates: [ <coordinates> ]
7. }
8. }
9. }

$near
The near operator defines a point for which a geospatial query returns the documents from
close to far.

Syntax:

1. {
2. <location field>: {
3. $near: {
4. $geometry: {
5. type: "Point" ,
6. coordinates: [ <longitude> , <latitude> ]
7. },
8. $maxDistance: <distance in meters>,
9. $minDistance: <distance in meters>
10. }
11. }
Example:

1. db.places.find(
2. {
3. location:
4. { $near :
5. {
6. $geometry: { type: "Point", coordinates: [ -73.9667, 40.78 ] },
7. $minDistance: 1000,
8. $maxDistance: 5000
9. }
10. }
11. }

$nearSphere
The nearsphere operator specifies a point for which the geospatial query returns the
document from nearest to farthest.

Syntax:

1. {
2. $nearSphere: [ <x>, <y> ],
3. $minDistance: <distance in radians>,
4. $maxDistance: <distance in radians>
5. }
Example:

1. db.legacyPlaces.find(
2. { location : { $nearSphere : [ -73.9667, 40.78 ], $maxDistance: 0.10 } }
3. )

$all
It chooses the document where the value of a field is an array that contains all the specified
elements.

Syntax:

1. { <field>: { $all: [ <value1> , <value2> ... ] } }


Example:

1. db.books.find( { tags: { $all: [ "Java", "MongoDB", "RDBMS" ] } } )

$elemMatch
The operator relates documents that contain an array field with at least one element that
matches with all the given query criteria.
Syntax:

1. { <field>: { $elemMatch: { <query1>, <query2>, ... } } }


Example:

1. db.books.find(
2. { results: { $elemMatch: { $gte: 500, $lt: 400 } } }
3. )

$size
It selects any array with the number of the element specified by the argument.

Syntax:

1. db.collection.find( { field: { $size: 2 } } );

MongoDB Bitwise Operator

$bitsAllClear
It matches the documents where all the bit positions given by the query are clear infield.

Syntax:

1. { <field>: { $bitsAllClear: <numeric bitmask> } }


Example:

1. db.inventory.find( { a: { $bitsAllClear: [ 1, 5 ] } } )

$bitsAllSet
The bitallset operator matches the documents where all the bit positions given by the
query are set in the field.

Syntax:

1. { <field>: { $bitsAllSet: <numeric bitmask> } }


Example:

1. db.inventory.find( { a: { $bitsAllClear: [ 1, 5 ] } } )

$bitsAnyClear
The bitAnyClear operator matches the document where any bit of positions given by the
query is clear in the field.

Syntax:
1. { <field>: { $bitsAnyClear: <numeric bitmask> } }
Example:

1. db.inventory.find( { a: { $bitsAnyClear: [ 5, 10 ] } } )

$bitsAnySet
It matches the document where any of the bit positions given by the query are set in the
field.

Syntax:

1. { <field>: { $bitsAnySet: <numeric bitmask> } }


Example:

1. db.inventory.find( { a: { $bitsAnySet: [ 1, 5 ] } } )

MongoDB comments operator

$comment
The $comment operator associates a comment to any expression taking a query
predicate.

Syntax:

1. db.inventory.find( { <query>, $comment: <comment> } )


Example:

1. db.inventory.find(
2. {
3. x: { $mod: [ 1, 0 ] },
4. $comment: "Find Odd values."
5. }

MongoDB Projection Operator

$
The $ operator limits the contents of an array from the query results to contain only the
first element matching the query document.

Syntax:

1. db.books.find( { <array>: <value> ... },


2. { "<array>.$": 1 } )
3. db.books.find( { <array.field>: <value> ...},
4. { "<array>.$": 1 } )

$elemMatch
The content of the array field made limited using this operator from the query result to
contain only the first element matching the element $elemMatch condition.

Syntax:

1. db.library.find( { bookcode: "63109" },


2. { students: { $elemMatch: { roll: 102 } } } )

$meta
The meta operator returns the result for each matching document where the metadata
associated with the query.

Syntax:

1. { $meta: <metaDataKeyword> }
Example:

1. db.books.find(
2. <query>,
3. { score: { $meta: "textScore" } }

$slice
It controls the number of values in an array that a query returns.

Syntax:

1. db.books.find( { field: value }, { array: {$slice: count } } );


Example:

1. db.books.find( {}, { comments: { $slice: [ 200, 100 ] } } )

Node.js - MongoDB Create Database

MongoDB is an open-source, cross-platform document-oriented database


environment. MongoDB uses JSON-like, schema-free documents. More than
one documents form a collection, and one or more collections may be
present in a MongoDB database. In this chapter, we whall learn how to
create a MongoDB database with a Node.js application.

The MongoDB database management software is available in the following


three editions −
MongoDB Community − The source-available, free-to-use, and self-managed
version of MongoDB, available for local installation, available for Windows,
Linux, and macOS.

MongoDB Enterprise − A commercial, subscription-based, self-managed


version of MongoDB, with a lot of advanced features than the community
edition.

MongoDB Atlas − An on-demand, fully managed service for MongoDB


deployments in the cloud. It runs on AWS, Microsoft Azure, and Google Cloud
Platform.

Connection strings
The mongodb driver for Node.js is imported into the code with the require()
function. The object of MongoClient class represents a database connection.
You need to pass a connection string to its constructor.

const { MongoClient } = require('mongodb');


const client = new MongoClient(ConnectionString);

The MongoDB connection string must be one of the following formats −

Standard Connection String Format − This format is used to connect to a self-


hosted MongoDB standalone deployment, replica set, or sharded cluster. The
standard URI connection scheme has the form −

mongodb://[username:password@]host1[:port1][,...hostN[:portN]][/[defaultauthdb][?options]]

The default connection string is −

mongodb://localhost:27017/

SRV Connection Format − A connection string with a hostname that


corresponds to a DNS SRV record. MongoDB Atlas uses SRV connection
format. MongoDB supports a DNS-constructed seed list. It allows more
flexibility of deployment and the ability to change the servers in rotation
without reconfiguring clients. The SRV URI connection scheme has the
following form −

mongodb+srv://[username:password@]host[/[defaultauthdb][?options]]

Here is an example of SRV connection string −

const uri =
"mongodb+srv://user:[email protected]/?retryWrites=true&w=majority";
In the following example, we are using the standard connection string to
fetch the list of databases.

Example: List of databases


The connect() method of MongoClient object returns a Promise. The call to
connect() method is asynchronous. Next a function listdatabases() is called.

const { MongoClient } = require('mongodb');

async function main() {


const uri = "mongodb://localhost:27017/";

const client = new MongoClient(uri);


try {
// Connect to the MongoDB cluster
await client.connect();

// Make the appropriate DB calls


await listDatabases(client);
} catch (e) {
console.error(e);
} finally {
// Close the connection to the MongoDB cluster
await client.close();
}
}

main().catch(console.error);

async function listDatabases(client) {


databasesList = await client.db().admin().listDatabases();
console.log("Databases:");
databasesList.databases.forEach(db => console.log(` - ${db.name}`));
};

Output

Databases:
- admin
- config
- local
- myProject
- mydb

Explore our latest online courses and learn new skills at your own pace. Enroll
and become a certified expert to boost your career.

Create a new database


To create a new database on the server, you need to call the db() method of
MongoClient class.

var dbobj = client.db(database_name, options);

The db() method returns a db instance that represents the database on the
server. In the following example, we have demonstrated how to create a new
database named as mydatabase in MongoDB.

const {MongoClient} = require('mongodb');

async function main(){


const uri = "mongodb://localhost:27017/mydb";
const client = new MongoClient(uri);

try {
// Connect to the MongoDB cluster
await client.connect();
await createdb(client, "mydatabase");
} finally {
// Close the connection to the MongoDB cluster
await client.close();
}
}

main().catch(console.error);

async function createdb(client, dbname){


const dbobj = await client.db(dbname);
console.log("Database created");
console.log(dbobj);
}

However, note that the database is not physically created on the server till at
least one collection is created and there should be at least one document in
it.

MongoDB CRUD Operations


CRUD Operations (Create, Read, Update, and Delete) are the basic set of
operations that allow users to interact with the MongoDB server.
As we know, to use MongoDB we need to interact with the MongoDB server
to perform certain operations like entering new data into the application,
updating data into the application, deleting data from the application, and

reading the application .

4 major operations– CREATE, READ, UPDATE, and DELETE that form


the CRUD operations in MongoDB.
Perform CRUD Operations in MongoDB
Now that we know the components of the CRUD operation, let’s learn about
each individual operation in MongoDB. We will know what each operation
does, and the methods to perform these operations in MongoDB.
We will create, read, update and delete documents from MongoDB server.
1. Create Operations
The create or insert operations are used to insert or add new documents
in the collection. If a collection does not exist, then it will create a new
collection in the database.
You can perform, create operations using the following methods provided
by the MongoDB:
Method Description

It is used to insert a single document in the


db.collection.insertOne() collection.

It is used to insert multiple documents in the


db.collection.insertMany() collection.

db.createCollection() It is used to create an empty collection.

Create Operations Example


Let’s look at some examples of the Create operation from CRUD in
MongoDB.
Example 1: In this example, we are inserting details of a single student in
the form of document in the student collection
using db.collection.insertOne() method.
Example 2: In this example, we are inserting details of the multiple students
in the form of documents in the student collection
using db.collection.insertMany() method.
2. Read Operations
The Read operations are used to retrieve documents from the collection,
or in other words, read operations are used to query a collection for a
document.
You can perform read operation using the following method provided by
the MongoDB:
Method Description

db.collection.find() It is used to retrieve documents from the collection.

Note: pretty() method is used to decorate the result such that it


is easy to read.
Read Operations Example
Let’s look at some examples of Read operation from CRUD in MongoDB.
Example: In this example, we are retrieving the details of students from the
student collection using db.collection.find() method.
3. Update Operations
The update operations are used to update or modify the existing document
in the collection. You can perform update operations using the following
methods provided by the MongoDB:
Method Description

It is used to update a single document in the


db.collection.updateOne() collection that satisfy the given criteria.

It is used to update multiple documents in


db.collection.updateMany() the collection that satisfy the given criteria.

It is used to replace single document in the


db.collection.replaceOne() collection that satisfy the given criteria.

Update Operations Example


Let’s look at some examples of the update operation from CRUD in
MongoDB.
Example 1: In this example, we are updating the age of Sumit in the student
collection using db.collection.updateOne() method.
Example 2: In this example, we are updating the year of course in all the
documents in the student collection
using db.collection.updateMany() method.
4. Delete Operations
The delete operation are used to delete or remove the documents from a
collection. You can perform delete operations using the following methods
provided by the MongoDB:
Method Description

It is used to delete a single document from


db.collection.deleteOne() the collection that satisfy the given criteria.

It is used to delete multiple documents from


db.collection.deleteMany() the collection that satisfy the given criteria.

Delete Operations Examples


Let’s look at some examples of delete operation from CRUD in MongoDB.
Example 1: In this example, we are deleting a document from the student
collection using db.collection.deleteOne() method.
Example 2: In this example, we are deleting all the documents from the
student collection using db.collection.deleteMany() method.

You might also like