Server Side Development
Server Side Development
MongoDB
NAVEEN SAGGAM
http://github.com/thenaveensaggam
What is Node JS
Node.js is an open-source, cross-platform runtime environment used for development of
server-side web applications. Node.js applications are written in JavaScript and can be run on a
wide variety of operating systems.
Over a long period of time, the framework available for web development were all based on a
stateless model. A stateless model is where the data generated in one session (such as
information about user settings and events that occurred) is not maintained for usage in the
next session with that user.
A lot of work had to be done to maintain the session information between requests for a user.
But with Node.js there is finally a way for web applications to have a real-time, two-way
connections, where both the client and server can initiate communication, allowing them to
exchange data freely.
Features of Node.js
Let's look at some of the key features of Node.js
var fs = require('fs');
fs.readFile("Sample.txt",function(error,data)
{
Chat applications
Game servers – Fast and high-performance servers that need to processes thousands of
requests at a time, then this is an ideal framework.
Good for collaborative environment – This is good for environments which manage
document. In document management environment you will have multiple people who post
their documents and do constant changes by checking out and checking in documents. So
Node.js is good for these environments because the event loop in Node.js can be triggered
whenever documents are changed in a document managed environment.
Advertisement servers – Again here you could have thousands of request to pull
advertisements from the central server and Node.js can be an ideal framework to handle this.
Streaming servers – Another ideal scenario to use Node is for multimedia streaming servers
wherein clients have request's to pull different multimedia contents from this server.
Node.js is good when you need high levels of concurrency but less amount of dedicated CPU
time.
Best of all, since Node.js is built on javascript, it's best suited when you build client-side
applications which are based on the same javascript framework.
An event loop is constantly watching for the events to be raised for an asynchronous job and
executing callback function when the job completes. Internally, Node.js uses libevfor the event
loop which in turn uses internal C++ thread pool to provide asynchronous I/O.
The following figure illustrates asynchronous web server model using Node.js.
Node JS Installation
We can install the node JS from the official website https://nodejs.org/en/
Select the Destination path, keep the default program files location.
REPL stands for Read Eval Print Loop and it represents a computer environment like a Windows
console or Unix/Linux shell where a command is entered and the system responds with an output
in an interactive mode. Node.js or Node comes bundled with a REPL environment. It performs
the following tasks:
● Read - Reads user's input, parses the input into JavaScript data-structure, and stores in
memory.
● Loop - Loops the above command until the user presses ctrl-c twice. The REPL feature of Node
is very useful in experimenting with Node.js codes and to debug JavaScript codes
Simple Expressions
Use variables
You can make use variables to store values and print later like any conventional script. If var
keyword is not used, then the 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
console.log().
Multiline Expression
Node REPL supports multiline expression similar to JavaScript. Let's check the following dowhile
loop in action:
REPL Commands
Node.js Basics
Node.js supports JavaScript. So, JavaScript syntax on Node.js is similar to the browser's
JavaScript syntax.
Primitive Types
Node.js includes following primitive types:
1. String
2. Number
3. Boolean
4. Undefined
5. Null
Everything else is an object in Node.js.
Loose Typing
JavaScript in Node.js supports loose typing like the browser's JavaScript. Use let keyword to
declare a variable of any type.
Object Literal
Object literal syntax is same as browser's JavaScript.
Buffer
Node.js includes an additional data type called Buffer (not available in browser's JavaScript).
Buffer is mainly used to store binary data, while reading from a file or receiving packets over
the network.
process object
Each Node.js script runs in a process. It includes process object to get all the information about
the current process of Node.js application.
The following example shows how to get process information in REPL using process object.
Defaults to local
Node's JavaScript is different from browser's JavaScript when it comes to global scope. In the
browser's JavaScript, variables declared without var keyword become global. In Node.js,
everything becomes local by default.
Now, you can import log object using require() function and use it anywhere in your Node.js
project.
Node.js Module
Module in Node.js is a simple or complex functionality organized in single or multiple JavaScript
files which can be reused throughout the Node.js application.
1. Core Modules
2. Custom / Local Modules
3. Third Party Modules
The following table lists some of the important core modules in Node.js.
url url module includes methods for URL resolution and parsing.
In order to use Node.js core or NPM modules, you first need to import it using require()
function as shown below.
As per above syntax, specify the module name in the require() function. The require() function
will return an object, function, property or any other JavaScript type, depending on what the
specified module returns.
The following example demonstrates how to use Node.js http module
In the above example, require() function returns an object because http module returns its
functionality as an object, you can then use its properties and methods using dot notation.
In the above example of logging module, we have created an object with three functions -
info(), warning() and error(). At the end, we have assigned this object to module.exports. The
module.exports in the above example exposes a log object as a module.
The module.exports is a special object which is included in every JS file in the Node.js
application by default. Use module.exports or exports to expose a function, object or variable
as a module in Node.js.
Now, let's see how to use the above logging module in our application.
To use local modules in your application, you need to load it using require() function in the
same way as core module. However, you need to specify the path of JavaScript file of the
module.
The following example demonstrates how to use the above logging module contained in Log.js.
In the above example, app.js is using log module. First, it loads the logging module using
require() function and specified path where logging module is stored. Logging module is
contained in Log.js file in the root folder. So, we have specified the path './log.js' or './log' in the
require() function. The '.' denotes a root folder.
Export Literals
As mentioned above, exports is an object. So it exposes whatever you assigned to it as a
module. For example, if you assign a string literal then it will expose that string literal as a
module.
The following example exposes simple string message as a module in Message.js.
Note: You must specify './' as a path of root folder to import a local module. However, you do
not need to specify path to import Node.js core module or NPM module in the require()
function.
Export Object
exports is an object. So, you can attach properties or methods to it. The following example
exposes an object with a string property in Message.js file.
The same way as above, you can expose an object with function. The following example
exposes an object with log function as a module.
Export Function
You can attach an anonymous function to exports object as shown below.
In the above example, . is for root folder and then specify exact path of your module file.
Node.js also allows us to specify the path to the folder without specifying file name.
If you have an older version of NPM then you can update it to the latest version using the
following command.
To access NPM help, write npm help in the command prompt or terminal window.
For example, the following command will install ExpressJS into Project1 folder.
All the modules installed using NPM are installed under node_modules folder. The above
command will create ExpressJS folder under node_modules folder in the root folder of your
project and install Express.js there.
Update Package
To update the package installed locally in your Node.js project, navigate the command prompt
or terminal window path to the project folder and write the following update command.
The following command will update the existing ExpressJS module to the latest version.
Uninstall Packages
Use the following command to remove a local package from your project.
Node JS Webserver
In this section, we will learn how to create a simple Node.js web server and handle HTTP
requests.
In this section, we will learn how to create a simple Node.js web server and handle HTTP
requests.
To access web pages of any web application, you need a web server. The web server will handle
all the http requests for the web application.
e.g: IIS is a web server for ASP.NET web applications
Apache is a web server for PHP or Java web applications.
Node.js provides capabilities to create your own web server which will handle HTTP requests
asynchronously.
The following example demonstrates handling HTTP request and response in Node.js
For Windows users, point your browser to http://localhost:3000 and see the following result.
Reading File
Parameter Description:
The above example reads data.txt (on Windows) asynchronously and executes callback function
when read operation completes.
This read operation either throws an error or completes successfully. The err parameter
contains error information if any. The data parameter contains the content of the specified file.
Writing File
Use fs.writeFile() method to write data to a file. If file already exists then it overwrites the
existing content otherwise it creates a new file and writes data into it.
Parameter Description:
filename: Full path and name of the file as a string.
Data: The content to be written in a file.
options: The options parameter can be an object or string which can include encoding, mode
and flag. The default encoding is utf8 and default flag is "r".
In the same way, use fs.appendFile() method to append the content to an existing file.
Delete File
Use fs.unlink() method to delete an existing file.
There are various third party open-source frameworks available in Node Package Manager
which makes Node.js application development faster and easy. You can choose an appropriate
framework as per your application requirements.
The following table lists frameworks for Node.js.
Express.js
"Express is a fast, un-opinionated minimalist web framework for Node.js" - official web site:
Expressjs.com
Express.js is a web application framework for Node.js. It provides various features that make
web application development fast and easy which otherwise takes more time using only
Node.js.
Express.js is based on the Node.js middleware module called connect which in turn uses http
module. So, any middleware which is based on connect will also work with Express.js.
Advantages of Express.js
Makes Node.js web application development fast and easy.
Install Express.js
You can install express.js using npm. The following command will install latest version of
express.js globally on your machine so that every Node.js application on your machine can use
it.
The following command will install latest version of express.js local to your project folder.
As you know, --save will update the package.json file by specifying express.js dependency.
Web Server
First of all, import the Express.js module and create the web server as shown below.
Configure Routes
Use app object to define different routes of your application. The app object includes get(),
post(), put() and delete() methods to define routes for HTTP GET, POST, PUT and DELETE
requests respectively.
The following example demonstrates configuring routes for HTTP requests.
In the above example, app.get(), app.post(), app.put() and app.delete() methods define routes
for HTTP GET, POST, PUT, DELETE respectively. The first parameter is a path of a route which
will start after base URL. The callback function includes request and response object which will
be executed on each request.
To handle HTTP POST request in Express.js version 4 and above, you need to install middleware
module called body-parser. The middleware was a part of Express.js earlier but now you have
to install it separately.
This body-parser module parses the JSON, buffer, string and url encoded data submitted using
HTTP POST request. Install body-parser using NPM as shown below.
Now, import body-parser and get the POST request data as shown below.
In the above example, app.use() method mounts the middleware express.static for every
request. The express.static middleware is responsible for serving the static assets of an
Express.js application. The express.static() method specifies the folder from which to serve all
static resources.
Now, run the above code using node server.js command and point your browser to
http://127.0.0.1:3000/myImage.jpg and it will display myImage.jpg from the public folder
(public folder should have myImage.jpg).
If you have different folders for different types of resources then you can set express.static
middleware as shown below.
To access the database from Node.js, you first need to install drivers for the database you want
to use.
The following table lists important relational databases and respective drivers.
This Template Engine is used to display any dynamic data from the server to the browser.
In this, we won't use DOM manipulation because the data has to serve from the server.
In this template Engine, we mix the JavaScript code with the HTML Tags. with EJS Syntax.
Each file which is serving dynamic data from the server using EJS should be have an extension '.ejs'
Mostly all the Template Engine files are to be kept in the ‘views’ folder. This is the default
folder location the express js looks for ejs files / template engine specific files. Other than this
folder we have to mention in the middleware.
To send any response back to browser in the form of ejs file, we use the ‘render()’ function to
send the ejs / template engine data.
Any data/objects to be send to the front end, we have to send them using the above syntax like
pageTitle and page parameters.
We can access this data / parameters / Objects on the frontend ejs file using the ejs file syntax
as follows,
Let’s see the different between HTML page and Pug template as follows,
If you are familiar with HTML language, there you can easily learn PUG template.
There are many online tools available for this PUG template Conversion such as,
https://html2jade.org/ OR https://html-to-pug.com/
In order to display any dynamic data with the template we use the following Syntax,
Mostly all the Template Engine files are to be kept in the ‘views’ folder. This is the default
folder location the express js looks for pug files / template engine specific files. Other than this
folder we have to mention in the middleware.
To send any response back to browser in the form of pug file, we use the ‘render()’ function to
send the pug / template engine data.
For More Information on this PUG Template Engine, you can refer the website,
Database
Database is a physical container for collections. Each database gets its own set of files on the
file system. A single MongoDB server typically has multiple databases.
Collection
Collection is a group of MongoDB documents. It is the equivalent of an RDBMS table. A
collection exists within a single database. Collections do not enforce a schema. Documents
within a collection can have different fields. Typically, all documents in a collection are of
similar or related purpose.
Document
A document is a set of key-value pairs. Documents have dynamic schema. Dynamic schema
means that documents in the same collection do not need to have the same set of fields or
structure, and common fields in a collection's documents may hold different types of data.
The following table shows the relationship of RDBMS terminology with MongoDB.
Sample Document
Following example shows the document structure of a blog site, which is simply a comma
separated key value pair.
_id is a 12 bytes hexadecimal number which assures the uniqueness of every document. You
can provide _id while inserting the document. If you don’t provide then MongoDB provides a
unique id for every document. These 12 bytes first 4 bytes for the current timestamp, next 3
bytes for machine id, next 2 bytes for process id of MongoDB server and remaining 3 bytes are
simple incremental VALUE.
Any relational database has a typical schema design that shows number of tables and the
relationship between these tables. While in MongoDB, there is no concept of relationship.
C:\Program Files\MongoDB\Server\4.0\bin
Select the System Environment Variables, Select the Path and click on Edit and Click on New
option, paste the Address you copied and click on OK => OK => OK.
You should see the message like connecting to MongoDB, It says you have successfully installed
the MongoDB and connected to it successfully.
Syntax
Basic syntax of use DATABASE statement is as follows
If you want to use a database with name showroom then use DATABASE statement would be
as follows
If you want to check your databases list, use the command show dbs.
Your created database (showroom) is not present in list. To display database, you need to insert
at least one document into it.
To use this first your need to switch the required database and type this command to delete
the database.
In the command, name is name of collection to be created. Options is a document and is used
to specify configuration of collection.
Basic syntax of createCollection() method without options is as follows
In MongoDB, you don't need to create collection. MongoDB creates collection automatically,
when you insert some document.
Arrays − This type is used to store arrays or list or multiple values into one key.
Timestamp − ctimestamp. This can be handy for recording when a document has been
modified or added.
Object − This datatype is used for embedded documents.
Null − This type is used to store a Null value.
Symbol − This datatype is used identically to a string; however, it's generally reserved for
languages that use a specific symbol type.
Date − This datatype is used to store the current date or time in UNIX time format. You can
specify your own date time by creating object of Date and passing day, month, year into it.
Object ID − This datatype is used to store the document’s ID.
In MongoDB, insert operations target a single collection. All write operations in MongoDB are
atomic on the level of a single document.
insertOne() returns a document that includes the newly inserted document’s _id field value. For
an example of a return document, see db.collection.insertOne() reference.
To retrieve the document that you just inserted, query the collection:
You can specify query filters or criteria that identify the documents to return.
To select all documents in the collection, pass an empty document as the query filter parameter
to the find method. The query filter parameter determines the select criteria:
The following example selects from the inventory collection all documents where the status
equals "D":
A query filter document can use the query operators to specify conditions in the following form
The following example retrieves all documents from the inventory collection where status
equals either "A" or "D":
A compound query can specify conditions for more than one field in the collection’s
documents. Implicitly, a logical AND conjunction connects the clauses of a compound query so
that the query selects the documents in the collection that match all the conditions.
The following example retrieves all documents in the inventory collection where the status
equals "A" and qty is less than ($lt) 30:
Using the $or operator, you can specify a compound query that joins each clause with a logical
OR conjunction so that the query selects the documents in the collection that match at least
one condition.
In the following example, the compound query document selects all documents in the
collection where the status equals "A" and either qty is less than ($lt) 30 or item starts with the
character p:
The following examples use the inventory collection. To create and/or populate the inventory
collection
To update a document, MongoDB provides update operators, such as $set, to modify field
values.
To use the update operators, pass to the update methods an update document of the form:
The examples on this page use the inventory collection. To populate the inventory collection,
run the following:
To delete all documents from a collection, pass an empty filter document {} to the
db.collection.deleteMany() method.
The following example deletes all documents from the inventory collection
A query filter document can use the query operators to specify conditions in the following form:
To delete all documents that match a deletion criteria, pass a filter parameter to the
deleteMany() method.
The following example removes all documents from the inventory collection where the status
field equals "A":
The method returns a document with the status of the operation. For more information and
examples, see deleteMany().
To delete at most a single document that matches a specified filter (even though multiple
documents may match the specified filter) use the db.collection.deleteOne() method.
The following example deletes the first document where status is "D"