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

Node JS

Node.js is an open-source, cross-platform JavaScript runtime environment that enables server-side JavaScript execution, utilizing an efficient, non-blocking I/O model. It is widely used for building back-end services and applications, allowing for dynamic content generation and database interaction. The document also covers installation, the REPL environment, package management with npm, and the event-driven architecture of Node.js.

Uploaded by

hodcs2
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)
15 views59 pages

Node JS

Node.js is an open-source, cross-platform JavaScript runtime environment that enables server-side JavaScript execution, utilizing an efficient, non-blocking I/O model. It is widely used for building back-end services and applications, allowing for dynamic content generation and database interaction. The document also covers installation, the REPL environment, package management with npm, and the event-driven architecture of Node.js.

Uploaded by

hodcs2
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

lOMoARcPSD|60855493

What is [Link]?

[Link] is an open-source, cross-platform JavaScript runtime environment that allows developers


to run JavaScript code on the server side. Created by Ryan Dahl in 2009, [Link] has
revolutionized server-side programming by offering an efficient, event-driven, and non-blocking
I/O model.
• [Link] is an open source server environment

• [Link] is free

• [Link] runs on various platforms (Windows, Linux, Unix, Mac OS X, etc.)

• [Link] uses JavaScript on the server

It’s a powerful tool used for various types of projects. Let’s explore some key aspects:
• JavaScript Runtime: [Link] runs on the V8 JavaScript engine, which is also the
core engine behind Google Chrome.
• Single Process Model: A [Link] application operates within a single process,
avoiding the need to create a new thread for every request.
• Asynchronous I/O: [Link] provides a set of asynchronous I/O primitives in its
standard library. These primitives prevent JavaScript code from blocking, making
non-blocking behavior the norm.
• Concurrency Handling: [Link] efficiently handles thousands of concurrent
connections using a single server. It avoids the complexities of managing thread
concurrency, which can lead to bugs.
• JavaScript Everywhere: Frontend developers familiar with JavaScript can
seamlessly transition to writing server-side code using [Link].
• ECMAScript Standards: [Link] supports the latest ECMAScript standards. You can
choose the version you want to use, independent of users’ browser updates.

Why [Link]?

[Link] 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.
[Link] uses asynchronous programming!
A common task for a web server can be to open a file on the server and return the content to the
client.

Downloaded by HOD CSE 2 (hodcs2@[Link])


lOMoARcPSD|60855493

Here is how PHP or ASP handles a file request:

1. Sends the task to the computer's file system.

2. Waits while the file system opens and reads the file.

3. Returns the content to the client.

4. Ready to handle the next request.

Here is how [Link] handles a file request:

1. Sends the task to the computer's file system.

2. Ready to handle the next request.

3. When the file system has opened and read the file, the server returns the content to the
client.

[Link] eliminates the waiting, and simply continues with the next request.

[Link] runs single-threaded, non-blocking, asynchronous programming, which is very memory


efficient.

What Can [Link] Do?

• [Link] can generate dynamic page content

• [Link] can create, open, read, write, delete, and close files on the server

• [Link] can collect form data

• [Link] can add, delete, modify data in your database

What is a [Link] File?

• [Link] files contain tasks that will be executed on certain events

• A typical event is someone trying to access a port on the server

• [Link] files must be initiated on the server before having any effect

• [Link] files have extension ".js"

Downloaded by HOD CSE 2 (hodcs2@[Link])


lOMoARcPSD|60855493

Local Environment Setup

If you are still willing to set up your environment for [Link], this section will guide you. [Link] can
be installed on different OS platforms such as Windows, Linux, Mac OS X, etc. You need the
following tools on your computer −

• The [Link] binary installer

• Node Package Manager (NPM)

• IDE or Text Editor

Binaries for various OS platforms are available on the downloads page of the official website of
[Link]. Visit [Link] get the list.

This page shows two sets of binaries for different OS platforms, one for the current or latest version,
and the other a version with LTS (Long Term Support), that is recommended for a normal user. 32 bit
and 64 bit installers as well as ZIP archives for Windows, macOS installer as well as tar archives
and binaries for Linux OS on x64 and ARM architecture are available.

Downloaded by HOD CSE 2 (hodcs2@[Link])


lOMoARcPSD|60855493

Installation on Windows

Assuming that you are working with Windows 10/Windows 11 powered computer, download the 64-
bit installer for Windows: [Link] and start the
installation b double-clicking the downloaded file.

The installation takes you through a few steps of the installation wizard. It also adds the installation
directory of [Link] executable to the system path.

To verify if [Link] has been successfully installed, open the command prompt and type node -v. If
[Link] is installed successfully then it will display the version of the [Link] installed on your
machine, as shown below.

Downloaded by HOD CSE 2 (hodcs2@[Link])


lOMoARcPSD|60855493

REPL Terminal
The [Link] REPL (Read-Eval-Print-Loop) is an interactive shell that allows you to run JavaScript
code directly in your terminal without having to create a separate file.
The term REPL stands for Read Eval Print and Loop. It specifies a computer environment like a
window console or a Unix/Linux shell where you can enter the commands and the system responds
with an output in an interactive mode.
REPL Environment
The [Link] or node come bundled with REPL environment. Each part of the REPL environment
has a specific work.
Read: It reads user's input; parse the input into JavaScript data-structure and stores in memory.
Eval: It takes and evaluates the data structure.
Print: It prints the result.
Loop: It loops the above command until user press ctrl-c twice.
How to start REPL
You can start REPL by simply running "node" on the command prompt. See this:

You can execute various mathematical operations on REPL [Link] command prompt:
[Link] Simple expressions
After starting REPL node command prompt put any mathematical expression:
1. Example: >10+20-5
2. 25

Downloaded by HOD CSE 2 (hodcs2@[Link])


lOMoARcPSD|60855493

1. Example2: >10+12 + (5*4)/7

Using variable
Variables are used to store values and print later. If you don't use var keyword then
value is stored in the variable and printed whereas if var keyword is used then the value
is stored but not printed. You can print variables using [Link] ().

Downloaded by HOD CSE 2 (hodcs2@[Link])


lOMoARcPSD|60855493

Example:

[Link] Multiline expressions


Node REPL supports multiline expressions like JavaScript. See the following do-while
loop example:
1. var x = 0
2. undefined
3. > do {
4. ... x++;
5. ... [Link]("x: " + x);
6. ... } while ( x < 10 );

Downloaded by HOD CSE 2 (hodcs2@[Link])


lOMoARcPSD|60855493

[Link] Underscore Variable


You can also use underscore _ to get the last result.
Example:

[Link] REPL Commands

Commands Description

ctr + c It is used to terminate the current command.

Downloaded by HOD CSE 2 (hodcs2@[Link])


lOMoARcPSD|60855493

ctrl + c twice It terminates the node repl.

ctrl + d It terminates the node repl.

It is used to see command history and modify previous


up/down keys
commands.

tab keys It specifies the list of current command.

.help It specifies the list of all commands.

.break It is used to exit from multi-line expressions.

.clear It is used to exit from multi-line expressions.

.save filename It saves current node repl session to a file.

.load filename It is used to load file content in current node repl session.

