KEMBAR78
UNIT 3 FS Notes | PDF | No Sql | Relational Database
0% found this document useful (0 votes)
53 views45 pages

UNIT 3 FS Notes

This document provides an overview of advanced Node.js and NoSQL databases, particularly focusing on MongoDB. It discusses the advantages of NoSQL over relational databases, including scalability, flexibility, and ease of data manipulation, as well as key components and features of MongoDB. Additionally, it covers basic MongoDB commands and the Mongo shell for database interaction.

Uploaded by

bdhanush289
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)
53 views45 pages

UNIT 3 FS Notes

This document provides an overview of advanced Node.js and NoSQL databases, particularly focusing on MongoDB. It discusses the advantages of NoSQL over relational databases, including scalability, flexibility, and ease of data manipulation, as well as key components and features of MongoDB. Additionally, it covers basic MongoDB commands and the Mongo shell for database interaction.

Uploaded by

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

FULL STACK WEB DEVELOPMENT-MC4201

UNIT-III
UNIT III ADVANCED NODE JS AND DATABASE 9
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 – Handling Cookies in NodeJS –Handling User Authentication with NodeJS

ADVANCED NODE JS AND DATABASE

Introduction to NoSQL Databases


A database Management System provides the mechanism to store and retrieve thedata. There are different
kinds of database Management Systems:
1. RDBMS (Relational Database Management Systems)
2. OLAP (Online Analytical Processing)
3. NoSQL (Not only SQL)
In this guide, We will discuss NoSQL. NoSQL databases were created toovercome the limitations
of relational databases.

What is a NoSQL database?


NoSQL databases are different than relational databases like MQSql. In relational database you need to create
the table, define schema, set the data types of fields etcbefore you can actually insert the data. In NoSQL you
don’t have to worry about that, you can insert, update data on the fly.

One of the advantages of NoSQL database is that they are really easy to scale andthey are much faster in
most types of operations that we perform on database.
There are certain situations where you would prefer relational database over NoSQL, however when you are
dealing with huge amount of data then NoSQLdatabase is your best choice.

Limitations of Relational databases

1. In relational database we need to define structure and schema of data first and
then only we can process the data.

2. Relational database systems provides consistency and integrity of data by


enforcing ACID properties (Atomicity, Consistency, Isolation and Durability ).
There are some scenarios where this is useful like banking system. However in
most of the other cases these properties are significant performance overhead and
can make your database response very slow.
3. Most of the applications store their data in JSON format and RDBMS don’t
provide you a better way of performing operations such as create, insert, update,
delete etc on this data. On the other hand NoSQL store their data in JSON format,
which is compatible with most of the today’s world application.
What are the advantages of NoSQL
There are several advantages of working with NoSQL databases such as MongoDBand Cassandra. The main
advantages are high scalability and high availability.
High scalability: NoSQL database such as MongoDB uses sharding for horizontalscaling. Sharding is
partitioning of data and placing it on multiple machines in such a way that the order of the data is preserved.
Vertical scaling means adding more resources to the existing machine while horizontal scaling means adding
more machines to handle the data. Vertical scaling is not that easy to implement, on the other hand horizontal
scaling is easy to implement. Horizontal scaling database examples: MongoDB, Cassandra etc. Because of
this feature NoSQL can handle huge amount of data, as the data grows NoSQL scale itself to handle that data
in efficient manner.
High Availability: Auto replication feature in MongoDB makes it highly availablebecause in case of any
failure data replicates itself to the previous consistent state.

Types of NoSQL database


Here are the types of NoSQL databases and the name of the databases system thatfalls in that category.
MongoDB falls in the category of NoSQL document based database.
Key Value Store: Memcached, Redis, Coherence
Tabular: Hbase, Big Table, Accumulo
Document based: MongoDB, CouchDB, Cloudant
RDBMS Vs NoSQL

RDBMS: It is a structured data that provides more functionality but gives lessperformance.
NoSQL: Structured or semi structured data, less functionality and highperformance.
So when I say less functionality in NoSQL what’s missing:

1. You can’t have constraints in NoSQL


