0% found this document useful (0 votes)
56 views

Unit 3

Uploaded by

Santhosh Kumar
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
56 views

Unit 3

Uploaded by

Santhosh Kumar
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 28

UNIT III ADVANCED NODE JS AND DATABASE

Introduction to NoSQL databases – MongoDB System Overview - Basic Querying with


MongoDB Shell – Request Body Parsing in Express – NodeJS MongoDB Connection –
Adding and Retrieving Data to MongoDB from NodeJS – Handling SQL Databases from
NodeJS.

Introduction to NoSQL databases

 NoSQL is a type of database management system (DBMS) that is designed to


handle and store large volumes of unstructured and semi-structured data. Unlike
traditional relational databases that use tables with pre-defined schemas to store
data, NoSQL databases use flexible data models that can adapt to changes in
data structures and are capable of scaling horizontally to handle growing
amounts of data.
 The term NoSQL originally referred to “non-SQL” or “non-relational”
databases, but the term has since evolved to mean “not only SQL,” as NoSQL
databases have expanded to include a wide range of different database
architectures and data models.
NoSQL databases are generally classified into four main categories:
1. Document databases: These databases store data as semi-structured documents,
such as JSON or XML, and can be queried using document-oriented query
languages.
2. Key-value stores: These databases store data as key-value pairs, and are
optimized for simple and fast read/write operations.
3. Column-family stores: These databases store data as column families, which are
sets of columns that are treated as a single entity. They are optimized for fast
and efficient querying of large amounts of data.
4. Graph databases: These databases store data as nodes and edges, and are
designed to handle complex relationships between data.
NoSQL databases are often used in applications where there is a high volume of data
that needs to be processed and analyzed in real-time, such as social media analytics, e-
commerce, and gaming. They can also be used for other applications, such as content
management systems, document management, and customer relationship management.
1
Page

However, NoSQL databases may not be suitable for all applications, as they may not
provide the same level of data consistency and transactional guarantees as traditional
relational databases. It is important to carefully evaluate the specific needs of an
application when choosing a database management system.

NoSQL originally referring to non SQL or non relational is a database that provides a
mechanism for storage and retrieval of data. This data is modeled in means other than
the tabular relations used in relational databases. Such databases came into existence in
the late 1960s, but did not obtain the NoSQL moniker until a surge of popularity in the
early twenty-first century. NoSQL databases are used in real-time web applications
and big data and their use are increasing over time.

NoSQL systems are also sometimes called Not only SQL to emphasize the fact that
they may support SQL-like query languages. A NoSQL database includes simplicity of
design, simpler horizontal scaling to clusters of machines and finer control over
availability. The data structures used by NoSQL databases are different from those
used by default in relational databases which makes some operations faster in NoSQL.
The suitability of a given NoSQL database depends on the problem it should solve.

NoSQL databases, also known as “not only SQL” databases, are a new type of
database management system that have gained popularity in recent years. Unlike
traditional relational databases, NoSQL databases are designed to handle large
amounts of unstructured or semi-structured data, and they can accommodate dynamic
changes to the data model. This makes NoSQL databases a good fit for modern web
applications, real-time analytics, and big data processing.

Data structures used by NoSQL databases are sometimes also viewed as more flexible
than relational database tables. Many NoSQL stores compromise consistency in favor
of availability, speed and partition tolerance. Barriers to the greater adoption of
NoSQL stores include the use of low-level query languages, lack of standardized
interfaces, and huge previous investments in existing relational databases.

Most NoSQL stores lack true ACID(Atomicity, Consistency, Isolation, Durability)


transactions but a few databases, such as MarkLogic, Aerospike, FairCom c-treeACE,
Google Spanner (though technically a NewSQL database), Symas LMDB, and
OrientDB have made them central to their designs.
2
Page
Most NoSQL databases offer a concept of eventual consistency in which database
changes are propagated to all nodes so queries for data might not return updated data
immediately or might result in reading data that is not accurate which is a problem
known as stale reads. Also some NoSQL systems may exhibit lost writes and other
forms of data loss. Some NoSQL systems provide concepts such as write-ahead
logging to avoid data loss.
One simple example of a NoSQL database is a document database. In a document
database, data is stored in documents rather than tables. Each document can contain a
different set of fields, making it easy to accommodate changing data requirements
For example, “Take, for instance, a database that holds data regarding employees.”. In
a relational database, this information might be stored in tables, with one table for
employee information and another table for department information. In a document
database, each employee would be stored as a separate document, with all of their
information contained within the document.
NoSQL databases are a relatively new type of database management system that have
gained popularity in recent years due to their scalability and flexibility. They are
designed to handle large amounts of unstructured or semi-structured data and can
handle dynamic changes to the data model. This makes NoSQL databases a good fit
for modern web applications, real-time analytics, and big data processing.
Key Features of NoSQL :

 Dynamic schema: NoSQL databases do not have a fixed schema and can
