Node JS
Node JS
What is [Link]?
• [Link] is free
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.
2. Waits while the file system opens and reads the file.
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] can create, open, read, write, delete, and close files on the server
• [Link] files must be initiated on the server before having any effect
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 −
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.
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.
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
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] ().
Example:
Commands Description
.load filename It is used to load file content in current node repl session.
You can use npm ls command to list down all the locally installed modules.
Open the [Link] command prompt and execute "npm ls":
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
The [Link] module is uninstalled. You can verify by using the following command:
1. npm ls
Searching a Module
"npm search express" command is used to search express or module.
1. npm search express
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.
• 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');
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:
• 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.
// 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');
// 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
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.
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.
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.
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).
• Uniform interface
• Statelessness
• Client-server
• Cacheability
• Layered system
• Code on demand
• 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.
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.
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.
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.
Explore our latest online courses and learn new skills at your own pace. Enroll and become a
certified expert to boost your career.
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.
{
"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.
List Users
Let's implement the first route in our RESTful API to list all Users using the following code in a
[Link] file
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.
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
},
"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.
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.
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
},
"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.
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.
{
"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
}
});
})
users[id]=[Link];
[Link]( [Link](users));
})
})
var server = [Link](5000, function () {
[Link]("Express App running at [Link]
})
Print Page
[Link] MongoDB
MongoDB will create the database if it does not exist, and make a connection to
it.
Example
Create a database called "mydb":
Save the code above in a file called "demo_create_mongo_db.js" and run the file:
Run "demo_create_mongo_db.js"
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:
Example
Create a collection called "customers":
Run "demo_mongodb_createcollection.js"
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.
It also takes a callback function where you can work with any errors, or the
result of the insertion:
Example
Insert a document in the "customers" collection:
Save the code above in a file called "demo_mongodb_insert.js" and run the file:
Run "demo_mongodb_insert.js"
1 document inserted
Note: If you try to insert documents in a collection that do not exist, MongoDB
will create the collection automatically.
It also takes a callback function where you can work with any errors, or the
result of the insertion:
Example
Run "demo_mongodb_insert_multiple.js"
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,
58fdbf5c0ef8a50b4cdd9a8d,
58fdbf5c0ef8a50b4cdd9a8e,
58fdbf5c0ef8a50b4cdd9a8f
58fdbf5c0ef8a50b4cdd9a90,
58fdbf5c0ef8a50b4cdd9a91 ]
}
Example
Return the number of inserted documents:
[Link]([Link])
14
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:
];
[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"
{
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 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:
Save the code above in a file called "demo_mongodb_findone.js" and run the
file:
Run "demo_mongodb_findone.js"
Company Inc.
Find All
To select data from a table in MongoDB, we can also use the find() method.
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.
Example
Find all documents in the customers collection:
Save the code above in a file called "demo_mongodb_find.js" and run the file:
Run "demo_mongodb_find.js"
[
{ _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
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":
Save the code above in a file called "demo_mongodb_query.js" and run the file:
Run "demo_mongodb_query.js"
[
{ _id: 58fdbf5c0ef8a50b4cdd9a8e , name: 'Ben', address: 'Park Lane 38' }
]
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":
Save the code above in a file called "demo_mongodb_query_s.js" and run the
file:
Run "demo_mongodb_query_s.js"
[
{ _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:
Save the code above in a file called "demo_sort.js" and run the file:
Run "demo_sort.js"
[
{ _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":
Save the code above in a file called "demo_delete.js" and run the file:
Run "demo_delete.js"
1 document deleted
Delete Many
To delete more than one document, use the deleteMany() method.
Example
Delete all documents were the address starts with the letter "O":
[Link]();
});
});
Save the code above in a file called "demo_delete_many.js" and run the file:
Run "demo_delete_many.js"
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:
Save the code above in a file called "demo_drop.js" and run the file:
Run "demo_drop.js"
Collection deleted
[Link]
You can also use the dropCollection() method to delete a table (collection).
Example
Delete the "customers" collection, using dropCollection():
Save the code above in a file called "demo_dropcollection.js" and run the file:
Run "demo_dropcollection.js"
Collection deleted
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":
Save the code above in a file called "demo_update_one.js" and run the file:
Run "demo_update_one.js"
1 document 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) {
...
Example
Update all documents where the name starts with the letter "S":
Save the code above in a file called "demo_update_many.js" and run the file:
Run "demo_update_many.js"
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.
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
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:
Save the code above in a file called "demo_mongodb_limit.js" and run the file:
Run "demo_mongodb_limit.js"
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.
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.
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:
]).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"
[
{ "_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.