2. Joins are not supported in NoSQL
These supports actually hinders the scalability of a database, so while using NoSQL database like
MongoDB, you can implements these functionalities at theapplication level.

When to go for NoSQL

When you would want to choose NoSQL over relational database:

1. When you want to store and retrieve huge amount of data.


2. The relationship between the data you store is not that important
3. The data is not structured and changing over time
4. Constraints and Joins support is not required at database level
5. The data is growing continuously and you need to scale the database regular
to handle the data.

What is MongoDB? Introduction, Architecture, Features &Example

What is MongoDB?
MongoDB is a document-oriented NoSQL database used for high volume data storage. Instead of using
tables and rows as in the traditional relational databases,MongoDB makes use of collections and documents.
Documents consist of key- value pairs which are the basic unit of data in MongoDB. Collections contain sets
of documents and function which is the equivalent of relational database tables.
MongoDB is a database which came into light around the mid-2000s.

MongoDB Features

1. Each database contains collections which in turn contains documents. Each


document can be different with a varying number of fields. The size and
content of each document can be different from each other.
2. The document structure is more in line with how developers construct their
classes and objects in their respective programming languages. Developers
will often say that their classes are not rows and columns but have a clear
structure with key-value pairs.
3. The rows (or documents as called in MongoDB) doesn’t need to have a
schema defined beforehand. Instead, the fields can be created on the fly.
4. The data model available within MongoDB allows you to represent
hierarchical relationships, to store arrays, and other more complex structures
more easily.
5. Scalability – The MongoDB environments are very scalable. Companies
across the world have defined clusters with some of them running 100+
nodes with around millions of documents within the database

MongoDB Example
The below example shows how a document can be modeled in MongoDB.

1. The _id field is added by MongoDB to uniquely identify the document in the
collection.
2. What you can note is that the Order Data (OrderID, Product, and Quantity )
which in RDBMS will normally be stored in a separate table, while in
MongoDB it is actually stored as an embedded document in the collection
itself. This is one of the key differences in how data is modeled in
MongoDB.
Key Components of MongoDB Architecture
Below are a few of the common terms used in MongoDB

1. _id – This is a field required in every MongoDB document. The _id field
represents a unique value in the MongoDB document. The _id field is like
the document’s primary key. If you create a new document without an _id
field, MongoDB will automatically create the field. So for example, if we
see the example of the above customer table, Mongo DB will add a 24 digit
unique identifier to each document in the collection.

_Id CustomerID
563479cc8a8a4246bd27d784 11
563479cc7a8a4246bd47d784 22
563479cc9a8a4246bd57d784 33

2. Collection – This is a grouping of MongoDB documents. A collection is the


equivalent of a table which is created in any other RDMS such as Oracle or
MS SQL. A collection exists within a single database. As seen from the
introduction collections don’t enforce any sort of structure.
3. Cursor – This is a pointer to the result set of a query. Clients can iterate
through a cursor to retrieve results.
4. Database – This is a container for collections like in RDMS wherein it is a
container for tables. Each database gets its own set of files on the file
system. A MongoDB server can store multiple databases.
5. Document – A record in a MongoDB collection is basically called a
document. The document, in turn, will consist of field name and values.
6. Field – A name-value pair in a document. A document has zero or more
fields. Fields are analogous to columns in relational databases.The following
diagram shows an example of Fields with Key value pairs. So in the
example below CustomerID and 11 is one of the key value pair’s defined in
the document.
7. JSON – This is known as JavaScript Object Notation. This is a human-
readable, plain text format for expressing structured data. JSON is currently
supported in many programming languages.

Just a quick note on the key difference between the _id field and a normal collection field. The _id field is used
to uniquely identify the documents in a collection and is automatically added by MongoDB when the collection
is created.

Why Use MongoDB?


Below are the few of the reasons as to why one should start using MongoDB

1. Document-oriented – Since MongoDB is a NoSQL type database, instead of