accommodate changing data structures without the need for migrations or
schema alterations.
 Horizontal scalability: NoSQL databases are designed to scale out by adding
more nodes to a database cluster, making them well-suited for handling large
amounts of data and high levels of traffic.
 Document-based: Some NoSQL databases, such as MongoDB, use a document-
based data model, where data is stored in semi-structured format, such as JSON
or BSON.
 Key-value-based: Other NoSQL databases, such as Redis, use a key-value data
model, where data is stored as a collection of key-value pairs.
 Column-based: Some NoSQL databases, such as Cassandra, use a column-
based data model, where data is organized into columns instead of rows.
 Distributed and high availability: NoSQL databases are often designed to be
highly available and to automatically handle node failures and data replication
3

across multiple nodes in a database cluster.


Page

 Flexibility: NoSQL databases allow developers to store and retrieve data in a


flexible and dynamic manner, with support for multiple data types and changing
data structures.
 Performance: NoSQL databases are optimized for high performance and can
handle a high volume of reads and writes, making them suitable for big data and
real-time applications.
Advantages of NoSQL: There are many advantages of working with NoSQL
databases such as MongoDB and Cassandra. The main advantages are high scalability
and high availability.

 High scalability : NoSQL databases use sharding for horizontal scaling.


Partitioning of data and placing it on multiple machines in such a way that the
order of the data is preserved is sharding. Vertical scaling means adding more
resources to the existing machine whereas horizontal scaling means adding
more machines to handle the data. Vertical scaling is not that easy to implement
but horizontal scaling is easy to implement. Examples of horizontal scaling
databases are MongoDB, Cassandra, etc. NoSQL can handle a huge amount of
data because of scalability, as the data grows NoSQL scale itself to handle that
data in an efficient manner.
 Flexibility: NoSQL databases are designed to handle unstructured or semi-
structured data, which means that they can accommodate dynamic changes to
the data model. This makes NoSQL databases a good fit for applications that
need to handle changing data requirements.
 High availability : Auto replication feature in NoSQL databases makes it highly
available because in case of any failure data replicates itself to the previous
consistent state.
 Scalability: NoSQL databases are highly scalable, which means that they can
handle large amounts of data and traffic with ease. This makes them a good fit
for applications that need to handle large amounts of data or traffic
 Performance: NoSQL databases are designed to handle large amounts of data
and traffic, which means that they can offer improved performance compared to
traditional relational databases.
 Cost-effectiveness: NoSQL databases are often more cost-effective than
traditional relational databases, as they are typically less complex and do not
require expensive hardware or software.
Disadvantages of NoSQL:
NoSQL has the following disadvantages.
4
Page
 Lack of standardization : There are many different types of NoSQL databases,
each with its own unique strengths and weaknesses. This lack of standardization
can make it difficult to choose the right database for a specific application
 Lack of ACID compliance : NoSQL databases are not fully ACID-compliant,
which means that they do not guarantee the consistency, integrity, and
durability of data. This can be a drawback for applications that require strong
data consistency guarantees.
 Narrow focus : NoSQL databases have a very narrow focus as it is mainly
designed for storage but it provides very little functionality. Relational
databases are a better choice in the field of Transaction Management than
NoSQL.
 Open-source : NoSQL is open-source database. There is no reliable standard for
NoSQL yet. In other words, two database systems are likely to be unequal.
 Lack of support for complex queries : NoSQL databases are not designed to
handle complex queries, which means that they are not a good fit for
applications that require complex data analysis or reporting.
 Lack of maturity : NoSQL databases are relatively new and lack the maturity of
traditional relational databases. This can make them less reliable and less secure
than traditional databases.
 Management challenge : The purpose of big data tools is to make the
management of a large amount of data as simple as possible. But it is not so
easy. Data management in NoSQL is much more complex than in a relational
database. NoSQL, in particular, has a reputation for being challenging to install
and even more hectic to manage on a daily basis.
 GUI is not available : GUI mode tools to access the database are not flexibly
available in the market.
 Backup : Backup is a great weak point for some NoSQL databases like