[Link] Exit REPL


Use ctrl + c command twice to come out of [Link] REPL.

Downloaded by HOD CSE 2 (hodcs2@[Link])


lOMoARcPSD|60855493

[Link] Package Manager


Node Package Manager provides two main functionalities:
o It provides online repositories for [Link] packages/modules which are
searchable on [Link]
o It also provides command line utility to install [Link] packages, do version
management and dependency management of [Link] packages.
The npm comes bundled with [Link] installables in versions after that v0.6.3. You can
check the version by opening [Link] command prompt and typing the following
command:
1. npm version

Installing Modules using npm


Following is the syntax to install any [Link] module:
1. npm install <Module Name>
Let's install a famous [Link] web framework called express:
Open the [Link] command prompt and execute the following command:
1. npm install express
You can see the result after installing the "express" framework.

Downloaded by HOD CSE 2 (hodcs2@[Link])


lOMoARcPSD|60855493

Global vs Local Installation


By default, npm installs dependency in local mode. Here local mode specifies the folder
where Node application is present. For example if you installed express module, it
created node_modules directory in the current directory where it installed express
module.

Downloaded by HOD CSE 2 (hodcs2@[Link])


lOMoARcPSD|60855493

You can use npm ls command to list down all the locally installed modules.
Open the [Link] command prompt and execute "npm ls":

Downloaded by HOD CSE 2 (hodcs2@[Link])


lOMoARcPSD|60855493

Globally installed packages/dependencies are stored in system directory. Let's install


express module using global installation. Although it will also produce the same result
but modules will be installed globally.
Open [Link] command prompt and execute the following code:
1. npm install express -g

Downloaded by HOD CSE 2 (hodcs2@[Link])


lOMoARcPSD|60855493

Here first line tells about the module version and its location where it is getting installed.
Uninstalling a Module
To uninstall a [Link] module, use the following command:
1. npm uninstall express

Downloaded by HOD CSE 2 (hodcs2@[Link])


lOMoARcPSD|60855493

The [Link] module is uninstalled. You can verify by using the following command:
1. npm ls

You can see that the module is empty now.

Downloaded by HOD CSE 2 (hodcs2@[Link])


lOMoARcPSD|60855493

Searching a Module
"npm search express" command is used to search express or module.
1. npm search express

Downloaded by HOD CSE 2 (hodcs2@[Link])


lOMoARcPSD|60855493

Downloaded by HOD CSE 2 (hodcs2@[Link])


lOMoARcPSD|60855493

Callbacks Concept
In [Link], a callback function is a function that is passed as an argument to another
function and is executed after the completion of a specific task or operation. Callbacks
are fundamental to the asynchronous nature of [Link], allowing for non-blocking
operations and enabling efficient handling of I/O operations and other time-consuming
tasks.

Downloaded by HOD CSE 2 (hodcs2@[Link])


lOMoARcPSD|60855493

Here's how it works:

• Asynchronous Operations:
[Link] heavily relies on asynchronous operations, meaning that tasks like reading
files, making network requests, or interacting with databases don't block the
execution of the rest of the code. Instead, these operations are initiated, and the
program continues to execute other code while waiting for the operation to complete.
• Passing the Callback:
When you initiate an asynchronous operation, you typically pass a callback function
as an argument. This callback function will be called once the operation is finished.
• Callback Execution:
When the asynchronous operation completes, the callback function is executed. This
function can then handle the results of the operation, such as processing data or
handling errors.
Example (Reading a File):
JavaScript
const fs = require('fs');

[Link]('[Link]', 'utf-8', (err, data) => {


if (err) {
[Link]('Error reading file:', err);
return;
}

[Link]('File content:', data);


});

[Link]('This line will execute before the file is read.');

Explanation:
• [Link] is an asynchronous file reading function.
• We pass a callback function as the third argument, which takes two
parameters: err (for errors) and data (the file content).
• The code continues to execute, printing "This line will execute before the file is
read."
• Once the file reading is complete, the callback function is invoked, either
handling the error (err) or printing the file content (data).
Benefits of Callbacks:

Downloaded by HOD CSE 2 (hodcs2@[Link])


lOMoARcPSD|60855493

• Non-blocking I/O:
Callbacks enable [Link] to handle multiple I/O operations concurrently without
blocking the main execution thread, making it highly scalable.
• Efficient Resource Utilization:
[Link] can efficiently utilize system resources while waiting for asynchronous
operations to complete.
• Simplified Asynchronous Code:
Callbacks provide a structured way to handle asynchronous operations, making the
code more readable and manageable than nested callbacks (callback hell).
Alternatives to Callbacks:
• Promises:
A more modern way to handle asynchronous operations, providing better error
handling and chaining capabilities.
• Async/Await:
A syntactic sugar on top of Promises, making asynchronous code look more like
synchronous code.

[Link] Events
[Link] is built on an event-driven architecture that allows you to build
highly scalable applications. Understanding the event-driven nature of
[Link] and how to work with events is important for building efficient and
responsive applications.
What Are Events in [Link]?
In [Link], an event is an action or occurrence that the program can detect
and handle. The event-driven architecture allows asynchronous
programming, and your application becomes able to perform non-blocking
operations. This means that while waiting for an operation to complete (like
reading a file or making a network request), the application can continue
processing other tasks.
EventEmitter Class
At the core of the [Link] event system is the EventEmitter class. This class
allows objects to emit named events that can be listened to by other parts of
your application. It is included in the built-in events module.

Downloaded by HOD CSE 2 (hodcs2@[Link])


lOMoARcPSD|60855493

Key Features of EventEmitter:


• Event Registration: You can register listeners for specific events
using the on() method.
• Event Emission: Use the emit() method to trigger an event and call
all registered listeners for that event.
• Asynchronous Execution: Listeners can execute asynchronously,
allowing other operations to continue while waiting for events.
Syntax:
const EventEmitter=require('events');
var eventEmitter=new EventEmitter();
Working with Events in [Link]
Step 1: Importing the Events Module
To start using events in your application, you need to import the events
module and create an instance of the EventEmitter class.
const EventEmitter = require('events');
const myEmitter = new EventEmitter();
Step 2: Registering Event Listeners
You can register listeners for specific events using the on() method. The first
argument is the event name, and the second argument is the callback
function to be executed when the event is emitted.
[Link]('event', () => {
[Link]('An event occurred!');
});
Step 3: Emitting Events
To trigger an event, use the emit() method with the event name as the first
argument.
[Link]('event'); // Output: An event occurred!
Listening events
Before emitting any event, it must register functions(callbacks) to listen to
the events.
Syntax:
[Link](event, listener)
[Link](event, listener)
[Link](event, listener)
Removing Listener
The [Link]() takes two argument event and listener,
and removes that listener from the listeners array that is subscribed to that

Downloaded by HOD CSE 2 (hodcs2@[Link])


lOMoARcPSD|60855493

event. While [Link]() removes all the listener


from the array which are subscribed to the mentioned event.
Syntax:
[Link](event, listener)
[Link]([event])
Note:
• Removing the listener from the array will change the sequence of
the listener’s array, hence it must be carefully used.
• The [Link]() will remove at most one
instance of the listener which is in front of the queue.