having data in a relational type format, it stores the data in documents. This
makes MongoDB very flexible and adaptable to real business world
situation and requirements.
2. Ad hoc queries – MongoDB supports searching by field, range queries, and
regular expression searches. Queries can be made to return specific fields
within documents.
3. Indexing – Indexes can be created to improve the performance of searches
within MongoDB. Any field in a MongoDB document can be indexed.
4. Replication – MongoDB can provide high availability with replica sets. A
replica set consists of two or more mongo DB instances. Each replica set
member may act in the role of the primary or secondary replica at any time.
The primary replica is the main server which interacts with the client and
performs all the read/write operations. The Secondary replicas maintain a
copy of the data of the primary using built-in replication. When a primary
replica fails, the replica set automatically switches over to the secondary andthen it becomes the
primary server.
5. Load balancing – MongoDB uses the concept of sharding to scale
horizontally by splitting data across multiple MongoDB instances.
MongoDB can run over multiple servers, balancing the load and/or
duplicating data to keep the system up and running in case of hardware
failure.

Data Modelling in MongoDB


As we have seen from the Introduction section, the data in MongoDB has a flexibleschema. Unlike in SQL
databases, where you must have a table’s schema declared before inserting data, MongoDB’s collections do not
enforce document structure.
This sort of flexibility is what makes MongoDB so powerful. When modeling data in

Mongo, keep the following things in mind

1. What are the needs of the application – Look at the business needs of the
application and see what data and the type of data needed for the application.
Based on this, ensure that the structure of the document is decided
accordingly.
2. What are data retrieval patterns – If you foresee a heavy query usage then
consider the use of indexes in your data model to improve the efficiency of
queries.
3. Are frequent inserts, updates and removals happening in the database?
Reconsider the use of indexes or incorporate sharding if required in your
data modeling design to improve the efficiency of your overall MongoDB
environment.

Difference between MongoDB & RDBMS


Below are some of the key term differences between MongoDB and RDBMS

Mongo Difference
RDBMS
DB
Table Collection In RDBMS, the table contains the columns and rows which are
used to store the data whereas, in MongoDB, this same structure
is known as a collection. The collection contains documents which
in turn contains Fields, which in turn are key-value pairs.
Mongo Difference
RDBMS
DB
In RDBMS, the row represents a single, implicitly structured data
Row Document
item in a table. In MongoDB, the data is stored in documents.
Field In RDBMS, the column denotes a set of data values. These in
Column
MongoDB are known as Fields.
Joins Embedded In RDBMS, data is sometimes spread across various tables and in order to show a
documents complete view of all data, a join is sometimesformed across tables to get the data. In
MongoDB, the data is normally stored in a single collection, but separated by using
Embedded documents. So there is no concept of joins in MongoDB.

Apart from the terms differences, a few other differences are shown below

1. Relational databases are known for enforcing data integrity. This is not an
explicit requirement in MongoDB.
2. RDBMS requires that data be normalized first so that it can prevent orphan
records and duplicates Normalizing data then has the requirement of more
tables, which will then result in more table joins, thus requiring more keys
and indexes.As databases start to grow, performance can start becoming an
issue. Again this is not an explicit requirement in MongoDB. MongoDB is
flexible and does not need the data to be normalized first.
MongoDB: The Mongo Shell & Basic Commands

What is the MongoDB Mongo shell?

MongoDB Mongo shell is an interactive JavaScript interface that allows you to interact with MongoDB
instances through the command line. The shell can be usedfor:

• Data manipulation
• Administrative operations such as maintenance of database instances

MongoDB Mongo shell features


MongoDB Mongo shell is the default client for the MongoDB database server. It’sa command-line interface
(CLI), where the input and output are all console-based.The Mongo shell is a good tool to manipulate small
sets of data.

Here are the top features that Mongo shell offers:

• Run all MongoDB queries from the Mongo shell.


• Manipulate data and perform administration operations.
• Mongo shell uses JavaScript and a related API to issue commands.
• See previous commands in the mongo shell with up and down arrow keys.
• View possible command completions using the tab button after partially
entering a command.
• Print error messages, so you know what went wrong with your commands.

MongoDB has recently introduced a new mongo shell known as mongosh. It hassome additional features,
such as extensibility and embeddability—that is, the ability to use it inside other products such as VS Code.

Installing the mongo shell


The mongo shell gets installed when you install the MongoDB server. It isinstalled in the same location as
the MongoDB server binary.