MongoDB. MongoDB has no approach for the backup of data in a consistent
manner.
 Large document size : Some database systems like MongoDB and CouchDB
store data in JSON format. This means that documents are quite large (BigData,
network bandwidth, speed), and having descriptive key names actually hurts
since they increase the document size.
Types of NoSQL database:
Types of NoSQL databases and the name of the databases system that falls in that
category are:
5
Page

1. Graph Databases: Examples – Amazon Neptune, Neo4j


2. Key value store: Examples – Memcached, Redis, Coherence
3. Tabular: Examples – Hbase, Big Table, Accumulo
4. Document-based: Examples – MongoDB, CouchDB, Cloudant
When should NoSQL be used:
 When a huge amount of data needs to be stored and retrieved.
 The relationship between the data you store is not that important
 The data changes over time and is not structured.
 Support of Constraints and Joins is not required at the database level
 The data is growing continuously and you need to scale the database regularly
to handle the data.
MongoDB System Overview

MongoDB, the most popular NoSQL database, is an open-source document-oriented


database. The term ‘NoSQL’ means ‘non-relational’. It means that MongoDB isn’t
based on the table-like relational database structure but provides an altogether different
mechanism for storage and retrieval of data. This format of storage is called BSON (
similar to JSON format).

A simple MongoDB document Structure:

{
title: 'Geeksforgeeks',
by: 'Harshit Gupta',
url: 'https://www.geeksforgeeks.org',
type: 'NoSQL'
}
SQL databases store data in tabular format. This data is stored in a predefined data
model which is not very much flexible for today’s real-world highly growing
applications. Modern applications are more networked, social and interactive than
ever. Applications are storing more and more data and are accessing it at higher rates.

Relational Database Management System(RDBMS) is not the correct choice when it


comes to handling big data by the virtue of their design since they are not horizontally
scalable. If the database runs on a single server, then it will reach a scaling limit.
6

NoSQL databases are more scalable and provide superior performance. MongoDB is
Page

such a NoSQL database that scales by adding more and more servers and increases
productivity with its flexible document model.
RDBMS vs MongoDB:

RDBMS has a typical schema design that shows number of tables and the relationship
between these tables whereas MongoDB is document-oriented. There is no concept of
schema or relationship.
Complex transactions are not supported in MongoDB because complex join operations
are not available.
MongoDB allows a highly flexible and scalable document structure. For example, one
data document of a collection in MongoDB can have two fields whereas the other
document in the same collection can have four.
MongoDB is faster as compared to RDBMS due to efficient indexing and storage
techniques.
There are a few terms that are related in both databases. What’s called Table in
RDBMS is called a Collection in MongoDB. Similarly, a Row is called a Document
and a Column is called a Field. MongoDB provides a default ‘_id’ (if not provided
explicitly) which is a 12-byte hexadecimal number that assures the uniqueness of
every document. It is similar to the Primary key in RDBMS.
Features of MongoDB:

Document Oriented: MongoDB stores the main subject in the minimal number of
documents and not by breaking it up into multiple relational structures like RDBMS.
For example, it stores all the information of a computer in a single document called
Computer and not in distinct relational structures like CPU, RAM, Hard disk, etc.
Indexing: Without indexing, a database would have to scan every document of a
collection to select those that match the query which would be inefficient. So, for
efficient searching Indexing is a must and MongoDB uses it to process huge volumes
of data in very less time.
Scalability: MongoDB scales horizontally using sharding (partitioning data across
various servers). Data is partitioned into data chunks using the shard key, and these
data chunks are evenly distributed across shards that reside across many physical
servers. Also, new machines can be added to a running database.
Replication and High Availability: MongoDB increases the data availability with
multiple copies of data on different servers. By providing redundancy, it protects the
database from hardware failures. If one server goes down, the data can be retrieved
7

easily from other active servers which also had the data stored on them.
Page
Aggregation: Aggregation operations process data records and return the computed
results. It is similar to the GROUPBY clause in SQL. A few aggregation expressions
are sum, avg, min, max, etc
Where do we use MongoDB?

MongoDB is preferred over RDBMS in the following scenarios:

Big Data: If you have huge amount of data to be stored in tables, think of MongoDB
before RDBMS databases. MongoDB has built-in solution for partitioning and
sharding your database.
Unstable Schema: Adding a new column in RDBMS is hard whereas MongoDB is
schema-less. Adding a new field does not effect old documents and will be very easy.
Distributed data Since multiple copies of data are stored across different servers,
recovery of data is instant and safe even if there is a hardware failure.
Language Support by MongoDB:

MongoDB currently provides official driver support for all popular programming
languages like C, C++, Rust, C#, Java, Node.js, Perl, PHP, Python, Ruby, Scala, Go,
and Erlang.
Basic Querying with MongoDB Shell
MongoDB Shell is the quickest way to connect, configure, query, and work with your
MongoDB database.
It acts as a command-line client of the MongoDB server.
The MongoDB Shell is a standalone, open-source product and developed separately
from the MongoDB Server under the Apache 2 license.
It is a fully functional JavaScript and Node.js 14.x REPL for interacting with
MongoDB servers.
MongoDB Shell is already installed with MongoDB. You can find it in the installation
directory where you installed MongoDB. By default, it is "C:\Program
Files\MongoDB\Server". Open the installation folder and appropriate version folder
and go to the "bin" folder. Here, "mongo.exe" is MongoDB shell.

New MongoDB Shell - mongosh


In the installation folder, if you find mongosh.exe instead of mongo.exe then you
8

already have a new MongoDB shell. If you don't find it, then you need to install it
Page

separately.
The new MongoDB Shell mongosh has some more features than old shell mongo such
as intelligent autocomplete and syntax highlighting, easy to understand error messages,
formatting feature to present the output in a readable format, etc. However, all the
commands will be executed in mongosh as well as mongo shell.
Install mongosh
1. To install the new MongoDB shell (mongosh), visit www.mongodb.com and click
on Product menu -> Tools -> Database Shell
2. On the MongoDB Shell page, click on the Download button to download the
shell.
3. This will take you to a page where you can select a version, platform, and
package to download
4. Click on the Download button to download the installer file
5. Now, click on the downloaded installer file to start the installation wizard
6. Click Next to go to next step shown below.
7. Once installation completes, click the Finish button to close the wizard.
8. This should have installed mongosh in "C:\Program Files\mongosh" folder on
Windows
9. Click on the mongosh.exe to open a new MongoDB shell
MongoDB Shell Commands
MongoDB Shell is the quickest way to connect, configure, query,
and work with your MongoDB database. It acts as a command-line client of the
MongoDB server.
You can start MongoDB Shell by executing mongo or mongosh command on the
command prompt/terminal. mongosh is the new MongoDB shell with some more
features than the old mongo shell.
mongosh <commands>
The --help command display all the commands which you can use
with mongo or mongosh

--nodb allows you to run MongoDB shell without connecting to a


database.

MongoDB provides you read operations to retrieve documents from the collection or
query a collection for a document. You can perform read operations using the
db.collection.find() method. This method selects or views the documents from the
9

collection and returns the cursor to the selected document.


Page
find() is a mongo shell method, which can be used in the multi-document transactions.
The documents displayed by this method are in non-structured form. If you want to get
data in a structured form, then use pretty() method with find() method.
db.collection.find().pretty()
This method iterates the cursor automatically to display the first 20 documents of the
collection. If you want this method will display more than 20 documents, then type it
to continue the iteration.
Syntax:
db.collection.find(filter, projection)
Parameters:
filter: It is an optional parameter. It specifies the selection filter with the help of query
operators. And if you want to get all the documents present in the collection, then omit
these parameters or pass an empty document in the method. The type of this parameter
is a Document.
projection: It is an optional parameter. It specifies that only those fields return to the
document that matches the given query filter. And if you want to get all the fields in
the document, then omit this parameter.
Return: This method returns a cursor to the documents that match the specified query
criteria. When you use find() method, it returns documents which means the method is
actually returning the cursor to the documents.
Selecting all the documents:
In this example, we are selecting all the documents of the contributor collection and
displaying on the screen using db.collection.find() method.
Syntax:
db.contributor.find()
Select all documents in organized form:
In this example, we are selecting all the documents of the contributor collection and
displaying them in the organized form using db.collection.find() method with pretty()
method.
Syntax:
db.contributor.find().pretty()
Select documents that satisfy the given condition:
10

In this example, we are selecting only those documents that satisfy the given condition,
Page

i.e, language: “C#”. Or in other words, we are selecting only those contributors who
are working with C# language.
Syntax:
db.collection.find({field: value})
Select documents that satisfy the given condition (Using Query operators):
In this example, we are selecting only those documents that satisfy the given condition,
here the condition is created using query operators. Or in words, we are selecting only
those contributors who are working with C# or Java language.
Syntax:
db.collection.find({field: {operator: value}})
Here, we are using $in operator. This operator is used to matches any of the values
specified in the given array.
db.contributor.find({language: {$in:[ "Java", "C#"]}}).pretty()