// Importing events
const EventEmitter = require('events');
// Initializing event emitter instances
var eventEmitter = new EventEmitter();
var fun1 = (msg) => {
[Link]("Message from fun1: " + msg);
};
var fun2 = (msg) => {
[Link]("Message from fun2: " + msg);
};
// Registering fun1 and fun2
[Link]('myEvent', fun1);
[Link]('myEvent', fun1);
[Link]('myEvent', fun2);
// Removing listener fun1 that was
// registered on the line 13
[Link]('myEvent', fun1);
// Triggering myEvent
[Link]('myEvent', "Event occurred");
// Removing all the listeners to myEvent
[Link]('myEvent');

Downloaded by HOD CSE 2 (hodcs2@[Link])


lOMoARcPSD|60855493

// Triggering myEvent
[Link]('myEvent', "Event occurred");

Output:
Message from fun1: Event occurred
Message from fun2: Event occurred

[Link]()
It returns an array of listeners for the specified event.
Syntax:
[Link](event)
[Link]()
It returns the number of listeners listening to the specified event.
Syntax:
[Link](event)
[Link]()
It will add the one-time listener to the beginning of the array.
Syntax:
[Link](event, listener)
[Link]()
It will add the listener to the beginning of the array.
Syntax:
[Link](event, listener)

Special Events
All EventEmitter instances emit the event ‘newListener’ when new listeners
are added and ‘removeListener’ existing listeners are removed.
• Event: ‘newListener’ The EventEmitter instance will emit its own
‘newListener’ event before a listener is added to its internal array
of listeners. Listeners registered for the ‘newListener’ event will be
passed to the event name and reference to the listener being

Downloaded by HOD CSE 2 (hodcs2@[Link])


lOMoARcPSD|60855493

added. The event ‘newListener’ is triggered before adding the


listener to the array.
[Link]( 'newListener', listener)
[Link]( 'newListener', listener)
• Event: ‘removeListener’ The ‘removeListener’ event is emitted
after a listener is removed.
[Link]( ‘removeListener’, listener)
[Link]( 'removeListener’, listener)
• Event: ‘error’ When an error occurs within an EventEmitter
instance, the typical action is for an ‘error’ event to be emitted. If
an EventEmitter does not have at least one listener registered for
the ‘error’ event, and an ‘error’ event is emitted, the error is thrown,
a stack trace is printed, and the [Link] process exits.
[Link]('error', listener)

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

[Link] 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 [Link] 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
[Link] 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.

Downloaded by HOD CSE 2 (hodcs2@[Link])


lOMoARcPSD|60855493

The [Link] is built on top of the connect middleware, which in turn is based
on http, one of the core modules of [Link] API.

Installing Express
The [Link] 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.

[Link] - RESTful API

A [Link] application using ExpressJS is ideally suited for building REST APIs. In this chapter,
we shall explain what is a REST (also called RESTFul) API, and build a [Link] based, [Link]
REST application. We shall also use REST clients to test out REST API.

API is an acronym for Application Programming Interface. The word interface generally refers to
a common meeting ground between two isolated and independent environments. A programming
interface is an interface between two software applications. The term REST API or RESTFul API
is used for a web Application that exposes its resources to other web/mobile applications through
the Internet, by defining one or more endpoints which the client apps can visit to perform
read/write operations on the host's resources.

Downloaded by HOD CSE 2 (hodcs2@[Link])


lOMoARcPSD|60855493

REST architecture has become the de facto standard for building APIs, preferred by the developers
over other technologies such as RPC, (stands for Remote Procedure Call), and SOAP (stands for
Simple Object Access Protocol).

What is REST architecture?


REST stands for REpresentational State Transfer. REST is a well known software architectural
style. It defines how the architecture of a web application should behave. It is a resource based
architecture where everything that the REST server hosts, (a file, an image, or a row in a table of
a database), is a resource, having many representations. REST was first introduced by Roy Fielding
in 2000.

REST recommends certain architectural constraints.

• Uniform interface
• Statelessness
• Client-server
• Cacheability
• Layered system
• Code on demand

These are the advantages of REST constraints −

• Scalability
• Simplicity
• Modifiability
• Reliability
• Portability
• Visibility

A REST Server provides access to resources and REST client accesses and modifies the resources
using HTTP protocol. Here each resource is identified by URIs/ global IDs. REST uses various
representation to represent a resource like text, JSON, XML but JSON is the most popular one.

HTTP methods
Following four HTTP methods are commonly used in REST based architecture.

POST Method
The POST verb in the HTTP request indicates that a new resource is to be created on the server.
It corresponds to the CREATE operation in the CRUD (CREATE, RETRIEVE, UPDATE and
DELETE) term. To create a new resource, you need certain data, it is included in the request as a
data header.

Downloaded by HOD CSE 2 (hodcs2@[Link])


lOMoARcPSD|60855493

Examples of POST request −

HTTP POST [Link]


HTTP POST [Link]

GET Method
The purpose of the GET operation is to retrieve an existing resource on the server and return its
XML/JSON representation as the response. It corresponds to the READ part in the CRUD term.

Examples of a GET request −

HTTP GET [Link]


HTTP GET [Link]

PUT Method
The client uses HTTP PUT method to update an existing resource, corresponding to the
UPDATE part in CRUD). The data required for update is included in the request body.

Examples of a PUT request −

HTTP PUT [Link]


HTTP PUT [Link]

DELETE Method
The DELETE method (as the name suggest) is used to delete one or more resources on the
server. On successful execution, an HTTP response code 200 (OK) is sent.

Examples of a DELETE request −

HTTP DELETE [Link]


HTTP DELETE [Link]

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

RESTful Web Services

Downloaded by HOD CSE 2 (hodcs2@[Link])


lOMoARcPSD|60855493

Web services based on REST Architecture are known as RESTful web services. These
webservices uses HTTP methods to implement the concept of REST architecture. A RESTful
web service usually defines a URI, Uniform Resource Identifier a service, which provides
resource representation such as JSON and set of HTTP Methods.

Creating RESTful API for A Library


Consider we have a JSON based database of users having the following users in a file [Link]:

{
"user1" : {
"name" : "mahesh",
"password" : "password1",
"profession" : "teacher",
"id": 1
},

"user2" : {
"name" : "suresh",
"password" : "password2",
"profession" : "librarian",
"id": 2
},

"user3" : {
"name" : "ramesh",
"password" : "password3",
"profession" : "clerk",
"id": 3
}
}

Our API will expose the following endpoints for the clients to perform CRUD operations on the
[Link] file, which the collection of resources on the server.

[Link]. URI HTTP Method POST body Result

Downloaded by HOD CSE 2 (hodcs2@[Link])


lOMoARcPSD|60855493

1 / GET empty Show list of all the users.

2 / POST JSON String Add details of new user.

3 /:id DELETE JSON String Delete an existing user.

4 /:id GET empty Show details of a user.

5 /:id PUT JSON String Update an existing user

List Users
Let's implement the first route in our RESTful API to list all Users using the following code in a
[Link] file

var express = require('express');