If you want to install it separately, you can visit the MongoDB download center,from there select the
version and package you need, download the archive, and copy it to a location in your file system.
Mongo shell is available for all main operating systems, including:

• Windows
• Linux
• Mac OS

Connect to MongoDB database

Once you’ve downloaded and installed MongoDB, you can use the mongo shell toconnect with a MongoDB
server that is up and running.
Note: It is required that your server is already running before you connect with it through the shell. You can
start the server in CMD using the following command.
net start MongoDB

Then type mongo command to run the shell.

Mongo

Now you are in the Mongo shell.

If you want, you can run the mongo and mongod without the command prompt. Todo this, go to the installation
location and double click on the mongod and mongo applications. You will get the same result as the above.

Different port
The above mongo command only works if your MongoDB server runs on the default port, which is 27017. If
your MongoDB server runs on a different port, youhave to explicitly specify it in the command, as shown
below:

mongo --port 28010

Remote server
Both of the above commands only work if your MongoDB server is running on thelocalhost. If you want to
connect to a remote server, use the `–host` option with themongo command, as shown below.

mongo --host mongodb0.example.com --port 28010

Basic commands for Mongo shell

Now it’s time to work with the Mongo shell. First, we will learn some basic
commands that will help you to get started with using MongoDB.

Run the db command to see the database you are currently working with

db

Run the use command to switch to a different database. If you don’t have a
database, learn how to create a new database.

use company

You can create collections and insert data with the following command:

• db refers to the current database in use.


• employee is the collection name.
• insertOne is the method to insert a document to the collection.

db.employee.insertOne( { name: "mark" } );


Use the find method to fetch data in a collection. The forEach(printjson) method
will print them with JSON formatting
db.employee.find().forEach(printjson)

Use the show dbs command to Show all databases

show dbs

One important command will help you work with the Mongo shell easily:
the help command. Run the help command to get a list of help options available inthe mongo shell.

Help
To get a full list of commands that you can execute on the current database,type db.help()

We will discuss more data manipulation commands in coming tutorials. For a fulllist of commands, check
out the official Mongo shell page.

Mongo shell keyboard shortcuts


There are two important keyboard shortcuts that you should know:

1. Use up and down arrows to go back and forth in the commands history.
2. Press the tab key to get a full list of possible commands. For example,
type d and press tab twice. You will get the following output.

Disadvantages of the mongo shell

Although the Mongo shell is an excellent tool for learning and testing the MongoDB server, it is difficult to be
used in a production environment. Being ashell inherently carries certain disadvantages. Let’s see what they
are:
• The Mongo shell is strictly a console centric method of data manipulation.
While some find it easy and quick, others might not find those characteristics
appealing.
• If you are working on multiple sessions, you need multiple terminals.
• If the results are too long, they scroll away.
• Repetitive commands or debugging a function need the programmer to
traverse the long command line history manually.

Alternatives to MongoDB mongo shell

So now you know the mongo shell has some disadvantages. At this point, you maywant to know what other
options are available. MongoDB developers have introduced drivers specific to each programming language to
connect with the MongoDB databases when using MongoDB in your applications. You can find them here.
Additionally, many people prefer to use GUIs to work with databases nowadays.One of the best GUI tools
for MongoDB is the MongoDB Compass. Some otheruseful GUI tools are:

• NoSQLBooster
• Mongo Management Studio
• Robo 3T

Remember that the best MongoDB GUI depends on the task that needs to be accomplished. MongoDB
Compass is the go-to option if you need to avoid thecommand line completely. Robo 3T is simple and
well supported by the community, while NoSQLBooster is shell centric smart GUI tool.

What is Express body-parser?

Express body-parser is an npm library used to process data sent through an HTTPrequest body. It exposes
four express middlewares for parsing text, JSON, url- encoded and raw data set through an HTTP request
body. These middlewares are functions that process incoming requests before they reach the target controller.
body-parser doesn’t have to be installed as a separate package because it is a dependency of express version
4.16.0+. body-parser isn’t a dependency between version 4.0.0 and 4.16.0, so it will be installed separately in
projects locked to those versions. body-parser middlewares will be required by express in versions ofexpress
with body-parser dependency. Versions of Express without body-
parser will have to install it separately.
How to use body-parser