Request Body Parsing in Express


 Body-parser parses is an HTTP request body that usually helps when you need
to know more than just the URL being hit.
 Specifically in the context of a POST, PATCH, or PUT HTTP request where
the information you want is contained in the body.
 Using body-parser allows you to access req.body from within routes and use
that data.
Installation
To install the body-parser first, you must create a project and the first command you
will write here is npm init -y.
This is used to create a JSON file, and in that you can add all the dependencies.
Step 1:

Step 2: Now, you have to install express for that, you will write a command npm i
express.

Step 3: After that, go ahead and install body-parser. For that write command on your
11

terminal.
Page
Now, the body-parser is installed in your system.
Step 4: Go ahead and write a basic Express app that is common in every express
application.

Installation of body-parser module:


You can visit the link to Install the body-parser module. You can install this package
by using this command.
npm install body-parser
After installing body-parser you can check your body-parser version in the command
prompt using the command.
npm version body-parser
After that, you can just create a folder and add a file, for example, index.js. To run this
file you need to run the following command.
node index.js
12
Page
SampleForm.ejs

<!DOCTYPE html>
<html>
<head>
<title>Body-Parser Module Demo</title>
</head>

<body>
<h1>Demo Form</h1>

<form action="saveData" method="POST">


<pre>
Enter your Email : <input type="text"
name="email"> <br>

<input type="submit" value="Submit Form">


</pre>
</form>
</body>
</html>

index.js

const bodyparser = require('body-parser')


const express = require("express")
const path = require('path')
const app = express()

let PORT = process.env.port || 3000


13

// View Engine Setup


Page
app.set("views", path.join(__dirname))
app.set("view engine", "ejs")

// Body-parser middleware
app.use(bodyparser.urlencoded({ extended: true }))
app.use(bodyparser.json())

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


res.render("SampleForm")
});

app.post('/saveData', (req, res) => {


console.log("Using Body-parser: ", req.body.email)
})

app.listen(PORT, function (error) {


if (error) throw error
console.log("Server created Successfully on PORT", PORT)
})

Steps to run the program:


Make sure you have installed ‘view engine’ like I have used “ejs” and also installed
express and body-parser module using the following commands:
npm install express
npm install ejs
npm install body-parser
Run the index.js file using the below command:
node index.js
Now Open the browser and type the below URL and you will see the Demo Form as
shown below:
http://localhost:3000/
14
Page
Now submit the form and then you will see the following output:

15
Page
NodeJS MongoDB Connection

Node.js can be used in database applications.


One of the most popular NoSQL database is MongoDB.
Install MongoDB Driver
Let us try to access a MongoDB database with Node.js.
To download and install the official MongoDB driver, open the Command Terminal
and execute the following:
Download and install mongodb package:
C:\Users\Your Name>npm install mongodb
Now you have downloaded and installed a mongodb database driver.
Node.js can use this module to manipulate MongoDB databases:

var mongo = require('mongodb');


Creating a Database
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.

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


//Create a database named "mydb":
var url = "mongodb://localhost:27017/mydb";

MongoClient.connect(url, function(err, db) {


if (err) throw err;
console.log("Database created!");
db.close();
});

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

Run "demo_create_mongo_db.js"
Page
C:\Users\Your Name>node demo_create_mongo_db.js

Which will give you this result:

Database created!

To connect a Node.js application to MongoDB, we have to use a library


called Mongoose.
const mongoose = require("mongoose");
After that, we have to call the connect method of Mongoose
mongoose.connect("mongodb://localhost:27017/collectionName", {
useNewUrlParser: true,
useUnifiedTopology: true
});
Then we have to define a schema. A schema is a structure, that gives information
about how the data is being stored in a collection.
Example: Suppose we want to store information from a contact form of a website.
const contactSchema = {
email: String,
query: String,
};
Then we have to create a model using that schema which is then used to store data in a
document as objects.
const Contact = mongoose.model("Contact", contactSchema);
Then, finally, we are able to store data in our document.
app.post("/contact", function (req, res) {
const contact = new Contact({
email: req.body.email,
query: req.body.query,
});
contact.save(function (err) {
if (err) {
res.redirect("/error");
} else {
17

res.redirect("/thank-you");
Page

}
});
});

Contact.ejs

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content=
"width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<form action="/contact" method="post">
<input type="text" placeholder="Email" name="email">
<input type="text" placeholder="Query" name="query">
<button type="submit">Submit</button>
</form>
</body>
</html>