var app = express();
var fs = require("fs");
[Link]('/', function (req, res) {
[Link]( __dirname + "/" + "[Link]", 'utf8', function (err, data) {
[Link]( data );
});
})
var server = [Link](5000, function () {
[Link]("Express App running at [Link]
})

To test this endpoint, you can use a REST client such as Postman or Insomnia. In this chapter,
we shall use Insomnia client.

Run [Link] from command prompt, and launch the Insomnia client. Choose GET methos and
enter [Link] URL. The list of all users from [Link] will be displayed in the
Respone Panel on right.

Downloaded by HOD CSE 2 (hodcs2@[Link])


lOMoARcPSD|60855493

You can also use CuRL command line tool for sending HTTP requests. Open another terminal
and issue a GET request for the above URL.

C:\Users\mlath>curl [Link]
{
"user1" : {
"name" : "mahesh",
"password" : "password1",
"profession" : "teacher",
"id": 1
},

"user2" : {
"name" : "suresh",
"password" : "password2",
"profession" : "librarian",
"id": 2
},

Downloaded by HOD CSE 2 (hodcs2@[Link])


lOMoARcPSD|60855493

"user3" : {
"name" : "ramesh",
"password" : "password3",
"profession" : "clerk",
"id": 3
}
}

Show Detail
Now we will implement an API endpoint /:id which will be called using user ID and it will
display the detail of the corresponding user.

Add the following method in [Link] file −

[Link]('/:id', function (req, res) {


[Link]( __dirname + "/" + "[Link]", 'utf8', function (err, data) {
var users = [Link]( data );
var user = users["user" + [Link]]
[Link]( [Link](user));
});
})

In the Insomnia interface, enter [Link] and send the request.

You may also use the CuRL command as follows to display the details of user2 −

C:\Users\mlath>curl [Link]
{"name":"suresh","password":"password2","profession":"librarian","id":2}

Add User
Following API will show you how to add new user in the list. Following is the detail of the new
user. As explained earlier, you must have installed body-parser package in your application
folder.

Downloaded by HOD CSE 2 (hodcs2@[Link])


lOMoARcPSD|60855493

var bodyParser = require('body-parser')


[Link]( [Link]() );
[Link]([Link]({ extended: true }));

[Link]('/', function (req, res) {


[Link]( __dirname + "/" + "[Link]", 'utf8', function (err, data) {
var users = [Link]( data );
var user = [Link].user4;
users["user"+[Link]] = user
[Link]( [Link](users));
});
})

To send POST request through Insomnia, set the BODY tab to JSON, and enter the the user data
in JSON format as shown

You will get a JSON data of four users (three read from the file, and one added)

{
"user1": {
"name": "mahesh",
"password": "password1",
"profession": "teacher",
"id": 1

Downloaded by HOD CSE 2 (hodcs2@[Link])


lOMoARcPSD|60855493

},
"user2": {
"name": "suresh",
"password": "password2",
"profession": "librarian",
"id": 2
},
"user3": {
"name": "ramesh",
"password": "password3",
"profession": "clerk",
"id": 3
},
"user4": {
"name": "mohit",
"password": "password4",
"profession": "teacher",
"id": 4
}
}

Delete user
The following function reads the ID parameter from the URL, locates the user from the list that
is obtained by reading the [Link] file, and the corresponding user is deleted.

[Link]('/:id', function (req, res) {


[Link]( __dirname + "/" + "[Link]", 'utf8', function (err, data) {
data = [Link]( data );
var id = "user"+[Link];
var user = data[id];
delete data[ "user"+[Link]];
[Link]( [Link](data));
});
})

Downloaded by HOD CSE 2 (hodcs2@[Link])


lOMoARcPSD|60855493

Choose DELETE request in Insomnia, enter [Link] and send the request. The
user with ID=3 will be deleted, the remaining users are listed in the response panel

Output

{
"user1": {
"name": "mahesh",
"password": "password1",
"profession": "teacher",
"id": 1
},
"user2": {
"name": "suresh",
"password": "password2",
"profession": "librarian",
"id": 2
}
}

Update user
The PUT method modifies an existing resource with the server. The following [Link]() method
reads the ID of the user to be updated from the URL, and the new data from the JSON body.

[Link]("/:id", function(req, res) {


[Link]( __dirname + "/" + "[Link]", 'utf8', function (err, data) {

var users = [Link]( data );


var id = "user"+[Link];
users[id]=[Link];
[Link]( [Link](users));
})
})

Downloaded by HOD CSE 2 (hodcs2@[Link])


lOMoARcPSD|60855493

In Insomnia, set the PUT method for [Link] URL.

The response shows the updated details of user with ID=2

{
"user1": {
"name": "mahesh",
"password": "password1",
"profession": "teacher",
"id": 1
},
"user2": {
"name": "suresh",
"password": "password2",
"profession": "Cashier",
"id": 2
},
"user3": {
"name": "ramesh",
"password": "password3",
"profession": "clerk",
"id": 3
}

Downloaded by HOD CSE 2 (hodcs2@[Link])


lOMoARcPSD|60855493

Here is the complete code for the [Link] RESTFul API −

var express = require('express');


var app = express();
var fs = require("fs");
var bodyParser = require('body-parser')
[Link]( [Link]() );
[Link]([Link]({ extended: true }));

[Link]('/', function (req, res) {


[Link]( __dirname + "/" + "[Link]", 'utf8', function (err, data) {
[Link]( data );
});
})

[Link]('/:id', function (req, res) {


[Link]( __dirname + "/" + "[Link]", 'utf8', function (err, data) {
var users = [Link]( data );
var user = users["user" + [Link]]
[Link]( [Link](user));
});
})

var bodyParser = require('body-parser')


[Link]( [Link]() );
[Link]([Link]({ extended: true }));

[Link]('/', function (req, res) {


[Link]( __dirname + "/" + "[Link]", 'utf8', function (err, data) {
var users = [Link]( data );
var user = [Link].user4;
users["user"+[Link]] = user
[Link]( [Link](users));

Downloaded by HOD CSE 2 (hodcs2@[Link])


lOMoARcPSD|60855493

});
})

[Link]('/:id', function (req, res) {


[Link]( __dirname + "/" + "[Link]", 'utf8', function (err, data) {
data = [Link]( data );
var id = "user"+[Link];
var user = data[id];
delete data[ "user"+[Link]];
[Link]( [Link](data));
});
})
[Link]("/:id", function(req, res) {
[Link]( __dirname + "/" + "[Link]", 'utf8', function (err, data) {

var users = [Link]( data );


var id = "user"+[Link];

users[id]=[Link];
[Link]( [Link](users));
})

})
var server = [Link](5000, function () {
[Link]("Express App running at [Link]
})
Print Page

[Link] MongoDB

MongoDB Create Database


Creating a Database

Downloaded by HOD CSE 2 (hodcs2@[Link])


lOMoARcPSD|60855493

To create a database in MongoDB, start by creating a MongoClient object, then


specify a connection URL with the correct ip address and the name of the database
you want to create.

MongoDB will create the database if it does not exist, and make a connection to
it.

Example
Create a database called "mydb":

var MongoClient = require('mongodb').MongoClient;


var url = "mongodb://localhost:27017/mydb";

[Link](url, function(err, db) {


if (err) throw err;
[Link]("Database created!");
[Link]();
});

Save the code above in a file called "demo_create_mongo_db.js" and run the file:

Run "demo_create_mongo_db.js"

C:\Users\Your Name>node demo_create_mongo_db.js

Which will give you this result:

Database created!

MongoDB waits until you have created a collection (table), with at least one
document (record) before it actually creates the database (and collection).

Create Collection
A collection in MongoDB is the same as a table in MySQL

Creating a Collection
To create a collection in MongoDB, use the createCollection() method:

Downloaded by HOD CSE 2 (hodcs2@[Link])


lOMoARcPSD|60855493

Example
Create a collection called "customers":

var MongoClient = require('mongodb').MongoClient;


var url = "mongodb://localhost:27017/";

[Link](url, function(err, db) {


if (err) throw err;
var dbo = [Link]("mydb");
[Link]("customers", function(err, res) {
if (err) throw err;
[Link]("Collection created!");
[Link]();
});
});

Save the code above in a file called "demo_mongodb_createcollection.js" and


run the file:

Run "demo_mongodb_createcollection.js"

C:\Users\Your Name>node demo_mongodb_createcollection.js

Which will give you this result:

Collection created!

MongoDB Insert
Insert Into Collection
To insert a record, or document as it is called in MongoDB, into a collection, we
use the insertOne() method.

A document in MongoDB is the same as a record in MySQL

The first parameter of the insertOne() method is an object containing the


name(s) and value(s) of each field in the document you want to insert.

It also takes a callback function where you can work with any errors, or the
result of the insertion:

Downloaded by HOD CSE 2 (hodcs2@[Link])


lOMoARcPSD|60855493

Example
Insert a document in the "customers" collection:

var MongoClient = require('mongodb').MongoClient;


var url = "mongodb://localhost:27017/";

[Link](url, function(err, db) {


if (err) throw err;
var dbo = [Link]("mydb");
var myobj = { name: "Company Inc", address: "Highway 37" };
[Link]("customers").insertOne(myobj, function(err, res) {
if (err) throw err;
[Link]("1 document inserted");
[Link]();
});
});

Save the code above in a file called "demo_mongodb_insert.js" and run the file:

Run "demo_mongodb_insert.js"

C:\Users\Your Name>node demo_mongodb_insert.js

Which will give you this result:

1 document inserted
Note: If you try to insert documents in a collection that do not exist, MongoDB
will create the collection automatically.

Insert Multiple Documents


To insert multiple documents into a collection in MongoDB, we use
the insertMany() method.

The first parameter of the insertMany() method is an array of objects,


containing the data you want to insert.

It also takes a callback function where you can work with any errors, or the
result of the insertion:

Example

Downloaded by HOD CSE 2 (hodcs2@[Link])


lOMoARcPSD|60855493

Insert multiple documents in the "customers" collection:

var MongoClient = require('mongodb').MongoClient;


var url = "mongodb://localhost:27017/";

[Link](url, function(err, db) {


if (err) throw err;
var dbo = [Link]("mydb");
var myobj = [
{ name: 'John', address: 'Highway 71'},
{ name: 'Peter', address: 'Lowstreet 4'},
{ name: 'Amy', address: 'Apple st 652'},
{ name: 'Hannah', address: 'Mountain 21'},
{ name: 'Michael', address: 'Valley 345'},
{ name: 'Sandy', address: 'Ocean blvd 2'},
{ name: 'Betty', address: 'Green Grass 1'},
{ name: 'Richard', address: 'Sky st 331'},
{ name: 'Susan', address: 'One way 98'},
{ name: 'Vicky', address: 'Yellow Garden 2'},
{ name: 'Ben', address: 'Park Lane 38'},
{ name: 'William', address: 'Central st 954'},
{ name: 'Chuck', address: 'Main Road 989'},
{ name: 'Viola', address: 'Sideway 1633'}
];
[Link]("customers").insertMany(myobj, function(err, res) {
if (err) throw err;
[Link]("Number of documents inserted: " + [Link]);
[Link]();
});
});

Save the code above in a file called "demo_mongodb_insert_multiple.js" and


run the file:

Run "demo_mongodb_insert_multiple.js"

C:\Users\Your Name>node demo_mongodb_insert_multiple.js

Which will give you this result:

Number of documents inserted: 14

The Result Object

Downloaded by HOD CSE 2 (hodcs2@[Link])


lOMoARcPSD|60855493

When executing the insertMany() method, a result object is returned.

The result object contains information about how the insertion affected the
database.

The object returned from the example above looked like this:

{
result: { ok: 1, n: 14 },
ops: [
{ name: 'John', address: 'Highway 71', _id: 58fdbf5c0ef8a50b4cdd9a84
},
{ name: 'Peter', address: 'Lowstreet 4', _id: 58fdbf5c0ef8a50b4cdd9a85
},
{ name: 'Amy', address: 'Apple st 652', _id: 58fdbf5c0ef8a50b4cdd9a86
},
{ name: 'Hannah', address: 'Mountain 21', _id:
58fdbf5c0ef8a50b4cdd9a87 },
{ name: 'Michael', address: 'Valley 345', _id:
58fdbf5c0ef8a50b4cdd9a88 },
{ name: 'Sandy', address: 'Ocean blvd 2', _id:
58fdbf5c0ef8a50b4cdd9a89 },
{ name: 'Betty', address: 'Green Grass 1', _id:
58fdbf5c0ef8a50b4cdd9a8a },
{ name: 'Richard', address: 'Sky st 331', _id:
58fdbf5c0ef8a50b4cdd9a8b },
{ name: 'Susan', address: 'One way 98', _id: 58fdbf5c0ef8a50b4cdd9a8c },
{ name: 'Vicky', address: 'Yellow Garden 2', _id:
58fdbf5c0ef8a50b4cdd9a8d },
{ name: 'Ben', address: 'Park Lane 38', _id: 58fdbf5c0ef8a50b4cdd9a8e },
{ name: 'William', address: 'Central st 954', _id:
58fdbf5c0ef8a50b4cdd9a8f },
{ name: 'Chuck', address: 'Main Road 989', _id:
58fdbf5c0ef8a50b4cdd9a90 },
{ name: 'Viola', address: 'Sideway 1633', _id:
58fdbf5c0ef8a50b4cdd9a91 } ],
insertedCount: 14,
insertedIds: [
58fdbf5c0ef8a50b4cdd9a84,
58fdbf5c0ef8a50b4cdd9a85,
58fdbf5c0ef8a50b4cdd9a86,
58fdbf5c0ef8a50b4cdd9a87,
58fdbf5c0ef8a50b4cdd9a88,
58fdbf5c0ef8a50b4cdd9a89,
58fdbf5c0ef8a50b4cdd9a8a,
58fdbf5c0ef8a50b4cdd9a8b,
58fdbf5c0ef8a50b4cdd9a8c,

Downloaded by HOD CSE 2 (hodcs2@[Link])


lOMoARcPSD|60855493

58fdbf5c0ef8a50b4cdd9a8d,
58fdbf5c0ef8a50b4cdd9a8e,
58fdbf5c0ef8a50b4cdd9a8f
58fdbf5c0ef8a50b4cdd9a90,
58fdbf5c0ef8a50b4cdd9a91 ]
}

The values of the properties can be displayed like this:

Example
Return the number of inserted documents:

[Link]([Link])

Which will produce this result:

14

The _id Field


If you do not specify an _id field, then MongoDB will add one for you and assign
a unique id for each document.

In the example above no _id field was specified, and as you can see from the
result object, MongoDB assigned a unique _id for each document.

If you do specify the _id field, the value must be unique for each document:

Example
Insert three records in a "products" table, with specified _id fields:

var MongoClient = require('mongodb').MongoClient;


var url = "mongodb://localhost:27017/";

[Link](url, function(err, db) {


if (err) throw err;
var dbo = [Link]("mydb");
var myobj = [
{ _id: 154, name: 'Chocolate Heaven'},
{ _id: 155, name: 'Tasty Lemon'},
{ _id: 156, name: 'Vanilla Dream'}

Downloaded by HOD CSE 2 (hodcs2@[Link])


lOMoARcPSD|60855493

];
[Link]("products").insertMany(myobj, function(err, res) {
if (err) throw err;
[Link](res);
[Link]();
});
});

Save the code above in a file called "demo_mongodb_insert_id.js" and run the
file:

Run "demo_mongodb_insert_id.js"

C:\Users\Your Name>node demo_mongodb_insert_id.js

Which will give you this result:

{
result: { ok: 1, n: 3 },
ops: [
{ _id: 154, name: 'Chocolate Heaven },
{ _id: 155, name: 'Tasty Lemon },
{ _id: 156, name: 'Vanilla Dream } ],
insertedCount: 3,
insertedIds: [
154,
155,
156 ]
}

MongoDB Find
In MongoDB we use the find and findOne methods to find data in a collection.

Just like the SELECT statement is used to find data in a table in a MySQL
database.

Find One
To select data from a collection in MongoDB, we can use the findOne() method.

The findOne() method returns the first occurrence in the selection.

Downloaded by HOD CSE 2 (hodcs2@[Link])


lOMoARcPSD|60855493

The first parameter of the findOne() method is a query object. In this example
we use an empty query object, which selects all documents in a collection (but
returns only the first document).

Example
Find the first document in the customers collection:

var MongoClient = require('mongodb').MongoClient;


var url = "mongodb://localhost:27017/";

[Link](url, function(err, db) {


if (err) throw err;
var dbo = [Link]("mydb");
[Link]("customers").findOne({}, function(err, result) {
if (err) throw err;
[Link]([Link]);
[Link]();
});
});

Save the code above in a file called "demo_mongodb_findone.js" and run the
file:

Run "demo_mongodb_findone.js"

C:\Users\Your Name>node demo_mongodb_findone.js

Which will give you this result:

Company Inc.

Find All
To select data from a table in MongoDB, we can also use the find() method.

The find() method returns all occurrences in the selection.

The first parameter of the find() method is a query object. In this example we
use an empty query object, which selects all documents in the collection.

No parameters in the find() method gives you the same result as SELECT * in
MySQL.

Downloaded by HOD CSE 2 (hodcs2@[Link])


lOMoARcPSD|60855493

Example
Find all documents in the customers collection:

var MongoClient = require('mongodb').MongoClient;


var url = "mongodb://localhost:27017/";

[Link](url, function(err, db) {


if (err) throw err;
var dbo = [Link]("mydb");
[Link]("customers").find({}).toArray(function(err, result) {
if (err) throw err;
[Link](result);
[Link]();
});
});

Save the code above in a file called "demo_mongodb_find.js" and run the file:

Run "demo_mongodb_find.js"

C:\Users\Your Name>node demo_mongodb_find.js

Which will give you this result:

[
{ _id: 58fdbf5c0ef8a50b4cdd9a84 , name: 'John', address: 'Highway 71'},
{ _id: 58fdbf5c0ef8a50b4cdd9a85 , name: 'Peter', address: 'Lowstreet
4'},
{ _id: 58fdbf5c0ef8a50b4cdd9a86 , name: 'Amy', address: 'Apple st 652'},
{ _id: 58fdbf5c0ef8a50b4cdd9a87 , name: 'Hannah', address: 'Mountain
21'},
{ _id: 58fdbf5c0ef8a50b4cdd9a88 , name: 'Michael', address: 'Valley
345'},
{ _id: 58fdbf5c0ef8a50b4cdd9a89 , name: 'Sandy', address: 'Ocean blvd
2'},
{ _id: 58fdbf5c0ef8a50b4cdd9a8a , name: 'Betty', address: 'Green Grass
1'},
{ _id: 58fdbf5c0ef8a50b4cdd9a8b , name: 'Richard', address: 'Sky st
331'},
{ _id: 58fdbf5c0ef8a50b4cdd9a8c , name: 'Susan', address: 'One way 98'},
{ _id: 58fdbf5c0ef8a50b4cdd9a8d , name: 'Vicky', address: 'Yellow Garden
2'},
{ _id: 58fdbf5c0ef8a50b4cdd9a8e , name: 'Ben', address: 'Park Lane 38'},
{ _id: 58fdbf5c0ef8a50b4cdd9a8f , name: 'William', address: 'Central st
954'},
{ _id: 58fdbf5c0ef8a50b4cdd9a90 , name: 'Chuck', address: 'Main Road

Downloaded by HOD CSE 2 (hodcs2@[Link])


lOMoARcPSD|60855493

989'},
{ _id: 58fdbf5c0ef8a50b4cdd9a91 , name: 'Viola', address: 'Sideway
1633'}
]

MongoDB Query
Filter the Result
When finding documents in a collection, you can filter the result by using a
query object.

The first argument of the find() method is a query object, and is used to limit
the search.

Example
Find documents with the address "Park Lane 38":

var MongoClient = require('mongodb').MongoClient;


var url = "mongodb://localhost:27017/";

[Link](url, function(err, db) {


if (err) throw err;
var dbo = [Link]("mydb");
var query = { address: "Park Lane 38" };
[Link]("customers").find(query).toArray(function(err, result) {
if (err) throw err;
[Link](result);
[Link]();
});
});

Save the code above in a file called "demo_mongodb_query.js" and run the file:

Run "demo_mongodb_query.js"

C:\Users\Your Name>node demo_mongodb_query.js

Which will give you this result:

Downloaded by HOD CSE 2 (hodcs2@[Link])


lOMoARcPSD|60855493

[
{ _id: 58fdbf5c0ef8a50b4cdd9a8e , name: 'Ben', address: 'Park Lane 38' }
]

Filter With Regular Expressions


You can write regular expressions to find exactly what you are searching for.

Regular expressions can only be used to query strings.

To find only the documents where the "address" field starts with the letter "S",
use the regular expression /^S/:

Example
Find documents where the address starts with the letter "S":

var MongoClient = require('mongodb').MongoClient;


var url = "mongodb://localhost:27017/";

[Link](url, function(err, db) {


if (err) throw err;
var dbo = [Link]("mydb");
var query = { address: /^S/ };
[Link]("customers").find(query).toArray(function(err, result) {
if (err) throw err;
[Link](result);
[Link]();
});
});

Save the code above in a file called "demo_mongodb_query_s.js" and run the
file:

Run "demo_mongodb_query_s.js"

C:\Users\Your Name>node demo_mongodb_query_s.js

Downloaded by HOD CSE 2 (hodcs2@[Link])


lOMoARcPSD|60855493

Which will give you this result:

[
{ _id: 58fdbf5c0ef8a50b4cdd9a8b , name: 'Richard', address: 'Sky st 331'
},
{ _id: 58fdbf5c0ef8a50b4cdd9a91 , name: 'Viola', address: 'Sideway 1633'
}
]

MongoDB Sort
Sort the Result
Use the sort() method to sort the result in ascending or descending order.

The sort() method takes one parameter, an object defining the sorting order.

Example
Sort the result alphabetically by name:

var MongoClient = require('mongodb').MongoClient;


var url = "mongodb://localhost:27017/";

[Link](url, function(err, db) {


if (err) throw err;
var dbo = [Link]("mydb");
var mysort = { name: 1 };
[Link]("customers").find().sort(mysort).toArray(function(err,
result) {
if (err) throw err;
[Link](result);
[Link]();
});
});

Save the code above in a file called "demo_sort.js" and run the file:

Run "demo_sort.js"

C:\Users\Your Name>node demo_sort.js

Which will give you this result:

Downloaded by HOD CSE 2 (hodcs2@[Link])


lOMoARcPSD|60855493

[
{ _id: 58fdbf5c0ef8a50b4cdd9a86, name: 'Amy', address: 'Apple st 652'},
{ _id: 58fdbf5c0ef8a50b4cdd9a8e, name: 'Ben', address: 'Park Lane 38'},
{ _id: 58fdbf5c0ef8a50b4cdd9a8a, name: 'Betty', address: 'Green Grass
1'},
{ _id: 58fdbf5c0ef8a50b4cdd9a90, name: 'Chuck', address: 'Main Road
989'},
{ _id: 58fdbf5c0ef8a50b4cdd9a87, name: 'Hannah', address: 'Mountain
21'},
{ _id: 58fdbf5c0ef8a50b4cdd9a84, name: 'John', address: 'Highway 71'},
{ _id: 58fdbf5c0ef8a50b4cdd9a88, name: 'Michael', address: 'Valley
345'},
{ _id: 58fdbf5c0ef8a50b4cdd9a85, name: 'Peter', address: 'Lowstreet 4'},
{ _id: 58fdbf5c0ef8a50b4cdd9a8b, name: 'Richard', address: 'Sky st
331'},
{ _id: 58fdbf5c0ef8a50b4cdd9a89, name: 'Sandy', address: 'Ocean blvd
2'},
{ _id: 58fdbf5c0ef8a50b4cdd9a8c, name: 'Susan', address: 'One way 98'},
{ _id: 58fdbf5c0ef8a50b4cdd9a8d, name: 'Vicky', address: 'Yellow Garden
2'},
{ _id: 58fdbf5c0ef8a50b4cdd9a91, name: 'Viola', address: 'Sideway
1633'},
{ _id: 58fdbf5c0ef8a50b4cdd9a8f, name: 'William', address: 'Central st
954'}
]

MongoDB Delete
Delete Document
To delete a record, or document as it is called in MongoDB, we use
the deleteOne() method.

The first parameter of the deleteOne() method is a query object defining which
document to delete.

Note: If the query finds more than one document, only the first occurrence is
deleted.

Example
Delete the document with the address "Mountain 21":

var MongoClient = require('mongodb').MongoClient;


var url = "mongodb://localhost:27017/";

Downloaded by HOD CSE 2 (hodcs2@[Link])


lOMoARcPSD|60855493

[Link](url, function(err, db) {


if (err) throw err;
var dbo = [Link]("mydb");
var myquery = { address: 'Mountain 21' };
[Link]("customers").deleteOne(myquery, function(err, obj) {
if (err) throw err;
[Link]("1 document deleted");
[Link]();
});
});

Save the code above in a file called "demo_delete.js" and run the file:

Run "demo_delete.js"

C:\Users\Your Name>node demo_delete.js

Which will give you this result:

1 document deleted

Delete Many
To delete more than one document, use the deleteMany() method.

The first parameter of the deleteMany() method is a query object defining


which documents to delete.

Example
Delete all documents were the address starts with the letter "O":

var MongoClient = require('mongodb').MongoClient;


var url = "mongodb://localhost:27017/";

[Link](url, function(err, db) {


if (err) throw err;
var dbo = [Link]("mydb");
var myquery = { address: /^O/ };
[Link]("customers").deleteMany(myquery, function(err, obj) {
if (err) throw err;
[Link]([Link].n + " document(s) deleted");

Downloaded by HOD CSE 2 (hodcs2@[Link])


lOMoARcPSD|60855493

[Link]();
});
});

Save the code above in a file called "demo_delete_many.js" and run the file:

Run "demo_delete_many.js"

C:\Users\Your Name>node demo_delete_many.js

Which will give you this result:

2 document(s) deleted

MongoDB Drop
Drop Collection
You can delete a table, or collection as it is called in MongoDB, by using
the drop() method.

The drop() method takes a callback function containing the error object and the
result parameter which returns true if the collection was dropped successfully,
otherwise it returns false.

Example
Delete the "customers" table:

var MongoClient = require('mongodb').MongoClient;


var url = "mongodb://localhost:27017/";

[Link](url, function(err, db) {


if (err) throw err;
var dbo = [Link]("mydb");
[Link]("customers").drop(function(err, delOK) {
if (err) throw err;
if (delOK) [Link]("Collection deleted");
[Link]();
});
})

Save the code above in a file called "demo_drop.js" and run the file:

Downloaded by HOD CSE 2 (hodcs2@[Link])


lOMoARcPSD|60855493

Run "demo_drop.js"

C:\Users\Your Name>node demo_drop.js

Which will give you this result:

Collection deleted

[Link]
You can also use the dropCollection() method to delete a table (collection).

The dropCollection() method takes two parameters: the name of the


collection and a callback function.

Example
Delete the "customers" collection, using dropCollection():

var MongoClient = require('mongodb').MongoClient;


var url = "mongodb://localhost:27017/";

[Link](url, function(err, db) {


if (err) throw err;
var dbo = [Link]("mydb");
[Link]("customers", function(err, delOK) {
if (err) throw err;
if (delOK) [Link]("Collection deleted");
[Link]();
});
});

Save the code above in a file called "demo_dropcollection.js" and run the file:

Run "demo_dropcollection.js"

C:\Users\Your Name>node demo_dropcollection.js

Which will give you this result:

Collection deleted

Downloaded by HOD CSE 2 (hodcs2@[Link])


lOMoARcPSD|60855493

MongoDB Update
Update Document
You can update a record, or document as it is called in MongoDB, by using
the updateOne() method.

The first parameter of the updateOne() method is a query object defining which
document to update.

Note: If the query finds more than one record, only the first occurrence is
updated.

The second parameter is an object defining the new values of the document.

Example
Update the document with the address "Valley 345" to name="Mickey" and
address="Canyon 123":

var MongoClient = require('mongodb').MongoClient;


var url = "mongodb://[Link]:27017/";

[Link](url, function(err, db) {


if (err) throw err;
var dbo = [Link]("mydb");
var myquery = { address: "Valley 345" };
var newvalues = { $set: {name: "Mickey", address: "Canyon 123" } };
[Link]("customers").updateOne(myquery, newvalues, function(err,
res) {
if (err) throw err;
[Link]("1 document updated");
[Link]();
});
});

Save the code above in a file called "demo_update_one.js" and run the file:

Run "demo_update_one.js"

C:\Users\Your Name>node demo_update_one.js

Which will give you this result:

Downloaded by HOD CSE 2 (hodcs2@[Link])


lOMoARcPSD|60855493

1 document updated

Update Only Specific Fields


When using the $set operator, only the specified fields are updated:

Example
Update the address from "Valley 345" to "Canyon 123":

...
var myquery = { address: "Valley 345" };
var newvalues = { $set: { address: "Canyon 123" } };
[Link]("customers").updateOne(myquery, newvalues, function(err,
res) {
...

Update Many Documents


To update all documents that meets the criteria of the query, use
the updateMany() method.

Example
Update all documents where the name starts with the letter "S":

var MongoClient = require('mongodb').MongoClient;


var url = "mongodb://[Link]:27017/";

[Link](url, function(err, db) {


if (err) throw err;
var dbo = [Link]("mydb");
var myquery = { address: /^S/ };
var newvalues = {$set: {name: "Minnie"} };
[Link]("customers").updateMany(myquery,
newvalues, function(err, res) {
if (err) throw err;
[Link]([Link] + " document(s) updated");
[Link]();
});
});

Downloaded by HOD CSE 2 (hodcs2@[Link])


lOMoARcPSD|60855493

Save the code above in a file called "demo_update_many.js" and run the file:

Run "demo_update_many.js"

C:\Users\Your Name>node demo_update_many.js

Which will give you this result:

2 document(s) updated

MongoDB Limit
Limit the Result
To limit the result in MongoDB, we use the limit() method.

The limit() method takes one parameter, a number defining how many
documents to return.

Consider you have a "customers" collection:

Customers

[
{ _id: 58fdbf5c0ef8a50b4cdd9a84 , name: 'John', address: 'Highway 71'},
{ _id: 58fdbf5c0ef8a50b4cdd9a85 , name: 'Peter', address: 'Lowstreet
4'},
{ _id: 58fdbf5c0ef8a50b4cdd9a86 , name: 'Amy', address: 'Apple st 652'},
{ _id: 58fdbf5c0ef8a50b4cdd9a87 , name: 'Hannah', address: 'Mountain
21'},
{ _id: 58fdbf5c0ef8a50b4cdd9a88 , name: 'Michael', address: 'Valley
345'},
{ _id: 58fdbf5c0ef8a50b4cdd9a89 , name: 'Sandy', address: 'Ocean blvd
2'},
{ _id: 58fdbf5c0ef8a50b4cdd9a8a , name: 'Betty', address: 'Green Grass
1'},
{ _id: 58fdbf5c0ef8a50b4cdd9a8b , name: 'Richard', address: 'Sky st
331'},
{ _id: 58fdbf5c0ef8a50b4cdd9a8c , name: 'Susan', address: 'One way 98'},
{ _id: 58fdbf5c0ef8a50b4cdd9a8d , name: 'Vicky', address: 'Yellow Garden
2'},
{ _id: 58fdbf5c0ef8a50b4cdd9a8e , name: 'Ben', address: 'Park Lane 38'},
{ _id: 58fdbf5c0ef8a50b4cdd9a8f , name: 'William', address: 'Central st

Downloaded by HOD CSE 2 (hodcs2@[Link])


lOMoARcPSD|60855493

954'},
{ _id: 58fdbf5c0ef8a50b4cdd9a90 , name: 'Chuck', address: 'Main Road
989'},
{ _id: 58fdbf5c0ef8a50b4cdd9a91 , name: 'Viola', address: 'Sideway
1633'}
]

Example
Limit the result to only return 5 documents:

var MongoClient = require('mongodb').MongoClient;


var url = "mongodb://localhost:27017/";

[Link](url, function(err, db) {


if (err) throw err;
var dbo = [Link]("mydb");
[Link]("customers").find().limit(5).toArray(function(err,
result) {
if (err) throw err;
[Link](result);
[Link]();
});
});

Save the code above in a file called "demo_mongodb_limit.js" and run the file:

Run "demo_mongodb_limit.js"

C:\Users\Your Name>node demo_mongodb_limit.js

Which will give you this result:

customers
[
{ _id: 58fdbf5c0ef8a50b4cdd9a84 , name: 'John', address: 'Highway 71'},
{ _id: 58fdbf5c0ef8a50b4cdd9a85 , name: 'Peter', address: 'Lowstreet
4'},
{ _id: 58fdbf5c0ef8a50b4cdd9a86 , name: 'Amy', address: 'Apple st 652'},
{ _id: 58fdbf5c0ef8a50b4cdd9a87 , name: 'Hannah', address: 'Mountain
21'},
{ _id: 58fdbf5c0ef8a50b4cdd9a88 , name: 'Michael', address: 'Valley
345'}
]

As you can see from the result above, only the 5 first documents were returned.

Downloaded by HOD CSE 2 (hodcs2@[Link])


lOMoARcPSD|60855493

MongoDB Join
Join Collections
MongoDB is not a relational database, but you can perform a left outer join by
using the $lookup stage.

The $lookup stage lets you specify which collection you want to join with the
current collection, and which fields that should match.

Consider you have a "orders" collection and a "products" collection:

orders
[
{ _id: 1, product_id: 154, status: 1 }
]

products
[
{ _id: 154, name: 'Chocolate Heaven' },
{ _id: 155, name: 'Tasty Lemons' },
{ _id: 156, name: 'Vanilla Dreams' }
]

Example
Join the matching "products" document(s) to the "orders" collection:

var MongoClient = require('mongodb').MongoClient;


var url = "mongodb://[Link]:27017/";

[Link](url, function(err, db) {


if (err) throw err;
var dbo = [Link]("mydb");
[Link]('orders').aggregate([
{ $lookup:
{
from: 'products',
localField: 'product_id',
foreignField: '_id',
as: 'orderdetails'
}
}

Downloaded by HOD CSE 2 (hodcs2@[Link])


lOMoARcPSD|60855493

]).toArray(function(err, res) {
if (err) throw err;
[Link]([Link](res));
[Link]();
});
});

Save the code above in a file called "demo_mongodb_join.js" and run the file:

Run "demo_mongodb_join.js"

C:\Users\Your Name>node demo_mongodb_join.js

Which will give you this result:

[
{ "_id": 1, "product_id": 154, "status": 1, "orderdetails": [
{ "_id": 154, "name": "Chocolate Heaven" } ]
}
]

As you can see from the result above, the matching document from the
products collection is included in the orders collection as an array.

Downloaded by HOD CSE 2 (hodcs2@[Link])

You might also like