The middlewares that body-parser exposes can be a part of a single route or for thewhole app. You will need
to expose and register the required middleware.

In the code block below, the JSON parser middleware is registered for the wholeapplication. This means all
requests will pass through this middleware.
The body-parser middleware converts text sent through an HTTP request to atarget format. body-parser
fails to parse if the content type of the request doesmatch that defined on the route. body-parser exposes
4 different parsers: text,JSON, URL encoded, and raw.

How to connect mongodb Server with Node.js ?

mongodb.connect() method is the method of the MongoDB module of the Node.js which is used to connect
the database with our Node.js Application. Thisis an asynchronous method of the MongoDB module.
Syntax:
mongodb.connect(path,callbackfunction)
Parameters: This method accept two parameters as mentioned above anddescribed below:
1. Path/URL: The Path of the server of the MongoDB server which is running
on a particular port number.
2. callbackfunction: It returns the err or the instance of the mongodb database
for further operation if connection successful.
Installing module:
npm install mongodb --save

Project structure:

Command to run server on particular ip:


mongod --dbpath=data --bind_ip 127.0.0.1

FileName index.js
Javascript

// Module calling

const MongoClient = require("mongodb");

// Server path

const url = 'mongodb://localhost:27017/';

// Name of the database const

dbname = "conFusion";