Server File ( App.js or Index.js )


 Javascript

const express = require("express");


const ejs = require("ejs");
const mongoose = require("mongoose");
const bodyParser = require("body-parser");

mongoose.connect("mongodb://localhost:27017/newCollection", {
18

useNewUrlParser: true,
Page
useUnifiedTopology: true
});

const contactSchema = {
email: String,
query: String,
};

const Contact = mongoose.model("Contact", contactSchema);

const app = express();

app.set("view engine", "ejs");

app.use(bodyParser.urlencoded({
extended: true
}));

app.use(express.static(__dirname + '/public'));

app.get("/contact", function(req, res){


res.render("contact");
});

app.post("/contact", function (req, res) {


console.log(req.body.email);
con10st contact = new Contact({
emai0l: req.body.email,
query0: req.body.query,
});
contact.save(function (err) {
19

if (err) {
Page
throw err;
} else {
res.render("contact");
}
});
});

app.listen(3000, function(){
console.log("App is running on Port 3000");
});

Output:

20
Page
Page
21
Adding and Retrieving Data to MongoDB from NodeJS

Node.js MongoDB Insert


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

he 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

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


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

MongoClient.connect(url, function(err, db) {


if (err) throw err;
var dbo = db.db("mydb");
var myobj = { name: "Company Inc", address: "Highway 37" };
dbo.collection("customers").insertOne(myobj, function(err, res) {
if (err) throw err;
console.log("1 document inserted");
db.close();
});
});

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
22
Page
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:

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


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

MongoClient.connect(url, function(err, db) {


if (err) throw err;
var dbo = db.db("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'}
];
dbo.collection("customers").insertMany(myobj, function(err, res) {
if (err) throw err;
console.log("Number of documents inserted: " + res.insertedCount);
db.close();
});
});

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


the file:

Run "demo_mongodb_insert_multiple.js"
23

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


Page

Which will give you this result:


Number of documents inserted: 14

Node.js MongoDB Find

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.

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).

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


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

MongoClient.connect(url, function(err, db) {


if (err) throw err;
var dbo = db.db("mydb");
//Find the first document in the customers collection:
dbo.collection("customers").findOne({}, function(err, result) {
if (err) throw err;
console.log(result.name);
db.close();
});
});

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.
24
Page
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.

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


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

MongoClient.connect(url, function(err, db) {


if (err) throw err;
var dbo = db.db("mydb");
//Find all documents in the customers collection:
dbo.collection("customers").find({}).toArray(function(err, result) {
if (err) throw err;
console.log(result);
db.close();
});
});

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'},
25

{ _id: 58fdbf5c0ef8a50b4cdd9a8c , name: 'Susan', address: 'One way 98'},


{ _id: 58fdbf5c0ef8a50b4cdd9a8d , name: 'Vicky', address: 'Yellow Garden
Page

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'}
]

Handling SQL Databases from NodeJS.

Node.js can be used in database applications.

One of the most popular databases is MySQL.

MySQL Database

To be able to experiment with the code examples, you should have MySQL
installed on your computer.

You can download a free MySQL database


at https://www.mysql.com/downloads/.

Install MySQL Driver

Once you have MySQL up and running on your computer, you can access it by
using Node.js.

To access a MySQL database with Node.js, you need a MySQL driver. This
tutorial will use the "mysql" module, downloaded from NPM.

To download and install the "mysql" module, open the Command Terminal and
execute the following:

C:\Users\Your Name>npm install mysql

Now you have downloaded and installed a mysql database driver.


26

Node.js can use this module to manipulate the MySQL database:


Page
var mysql = require('mysql');

Create Connection

Start by creating a connection to the database.

Use the username and password from your MySQL database.

demo_db_connection.js

var mysql = require('mysql');

var con = mysql.createConnection({


host: "localhost",
user: "yourusername",
password: "yourpassword"
});

con.connect(function(err) {
if (err) throw err;
console.log("Connected!");
});

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

Run "demo_db_connection.js"

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

Which will give you this result:

Connected!

Now you can start querying the database using SQL statements.

Query a Database

Use SQL statements to read from (or write to) a MySQL database. This is also
called "to query" the database.

The connection object created in the example above, has a method for querying
the database:
27

con.connect(function(err) {
Page

if (err) throw err;


console.log("Connected!");
con.query(sql, function (err, result) {
if (err) throw err;
console.log("Result: " + result);
});
});

The query method takes an sql statements as a parameter and returns the
result.

28
Page

You might also like