MongoClient.connect(url, (err,client)=>{if(!err) {

console.log("successful connection with the server");

else

console.log("Error in the connectivity");

})

Running command:
node index.js

Output:
node index.js

(node:7016) DeprecationWarning: current Server Discovery and Monitoring engine is deprecated, and will
be removed in a future version. To use the new Server Discover and Monitoring engine, pass option {
useUnifiedTopology: true
} to the MongoClient constructor.

(Use `node --trace-deprecation ...` to show where the warning was created)successful connection with the
server

CRUD Operation in MongoDB using Node.js

Introduction
Node.js is an open-source, cross-platform and provides a run-time environment fordeveloping server-side and
networking applications. Node.js applications are written in JavaScript and can run within the Node.js Node.js
also provide a rich library of various Javascript module which simplifies the development of web application
using Node.js

VS Code

VS Code is a source-code editor developed by Microsoft for Windows, Linux, andiOS. The code supports
many languages.VS Code intuitive keyboard shortcuts, easy customization.

Step 1

Download Node.js from the link and then install node js


Step 2

Download VS Code from this link and install

Step 3

Download MongoDB compass from link for view database and after downloadinstall mongodb and run their
service from web service

Step 4

check version of Node to run command on cmd “ node -v”

Step 5

Open VS Code in your system and run a command to install npm “install npm -2
@angular/cli”

Then wait to done install the complete pakage(Liberary) from the servce

Step 6

After completing the installation, open VS Code in your system and select a folderto click on the Folder then
open this folder in VS Code.
MongoDB

Mongo DB is a cross-platform, open-source document-orient database. Mongod isNoSQL database(no


structure). Mongo DB stores JSON data in the form of collections. MongoDB has no structure of the data, so
it’s called NoSQL data.
Mongo DB has no limit to store data into a database like SQL. Mongo DB has norequirements to declare length
of the field like SQL/ Oracle / SqlYog.

CRUD Operation in MongoDB

CRUD stands for " create, read, update, and delete". Crud operations are used tocreate, read, update, and delete
any documents.

Step 1

Connect your system with the internet and open the command prompt and then runcommand

1. install mongodb --save


This command is used to install the MongoDB package in your system. It will takemore than 2 minutes. When
it completes, then close the command prompt

Step 7

Create a database in MongoDB using Node.js and VS Code. first, open VS Code and create a folder where
you want to make database program. and then open thisfolder in VS Code

Step 8

For performing any crud operation in MongoDB, you need a database and acollection. First. create a database
and then create a collection.

Step 9 - Create a database


Create a .js page(createdatabase.js) and now write the code:

createdatabase.js

1. var mongodb=require('mongodb');
2. var MongoClient=mongodb.MongoClient;
3. var url='mongodb://localhost:27017/';
4. MongoClient.connect(url,function(error, databases){// use for to connect to t
he databases
5. if(error){
6. throw error;
7.
8. }
9. var dbobject=databases.db('navigcollection');//use for create database
10.console.log("databases is created")
11.databases.close();
12.
13.})
Now compile this program in terminal and write command for compile

1. node createdb.js

After the compile, you should see that your database looks like this:
Now go to the mongodb compass and refresh the databases. after refreshing thedatabase you see there is
no database in databases.

Because an empty database doesn't show in the database list, to view the databasewe need to again create a
collection in your database. After creating collection your database is shown in the databases list.

Step 10 - Create collection in database

Create a .js file ("createcollection.js") and write code.

createcollection.js

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

4. MongoClient.connect(url,function(error,databases){
3. var
5. if(error){
6. throw error;
7.
8. }
var dbase=databases.db("navigcollection");
10.
9. dbase.createCollection("pract",function(error,response){
11. if(error){
12. throw error;
13. }
14.
15. console.log("collection is created .... ")
16. databases.close();
17. });
18.});
Now compile this program in the terminal and write the command for compile:

1. node createcollection.js

After compiling, the output will look like:

Now go to the database and refresh databases. After refreshing, the output willlook like:
Now click on your database and afterwards, click the collection shown:

Step 11 - Insert record in database

Now insert a record in the collection, to insert a record in the database create a newpage("insert1docu.js") and write code.

insert1docu.js"

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


2.
3. var mongoClient = mongodb.MongoClient;
4. var url = "mongodb://localhost:27017/";
5.
6. mongoClient.connect(url, function(err, databases) {
7. if (err)
8. {
9. throw err;
10. }
11. var nodetestDB = databases.db("navigcollection"); //here
12. var customersCollection = nodetestDB.collection("pract");
13.var customer = {_id:111, name:"Santosh Kumar" , address: "B-
222, Sector-19, NOIDA", orderdata:"Arrow Shirt"};
14.14.
15. customersCollection.insertOne(customer, function(error, response) {
16. if (error) {
17. throw error;
18. }
19.
20. console.log("1 document inserted");
21. databases.close();
22. });
23.});

Now compile this program in terminal write command

1. node insert1docu.js

Output will look like:


Then open database and refresh collection:

Now insert record into the collection, create again a js file ("createmanydocu.js")and write the code:

createmanydocu.js

1. var mongodb=require('mongodb');
2. var MongoClient=mongodb.MongoClient;
3. var url='mongodb://localhost:27017/';
4. MongoClient.connect(url,function(error,databases){
5. if(error){
6. throw error;
7.
8. }
9. var nodtst=databases.db("navigcollection");
10. var pract=[
11. {_id:11,name:"Chaman Gautam" , address: "Harvansh nagar Ghaziabad",
orderdata:"Jeans"},
12. {_id:12,name:"Shivani" , address: "Harvansh nagar Ghaziabad", orderdata:
"Jeans"},
13. {_id:13,name:"Menu" , address: "Harvansh nagar Ghaziabad",
orderdata:"
14. {_id:14,name:"Brajbala" , address: "Harvansh nagar Ghaziabad", orderdat
a:"Dinig table"},
15. {_id:15,name:"Ramsaran" , address: "Harvansh nagar Ghaziabad", orderda
ta:"Washing machine"},
16. {_id:16,name:"Dheeraj" , address: "Harvansh nagar Ghaziabad", orderdata
:"Jeans"}
17. ]
18.nodtst.collection('pract').insertMany(pract , function(error,response){
19. if(error){
20. throw error;
21.
22. }
23. console.log("Numnber of document is inserted ........ ");
24.})
25.})
Now compile this file in the terminal using the command:

1. node insertmanydocu.js

Output will look like:

Now go to the database and refresh the database, the database will look like this:
Step 12 - Find record from databaseFind 1 record

from collection

Now creata a .js page("find1docu.js") create a page and write the code:

1. var mongodb=require("mongodb");
2. var MongoClient=mongodb.MongoClient;
3. var url='mongodb://localhost:27017/';
4. MongoClient.connect(url, function(error, databases){
5. if(error){
6. throw error;
7.
8. }
9. var nodtst = databases.db("navigcollection");
10.
11. nodtst.collection("pract").findOne({name:'Shivani'}, function(err, result) {

12. if (err) throw err;


13. console.log("one record is find now .... "+result.name + ", " + result.addr
ess + ", " + result.orderdata);
14. databases.close();
15. })
16.})

Now compile this program in terminal and write command for compile,

1. node findonedocu.js
Output will look like this:

find many record from collection

Now, create a new .js page("findmanudocu.js") and write the following code:

findmanudocu.js

1. var mongodb=require("mongodb");
2. var MongoClient=mongodb.MongoClient;
3. var url='mongodb://localhost:27017/';
4. MongoClient.connect(url, function(error, databases){
5. if(error){
6. throw error;
7.
8. }
9.
10. var nodtst = databases.db("navigcollection");
11. nodtst.collection("pract").find({}).toArray(function(err, totalpract) {
12. if (err) throw err;
13.
14. for(i = 0; i < totalpract.length; i++) {
15. let pract = totalpract[i];
16. console.log(pract.name + ", " + pract.address + ", " + pract.orderdata);
17. }
18.
19.
20.
21. //console.log(result);
22. databases.close();
23. });
24.});

Now compile this program in terminal and write command for the compile:

1. node findmanydocu.js

After compile, the output will look like,

Step 13 - update record in collectionUpdate one

record from collection


Now you need to create 1 new .js file("updateone.js") and write the code:

updateone.js

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

3. var url="mongodb://localhost:27017/"
4. MongoClient.connect(url,function(error,databases){
5. if(error){
6. throw error;
7.
8. }
9. var nodtst=databases.db("navigcollection");
10.var whereClause = { name:/Chaman Gautam/};
11.var newvalues = { $set: { name:"Lucky Gautam"}};
12.nodtst.collection("pract").updateOne(whereClause,newvalues,function(err,re
s){
13. if(error){
14. throw error;
15.
16. }
17. console.log(res.result.n + "document updated");
18.});
19.});
Now compile this program in terminal and write the command for compile:

1. node updateone.js

After compiling, this command output will show in terminal like this:

The database will show like this without refresh database:


After refresh, the database output will look like this:

Now update records from collection

For update records in your database collection, you need to create a new .jsfile("updatemany.js") and write
code

updatemany.js

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


2.
3. var mongoClient = mongodb.MongoClient;
4. var url = "mongodb://localhost:27017/";
5.
6.
7. mongoClient.connect(url, function(err, databases) {
8. if (err)
9. {
10. throw err;
11. }
12. var nodeDB = databases.db("practicemongo"); //here
13. var myquery = { address: /Harvansh nagar/ };
14. var newvalues = {$set: {name: "Shivani"} };
15. nodeDB.collection("pract").updateMany(myquery, newvalues, function(
err, res) {
16. if (err) throw err;
17. console.log(res.result.nModified + " document(s) updated");
18. databases.close();
19. });
20.
21.
22. });

Now you need to compile this file in terminal using command

1. node updatemany.js

After running this command output will be shown in the terminal like this
Now go to the database

Before refresh database show like this:

After refresh, the database output will look like this now see the address in thiscollection address value will be
changed

Step 14 - now delete operation delete one

record from collection


Now you need to create a new .js file("deleteone.js") and write code

deleteone.js

1. var mongodb=require('mongodb');
2. var MongoClient=mongodb.MongoClient;
3. var url ='mongodb://localhost:27017/';
4. MongoClient.connect(url,function(error,databases){
5. if(error)
6. {
7. throw
error;8. }
9. var nodtst=databases.db('navigcollection');
10. var deleteQuery={name:'Menu'};
11. nodtst.collection("pract").deleteOne(deleteQuery,function(error,response){

12. if(error){
13. throw error;
14.
15. }
16. console.log(response.result.n+" 1 document deleted ..... ");
17. databases.close();
18.
19. })
20.
21.});

Now compile this program in terminal and write command for compile,

1. node deleteone.js

After compiling, the code output will be shown in the terminal like this:
Now go the database and check the database collection Before refreshing the

database output, it's shown like this

After a refresh, the database output will be shown like this:


Now you can see there is no record with the name of Raju

Delete records from database

Now you need again create a .js file ("deletemany.js")

deletemany.js

1. var mongodb=require('mongodb');
2. var MongoClient=mongodb.MongoClient;
3. var url='mongodb://localhost:27017/';
4. MongoClient.connect(url,function(error,databases){
5. if(error)
6. {
7. throw error;
8.
9. }
10. var nodtst=databases.db('navigcollection');
11. var deleteQuery={};
12. nodtst.collection('pract').deleteMany(deleteQuery,function(error,response)
{
13. if(error){
14. throw error;
15.
16. }
17. console.log(response.result.n + "document(s) deleted successfully ..... ");

18. databases.close();
19.
20.
21.
22. })
23.})

Now you need to compile this code in terminal using command

1. node deletemany.js

After compiling this code output is shown in terminal like this:


Now go to the database and check database

Before refresh database, the database will be shown like this

After refresh database is shown like this:


Now you will see that the database has a collection but no record in the collection

Now the CRUD operation in MongoDB using Node.js and VS code is complete.

Node.js MySQL

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 MySQLinstalled 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 byusing Node.js.

To access a MySQL database with Node.js, you need a MySQL driver. Thistutorial will use the
"mysql" module, downloaded from NPM.
To download and install the "mysql" module, open the Command Terminal andexecute the following:

C:\Users\Your Name>npm install mysql

Now you have downloaded and installed a mysql database driver.

Node.js can use this module to manipulate the MySQL database: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!");
});

C:\Users\My Name>node demo_db_connection.jsConnected!

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 alsocalled "to query" the database.

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

con.connect(function(err) { 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.

ExpressJS - Cookies
Cookies are simple, small files/data that are sent to client with a server request and stored on the client side.
Every time the user loads the website back, this cookie is sent with the request. This helps us keep track of the
user’s actions.
The following are the numerous uses of the HTTP Cookies −

• Session management
• Personalization(Recommendation systems)
• User tracking
To use cookies with Express, we need the cookie-parser middleware. To install it,
use the following code −

npm install --save cookie-parser


Now to use cookies with Express, we will require the cookie-parser. cookie-parser
is a middleware which parses cookies attached to the client request object. To use
it, we will require it in our index.js file; this can be used the same way as we useother middleware. Here,
we will use the following code.
var cookieParser = require('cookie-parser');
app.use(cookieParser());
cookie-parser parses Cookie header and populates req.cookies with an object keyed by the cookie names. To
set a new cookie, let us define a new route in your Express app like −
var express = require('express');var app =
express();

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

res.cookie('name', 'express').send('cookie set'); //Sets name = express


});

app.listen(3000);

To check if your cookie is set or not, just go to your browser, fire up the console,
and enter −
console.log(document.cookie);
You will get the output like (you may have more cookies set maybe due to
extensions in your browser) −
"name = express"
The browser also sends back cookies every time it queries the server. To view cookies from your server, on the
server console in a route, add the following code to that route.
console.log('Cookies: ', req.cookies);
Next time you send a request to this route, you will receive the following output.Cookies: { name: 'express'
}

Adding Cookies with Expiration Time

You can add cookies that expire. To add a cookie that expires, just pass an objectwith property 'expire' set to
the time when you want it to expire. For example,
//Expires after 360000 ms from the time it is set. res.cookie(name, 'value',
{expire: 360000 + Date.now()});
Another way to set expiration time is using 'maxAge' property. Using this
property, we can provide relative time instead of absolute time. Following is an
example of this method.
//This cookie also expires after 360000 ms from the time
it is set.res.cookie(name, 'value', {maxAge: 360000});

Deleting Existing Cookies

To delete a cookie, use the clearCookie function. For example, if you need to
cleara cookie named foo, use the following code.
var express
=
require('exp
ress');var
app =
express();

app.get('/clear_cookie_foo',
function(req, res){
res.clearCookie('foo');
res.send('cookie foo cleared');
});

app.listen(3000);

HANDLING USER AUTHENTICATION WITH NODE.JS USE 1ST LAB


PROGRAM AND EXPLAIN

You might also like