0% found this document useful (0 votes)
20 views91 pages

AWP HandBook ADVANCED WEB PROGRAMMING 3161611

The document provides an overview of advanced web programming concepts, focusing on JavaScript objects, the Document Object Model (DOM), and AngularJS. It explains how to create and manipulate JavaScript objects, access and modify HTML elements using the DOM, and introduces AngularJS as a framework for building dynamic web applications. Additionally, it covers Bootstrap as a responsive design framework and includes examples of code for practical understanding.

Uploaded by

Tushar Parmar
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)
20 views91 pages

AWP HandBook ADVANCED WEB PROGRAMMING 3161611

The document provides an overview of advanced web programming concepts, focusing on JavaScript objects, the Document Object Model (DOM), and AngularJS. It explains how to create and manipulate JavaScript objects, access and modify HTML elements using the DOM, and introduces AngularJS as a framework for building dynamic web applications. Additionally, it covers Bootstrap as a responsive design framework and includes examples of code for practical understanding.

Uploaded by

Tushar Parmar
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/ 91

ADVANCED WEB PROGRAMMING

Subject Code: 3161611

1.JavaScript Objects

In JavaScript, almost "everything" is an object.

● Booleans can be objects (if defined with the new keyword)


● Numbers can be objects (if defined with the new keyword)
● Strings can be objects (if defined with the new keyword)
● Dates are always objects
● Maths are always objects
● Regular expressions are always objects
● Arrays are always objects
● Functions are always objects
● Objects are always objects

All JavaScript values, except primitives, are objects.

A JavaScript object is a collection of named values


Creating a JavaScript Object

With JavaScript, you can define and create your own objects.

There are different ways to create new objects:

● Define and create a single object, using an object literal.


● Define and create a single object, with the keyword new.
● Define an object constructor, and then create objects of the constructed type.

var person = {fname:"John", lname:"Doe", age:25};

for (x in person) {

txt += person[x];

}
JavaScript Object Methods

var person = {

firstName: "John",

lastName : "Doe",

id : 5566,

fullName : function() {

return this.firstName + " " + this.lastName;

JavaScript Display Objects

<!DOCTYPE html>

<html>

<body>

<h2>JavaScript Display Object Properties</h2>

<p id="demo"></p>

<script>

var person = {name:"John", age:50, city:"New York"};

document.getElementById("demo").innerHTML = person.name + "," + person.age + "," +


person.city;

</script>
</body>

</html>

JavaScript HTML DOM

With the object model, JavaScript gets all the power it needs to create dynamic HTML:

● JavaScript can change all the HTML elements in the page


● JavaScript can change all the HTML attributes in the page
● JavaScript can change all the CSS styles in the page
● JavaScript can remove existing HTML elements and attributes
● JavaScript can add new HTML elements and attributes
● JavaScript can react to all existing HTML events in the page
● JavaScript can create new HTML events in the page

2. What is the DOM?

The DOM is a W3C (World Wide Web Consortium) standard.

The DOM defines a standard for accessing documents:

"The W3C Document Object Model (DOM) is a platform and language-neutral interface that
allows programs and scripts to dynamically access and update the content, structure, and style
of a document."
The W3C DOM standard is separated into 3 different parts:

● Core DOM - standard model for all document types


● XML DOM - standard model for XML documents
● HTML DOM - standard model for HTML documents

What is the HTML DOM?

The HTML DOM is a standard object model and programming interface for HTML. It defines:

● The HTML elements as objects


● The properties of all HTML elements
● The methods to access all HTML elements
● The events for all HTML elements

In other words: The HTML DOM is a standard for how to get, change, add, or delete HTML
elements.

<html>

<body>

<p id="demo"></p>

<script>

document.getElementById("demo").innerHTML = "Hello World!";

</script>

</body>

</html>

The HTML DOM Document Object


The document object represents your web page.

If you want to access any element in an HTML page, you always start with accessing the
document object.

Below are some examples of how you can use the document object to access and manipulate
HTML.

Finding HTML Elements

Method Description

document.getElementById(​id​) Find an element by element id

document.getElementsByTagName(​name​) Find elements by tag name

document.getElementsByClassName(​name)​ Find elements by class name

Changing HTML Elements

Property Description
element.​ innerHTML = ​new html content Change the inner HTML of an element

element.​ ​attribute = new value Change the attribute value of an HTML


element

element.​ style.​property = new style Change the style of an HTML element

Method Description

element.​ setAttribute​(attribute, value) Change the attribute value of an HTML


element

Adding and Deleting Elements

Method Description

document.createElement(​element)​ Create an HTML element

document.removeChild(​element​) Remove an HTML element

document.appendChild(​element)​ Add an HTML element


document.replaceChild(​new, old​) Replace an HTML element

document.write(​text​) Write into the HTML output stream

Adding Events Handlers

Method Description

document.getElementById(​id​).onclick = Adding event handler code to an onclick


function(){​code}​ event

Finding HTML Objects

The first HTML DOM Level 1 (1998), defined 11 HTML objects, object collections, and
properties. These are still valid in HTML5.

Later, in HTML DOM Level 3, more objects, collections, and properties were added.
Property Description DOM

document.anchors Returns all <a> elements that have a name 1


attribute

document.applets Returns all <applet> elements (Deprecated in 1


HTML5)

document.baseURI Returns the absolute base URI of the document 3

document.body Returns the <body> element 1

document.cookie Returns the document's cookie 1

document.doctype Returns the document's doctype 3

document.documentEle Returns the <html> element 3


ment

document.documentMod Returns the mode used by the browser 3


e

document.documentURI Returns the URI of the document 3


document.domain Returns the domain name of the document 1
server

document.domConfig Obsolete. Returns the DOM configuration 3

document.embeds Returns all <embed> elements 3

document.forms Returns all <form> elements 1

document.head Returns the <head> element 3

document.images Returns all <img> elements 1

document.implementatio Returns the DOM implementation 3


n

document.inputEncoding Returns the document's encoding (character set) 3

document.lastModified Returns the date and time the document was 3


updated

document.links Returns all <area> and <a> elements that have a 1


href attribute
document.readyState Returns the (loading) status of the document 3

document.referrer Returns the URI of the referrer (the linking 1


document)

document.scripts Returns all <script> elements 3

document.strictErrorChe Returns if error checking is enforced 3


cking

document.title Returns the <title> element 1

document.URL Returns the complete URL of the document 1

3. How to find HTML Elements

Often, with JavaScript, you want to manipulate HTML elements.

To do so, you have to find the elements first. There are several ways to do this:

● Finding HTML elements by id


● Finding HTML elements by tag name
● Finding HTML elements by class name
● Finding HTML elements by CSS selectors
● Finding HTML elements by HTML object collections

var myElement = document.getElementById("intro");

var x = document.getElementsByTagName("p");
var x = document.getElementsByClassName("intro");

var x = document.querySelectorAll("p.intro");

Ex:

<!DOCTYPE html>

<html>

<body>

<h2>Finding HTML Elements Using document.forms</h2>

<form id="frm1" action="/action_page.php">

First name: <input type="text" name="fname" value="Donald"><br>

Last name: <input type="text" name="lname" value="Duck"><br><br>

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

</form>

<p>Click "Try it" to display the value of each element in the form.</p>

<button onclick="myFunction()">Try it</button>


<p id="demo"></p>

<script>

function myFunction() {

var x = document.forms["frm1"];

var text = "";

var i;

for (i = 0; i < x.length ;i++) {

text += x.elements[i].value + "<br>";

document.getElementById("demo").innerHTML = text;

</script>

</body>

</html>

4. HTML events:

● When a user clicks the mouse


● When a web page has loaded
● When an image has been loaded
● When the mouse moves over an element
● When an input field is changed
● When an HTML form is submitted
● When a user strokes a key

Ex.

<!DOCTYPE html>

<html>

<body>

<p>Click "Try it" to execute the displayDate() function.</p>

<button id="myBtn">Try it</button>

<p id="demo"></p>

<script>

document.getElementById("myBtn").onclick = displayDate;

function displayDate() {

document.getElementById("demo").innerHTML = Date();

</script>

</body>
</html>

Ex.

<!DOCTYPE html>

<html>

<head>

<script>

function myFunction(x) {

x.style.background = "yellow";

</script>

</head>

<body>

Enter your name: <input type="text" onfocus="myFunction(this)">

<p>When the input field gets focus, a function is triggered which changes the
background-color.</p>

</body>

</html>

5. What is ​Bootstrap
Bootstrap 4 is the newest version of ​Bootstrap​, which is the most popular HTML, CSS, and
JavaScript framework for developing responsive, mobile-first websites.

What is Bootstrap?

● Bootstrap is a free front-end framework for faster and easier web development
● Bootstrap includes HTML and CSS based design templates for typography, forms,
buttons, tables, navigation, modals, image carousels and many other, as well as optional
JavaScript plugins
● Bootstrap also gives you the ability to easily create responsive designs

What is Responsive Web Design?

Responsive web design is about creating web sites which automatically adjust themselves to
look good on all devices, from small phones to large desktops.

Chapter : 2 Introduction to Angular JS

1. What Is AngularJS

AngularJS is a JavaScript framework. It can be added to an HTML page with a <script> tag.

AngularJS extends HTML attributes with Directives, and binds data to HTML with Expressions.

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>

AngularJS Extends HTML

AngularJS extends HTML with ng-directives.

The ng-app directive defines an AngularJS application.

The ng-model directive binds the value of HTML controls (input, select, textarea) to application
data.

The ng-bind directive binds application data to the HTML view.

Ex.
<!DOCTYPE html>

<html>

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>

<body>

<div ng-app="">

<p>Input something in the input box:</p>

<p>Name: <input type="text" ng-model="name"></p>

<p ng-bind="name"></p>

</div>

</body>

</html>

AngularJS starts automatically when the web page has loaded.

The ng-app directive tells AngularJS that the <div> element is the "owner" of an AngularJS
application.

The ng-model directive binds the value of the input field to the application variable name.

The ng-bind directive binds the content of the <p> element to the application variable name

<!DOCTYPE html>
<html>

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>

<body>

<div ng-app="">

<p>Input something in the input box:</p>

<p>Name: <input type="text" ng-model="name"></p>

<p>{{name}}</p>

</div>

</body>

</html>

2. AngularJS Applications

AngularJS modules define AngularJS applications.

AngularJS controllers control AngularJS applications.

The ng-app directive defines the application, the ng-controller directive defines the controller.

Ex:

<!DOCTYPE html>

<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>

<body>

<p>Try to change the names.</p>

<div ng-app="myApp" ng-controller="myCtrl">

First Name: <input type="text" ng-model="firstName"><br>

Last Name: <input type="text" ng-model="lastName"><br>

<br>

Full Name: {{firstName + " " + lastName}}

</div>

<script>

var app = angular.module('myApp', []);

app.controller('myCtrl', function($scope) {

$scope.firstName= "John";

$scope.lastName= "Doe";

});

</script>
</body>

</html>

3. AngularJS Expressions

AngularJS expressions can be written inside double braces: {{ ​expression​ }}.

AngularJS expressions can also be written inside a directive: ng-bind="​expression"​ .

AngularJS will resolve the expression, and return the result exactly where the expression is
written.

AngularJS expressions are much like JavaScript expressions: They can contain literals, operators,
and variables.

Example {{ 5 + 5 }} or {{ firstName + " " + lastName }}

ex.

<!DOCTYPE html>

<html>

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>

<body>

<p>Change the value of the input field:</p>


<div ng-app="" ng-init="myCol='lightblue'">

<input style="background-color:{{myCol}}" ng-model="myCol">

</div>

<p>AngularJS resolves the expression and returns the result.</p>

<p>The background color of the input box will be whatever you write in the input field.</p>

</body>

</html>

Ex.

<!DOCTYPE html>

<html>

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>

<body>
<div ng-app="" ng-init="quantity=1;cost=5">

<p>Total in dollar: <span ng-bind="quantity * cost"></span></p>

</div>

</body>

</html>

Ex.

<!DOCTYPE html>

<html>

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>

<body>

<div ng-app="" ng-init="firstName='John';lastName='Doe'">

<p>The full name is: <span ng-bind="firstName + ' ' + lastName"></span></p>

</div>

</body>
</html>

Ex.

<!DOCTYPE html>

<html>

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>

<body>

<div ng-app="" ng-init="person={firstName:'John',lastName:'Doe'}">

<p>The name is {{ person.lastName }}</p>

</div>

</body>

</html>

Ex.

<!DOCTYPE html>
<html>

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>

<body>

<div ng-app="" ng-init="points=[1,15,19,2,40]">

<p>The third result is <span ng-bind="points[2]"></span></p>

</div>

</body>

</html>

4. AngularJS Modules

An AngularJS module defines an application.

The module is a container for the different parts of an application.

The module is a container for the application controllers.

Controllers always belong to a module.

Creating a Module
A module is created by using the AngularJS function angular.module

<div ng-app="myApp">...</div>

<script>

var app = angular.module("myApp", []);

</script>

The "myApp" parameter refers to an HTML element in which the application will run.

Now you can add controllers, directives, filters, and more, to your AngularJS application.

Adding a Controller

Add a controller to your application, and refer to the controller with the ng-controller directive:

<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body>

<div ng-app="myApp" ng-controller="myCtrl">


{{ firstName + " " + lastName }}
</div>

<script>
var app = angular.module("myApp", []);
app.controller("myCtrl", function($scope) {
$scope.firstName = "John";
$scope.lastName = "Doe";
});
</script>

</body>
</html>

Adding a Directive

<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body>

<div ng-app="myApp" w3-test-directive></div>

<script>
var app = angular.module("myApp", []);
app.directive("w3TestDirective", function() {
return {
template : "I was made in a directive constructor!"
};
});
</script>

</body>
</html>

5. Modules and Controllers in Files

It is common in AngularJS applications to put the module and the controllers in JavaScript files.

In this example, "myApp.js" contains an application module definition, while "myCtrl.js"


contains the controller:

Example
<!DOCTYPE html>

<html>

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>

<body>

<div ng-app="myApp" ng-controller="myCtrl">

{{ firstName + " " + lastName }}

</div>

<script src="myApp.js"></script>

<script src="myCtrl.js"></script>

</body>

</html>

myApp.js

var app = angular.module("myApp", []);

The [] parameter in the module definition can be used to define dependent modules.
Without the [] parameter, you are not ​creating​ a new module, but ​retrieving​ an existing one.

myCtrl.js

app.controller("myCtrl", function($scope) {

$scope.firstName = "John";

$scope.lastName= "Doe";

});

<!DOCTYPE html>
<html>
<body>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>

<div ng-app="myApp" ng-controller="myCtrl">


{{ firstName + " " + lastName }}
</div>

<script>
var app = angular.module("myApp", []);
app.controller("myCtrl", function($scope) {
$scope.firstName = "John";
$scope.lastName = "Doe";
});
</script>

<p>It is recommended that you load the AngularJS library either in the HEAD or at the start of
the BODY.</p>

</body>
</html>
6. AngularJS Directives

AngularJS lets you extend HTML with new attributes called Directives.

AngularJS has a set of built-in directives which offers functionality to your applications.

AngularJS also lets you define your own directives.

AngularJS Directives

AngularJS directives are extended HTML attributes with the prefix ​ng-​.

The ​ng-app​ directive initializes an AngularJS application.

The ​ng-init​ directive initializes application data.

The ​ng-model​ directive binds the value of HTML controls (input, select, textarea) to application
data.

Ex.
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body>

<div ng-app="" ng-init="firstName='John'">

<p>Input something in the input box:</p>


<p>Name: <input type="text" ng-model="firstName"></p>
<p>You wrote: {{ firstName }}</p>

</div>

</body>
</html>
The ​ng-app​ directive also tells AngularJS that the <div> element is the "owner" of the AngularJS
application.

7. Data Binding

The ​{{ firstName }}​ expression, in the example above, is an AngularJS data binding expression.

Data binding in AngularJS binds AngularJS expressions with AngularJS data.

{{ firstName }}​ is bound with ​ng-model="firstName"​.

In the next example two text fields are bound together with two ng-model directives:

<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body>

<div data-ng-app="" data-ng-init="quantity=1;price=5">

<h2>Cost Calculator</h2>

Quantity: <input type="number" ng-model="quantity">


Price: <input type="number" ng-model="price">

<p><b>Total in dollar:</b> {{quantity * price}}</p>

</div>

</body>
</html>
Repeating HTML Elements

The ​ng-repeat​ directive repeats an HTML element:

<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body>

<div ng-app="" ng-init="names=['Jani','Hege','Kai']">


<p>Looping with ng-repeat:</p>
<ul>
<li ng-repeat="x in names">
{{ x }}
</li>
</ul>
</div>

</body>
</html>

The ​ng-repeat​ directive actually clones HTML elements once for each item in a collection.

The ​ng-repeat​ directive used on an array of objects:

Ex.
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body>

<div ng-app="" ng-init="names=[


{name:'Jani',country:'Norway'},
{name:'Hege',country:'Sweden'},
{name:'Kai',country:'Denmark'}]">

<p>Looping with objects:</p>


<ul>
<li ng-repeat="x in names">
{{ x.name + ', ' + x.country }}</li>
</ul>

</div>

</body>
</html>

The ng-app Directive

The ​ng-app​ directive defines the root element of an AngularJS application.

The ​ng-app​ directive will auto-bootstrap (automatically initialize) the application when a web
page is loaded.

The ng-init Directive

The ​ng-init​ directive defines initial values for an AngularJS application.

Normally, you will not use ng-init. You will use a controller or module instead.

The ng-model Directive

The ​ng-model​ directive binds the value of HTML controls (input, select, textarea) to application
data.

The ​ng-model​ directive can also:

● Provide type validation for application data (number, email, required).


● Provide status for application data (invalid, dirty, touched, error).
● Provide CSS classes for HTML elements.
● Bind HTML elements to HTML forms.

Read more about the ​ng-model​ directive in the next chapter.

8. Create New Directives

In addition to all the built-in AngularJS directives, you can create your own directives.

New directives are created by using the ​.directive​ function.


To invoke the new directive, make an HTML element with the same tag name as the new
directive.

When naming a directive, you must use a camel case name, ​w3TestDirective​, but when invoking
it, you must use ​-​ separated name, ​w3-test-directive​:

<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body ng-app="myApp">

<w3-test-directive></w3-test-directive>

<script>
var app = angular.module("myApp", []);
app.directive("w3TestDirective", function() {
return {
template : "<h1>Made by a directive!</h1>"
};
});
</script>

</body>
</html>

You can invoke a directive by using:

● Element name
● Attribute
● Class
● Comment

The examples below will all produce the same result:

Element name

<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body ng-app="myApp">

<w3-test-directive></w3-test-directive>

<script>
var app = angular.module("myApp", []);
app.directive("w3TestDirective", function() {
return {
template : "<h1>Made by a directive!</h1>"
};
});
</script>

</body>
</html>

9. Attribute

<!DOCTYPE html>

<html>

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>

<body ng-app="myApp">

<div w3-test-directive></div>

<script>

var app = angular.module("myApp", []);


app.directive("w3TestDirective", function() {

return {

template : "<h1>Made by a directive!</h1>"

};

});

</script>

</body>

</html>

Class

Ex.

<!DOCTYPE html>

<html>

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>

<body ng-app="myApp">

<div class="w3-test-directive"></div>

<script>
var app = angular.module("myApp", []);

app.directive("w3TestDirective", function() {

return {

restrict : "C",

template : "<h1>Made by a directive!</h1>"

};

});

</script>

<p><strong>Note:</strong> You must add the value "C" to the restrict property to be able to invoke
the directive from a class name.</p>

</body>

</html>

Restrictions

You can restrict your directives to only be invoked by some of the methods.

Example

By adding a ​restrict​ property with the value ​"A"​, the directive can only be invoked by attributes:

<!DOCTYPE html>

<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>

<body ng-app="myApp">

<w3-test-directive></w3-test-directive>

<div w3-test-directive></div>

<script>

var app = angular.module("myApp", []);

app.directive("w3TestDirective", function() {

return {

restrict : "A",

template : "<h1>Made by a directive!</h1>"

};

});

</script>

<p><strong>Note:</strong> By setting the <strong>restrict</strong> property to "A", only the HTML


element with the "w3-test-directive" attribute has invoked the directive.</p>
</body>

</html>

The legal restrict values are:

● E​ for Element name


● A​ for Attribute
● C​ for Class
● M​ for Comment

By default the value is ​EA​, meaning that both Element names and attribute names can invoke
the directive.

AngularJS ng-model Directive

The ng-model directive binds the value of HTML controls (input, select, textarea) to application
data.

The ng-model Directive

With the ​ng-model​ directive you can bind the value of an input field to a variable created in
AngularJS.

<!DOCTYPE html>

<html>

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>

<body>
<div ng-app="myApp" ng-controller="myCtrl">

Name: <input ng-model="name">

</div>

<script>

var app = angular.module('myApp', []);

app.controller('myCtrl', function($scope) {

$scope.name = "John Doe";

});

</script>

<p>Use the ng-model directive to bind the value of the input field to a property made in the
controller.</p>

</body>

</html>

10. Two-Way Binding


The binding goes both ways. If the user changes the value inside the input field, the AngularJS
property will also change its value:

<!DOCTYPE html>

<html>

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>

<body>

<div ng-app="myApp" ng-controller="myCtrl">

Name: <input ng-model="name">

<h1>You entered: {{name}}</h1>

</div>

<script>

var app = angular.module('myApp', []);

app.controller('myCtrl', function($scope) {

$scope.name = "John Doe";

});

</script>
<p>Change the name inside the input field, and you will see the name in the header changes
accordingly.</p>

</body>

</html>

11. Validate User Input

The ​ng-model​ directive can provide type validation for application data (number, e-mail,
required):

<!DOCTYPE html>

<html>

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>

<body>

<form ng-app="" name="myForm">

Email:

<input type="email" name="myAddress" ng-model="text">

<span ng-show="myForm.myAddress.$error.email">Not a valid e-mail address</span>

</form>

<p>Enter your e-mail address in the input field. AngularJS will display an errormessage if the
address is not an e-mail.</p>
</body>

</html>

Application Status

The ​ng-model​ directive can provide status for application data (valid, dirty, touched, error):

<!DOCTYPE html>

<html>

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>

<body>

<form ng-app="" name="myForm" ng-init="myText = '[email protected]'">

Email:

<input type="email" name="myAddress" ng-model="myText" required>

<p>Edit the e-mail address, and try to change the status.</p>

<h1>Status</h1>

<p>Valid: {{myForm.myAddress.$valid}} (if true, the value meets all criteria).</p>

<p>Dirty: {{myForm.myAddress.$dirty}} (if true, the value has been changed).</p>

<p>Touched: {{myForm.myAddress.$touched}} (if true, the field has been in focus).</p>

</form>
</body>

</html>

CSS Classes

The ​ng-model​ directive provides CSS classes for HTML elements, depending on their status:

<!DOCTYPE html>

<html>

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>

<style>

input.ng-invalid {

background-color: lightblue;

</style>

<body>

<form ng-app="" name="myForm">

Enter your name:

<input name="myName" ng-model="myText" required>

</form>

<p>Edit the text field and it will get/lose classes according to the status.</p>

<p><b>Note:</b> A text field with the "required" attribute is not valid when it is empty.</p>
</body>

</html>

The ​ng-model​ directive adds/removes the following classes, according to the status of the form
field:

● ng-empty
● ng-not-empty
● ng-touched
● ng-untouched
● ng-valid
● ng-invalid
● ng-dirty
● ng-pending
● Ng-pristine

12. AngularJS Data Binding

Data binding in AngularJS is the synchronization between the model and the view.

AngularJS Forms

Forms in AngularJS provides data-binding and validation of input controls.

Input Controls

Input controls are the HTML input elements:

● input elements
● select elements
● button elements
● textarea elements

Data-Binding

Input controls provides data-binding by using the ​ng-model​ directive.

<​input​ type​="text"​ ng-model​="firstname">

The application does now have a property named ​firstname​.

The ​ng-model​ directive binds the input controller to the rest of your application.

The property ​firstname​, can be referred to in a controller:

<!DOCTYPE html>
<html lang="en">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body>

<div ng-app="myApp" ng-controller="formCtrl">


<form>
First Name: <input type="text" ng-model="firstname">
</form>
</div>

<script>
var app = angular.module('myApp', []);
app.controller('formCtrl', function($scope) {
$scope.firstname = "John";
});
</script>

</body>
</html>
Ex.
<!DOCTYPE html>
<html lang="en">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body>

<div ng-app="myApp" ng-controller="formCtrl">


<form novalidate>
First Name:<br>
<input type="text" ng-model="user.firstName"><br>
Last Name:<br>
<input type="text" ng-model="user.lastName">
<br><br>
<button ng-click="reset()">RESET</button>
</form>
<p>form = {{user}}</p>
<p>master = {{master}}</p>
</div>a

<script>
var app = angular.module('myApp', []);
app.controller('formCtrl', function($scope) {
$scope.master = {firstName:"John", lastName:"Doe"};
$scope.reset = function() {
$scope.user = angular.copy($scope.master);
};
$scope.reset();
});
</script>

</body>
</html>

13. AngularJS Form Validation

AngularJS can validate input data.

Form Validation
AngularJS offers client-side form validation.

AngularJS monitors the state of the form and input fields (input, textarea, select), and lets you
notify the user about the current state.

AngularJS also holds information about whether they have been touched, or modified, or not.

You can use standard HTML5 attributes to validate input, or you can make your own validation
functions.

Client-side validation cannot alone secure user input. Server side validation is also necessary.

Required

Use the HTML5 attribute ​required​ to specify that the input field must be filled out:

<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body ng-app="">

<p>Try writing in the input field:</p>

<form name="myForm">
<input name="myInput" ng-model="myInput" required>
</form>

<p>The input's valid state is:</p>


<h1>{{myForm.myInput.$valid}}</h1>

</body>
</html>

E-mail

Use the HTML5 type ​email​ to specify that the value must be an e-mail:
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body ng-app="">

<p>Try writing an E-mail address in the input field:</p>

<form name="myForm">
<input type="email" name="myInput" ng-model="myInput">
</form>

<p>The input's valid state is:</p>


<h1>{{myForm.myInput.$valid}}</h1>
<p>Note that the state of the input field is "true" before you start writing in it, even if it does
not contain an e-mail address.</p>

</body>
</html>

Form State and Input State

AngularJS is constantly updating the state of both the form and the input fields.

Input fields have the following states:

● $untouched​ The field has not been touched yet


● $touched​ The field has been touched
● $pristine​ The field has not been modified yet
● $dirty​ The field has been modified
● $invalid​ The field content is not valid
● $valid​ The field content is valid

They are all properties of the input field, and are either ​true​ or ​false​.

Forms have the following states:

● $pristine​ No fields have been modified yet


● $dirty​ One or more have been modified
● $invalid​ The form content is not valid
● $valid​ The form content is valid
● $submitted​ The form is submitted

They are all properties of the form, and are either ​true​ or ​false​.

You can use these states to show meaningful messages to the user. Example, if a field is
required, and the user leaves it blank, you should give the user a warning:

<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body ng-app="">

<p>Try leaving the first input field blank:</p>

<form name="myForm">
<p>Name:
<input name="myName" ng-model="myName" required>
<span ng-show="myForm.myName.$touched && myForm.myName.$invalid">The name is
required.</span>
</p>

<p>Address:
<input name="myAddress" ng-model="myAddress" required>
</p>

</form>

<p>We use the ng-show directive to only show the error message if the field has been touched
AND is empty.</p>

</body>
</html>

CSS Classes

AngularJS adds CSS classes to forms and input fields depending on their states.

The following classes are added to, or removed from, input fields:
● ng-untouched​ The field has not been touched yet
● ng-touched​ The field has been touched
● ng-pristine​ The field has not been modified yet
● ng-dirty​ The field has been modified
● ng-valid​ The field content is valid
● ng-invalid​ The field content is not valid
● ng-valid-​key​ One ​key​ for each validation. Example: ​ng-valid-required​, useful when there
are more than one thing that must be validated
● ng-invalid-​key​ Example: ​ng-invalid-required

The following classes are added to, or removed from, forms:

● ng-pristine​ No fields has not been modified yet


● ng-dirty​ One or more fields has been modified
● ng-valid​ The form content is valid
● ng-invalid​ The form content is not valid
● ng-valid-​key​ One ​key​ for each validation. Example: ​ng-valid-required​, useful when there
are more than one thing that must be validated
● ng-invalid-​key​ Example: ​ng-invalid-required

The classes are removed if the value they represent is ​false​.

Add styles for these classes to give your application a better and more intuitive user interface.

<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<style>
input.ng-invalid {
background-color:pink;
}
input.ng-valid {
background-color:lightgreen;
}
</style>
<body ng-app="">

<p>Try writing in the input field:</p>


<form name="myForm">
<input name="myName" ng-model="myName" required>
</form>

<p>The input field requires content, and will therefore become green when you write in it.</p>

</body>
</html>

14. Custom Validation

To create your own validation function is a bit more tricky; You have to add a new directive to
your application, and deal with the validation inside a function with certain specified
arguments.

Example

Create your own directive, containing a custom validation function, and refer to it by using
my-directive​.

The field will only be valid if the value contains the character "e":

<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body ng-app="myApp">

<p>Try writing in the input field:</p>

<form name="myForm">
<input name="myInput" ng-model="myInput" required my-directive>
</form>

<p>The input's valid state is:</p>


<h1>{{myForm.myInput.$valid}}</h1>

<script>
var app = angular.module('myApp', []);
app.directive('myDirective', function() {
return {
require: 'ngModel',
link: function(scope, element, attr, mCtrl) {
function myValidation(value) {
if (value.indexOf("e") > -1) {
mCtrl.$setValidity('charE', true);
} else {
mCtrl.$setValidity('charE', false);
}
return value;
}
mCtrl.$parsers.push(myValidation);
}
};
});
</script>

<p>The input field must contain the character "e" to be consider valid.</p>

</body>
</html>

15. Validation Example

<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body>

<h2>Validation Example</h2>

<form ng-app="myApp" ng-controller="validateCtrl"


name="myForm" novalidate>

<p>Username:<br>
<input type="text" name="user" ng-model="user" required>
<span style="color:red" ng-show="myForm.user.$dirty && myForm.user.$invalid">
<span ng-show="myForm.user.$error.required">Username is required.</span>
</span>
</p>

<p>Email:<br>
<input type="email" name="email" ng-model="email" required>
<span style="color:red" ng-show="myForm.email.$dirty && myForm.email.$invalid">
<span ng-show="myForm.email.$error.required">Email is required.</span>
<span ng-show="myForm.email.$error.email">Invalid email address.</span>
</span>
</p>

<p>
<input type="submit"
ng-disabled="myForm.user.$dirty && myForm.user.$invalid ||
myForm.email.$dirty && myForm.email.$invalid">
</p>

</form>

<script>
var app = angular.module('myApp', []);
app.controller('validateCtrl', function($scope) {
$scope.user = 'John Doe';
$scope.email = '[email protected]';
});
</script>

</body>
</html>

16. AngularJS Routing

The ​ngRoute​ module helps your application to become a Single Page Application.

What is Routing in AngularJS?

If you want to navigate to different pages in your application, but you also want the application
to be a SPA (Single Page Application), with no page reloading, you can use the ​ngRoute​ module.
The ​ngRoute​ module ​routes​ your application to different pages without reloading the entire
application.

<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular-route.js"></script>

<body ng-app="myApp">

<p><a href="#/!">Main</a></p>

<a href="#!red">Red</a>
<a href="#!green">Green</a>
<a href="#!blue">Blue</a>

<div ng-view></div>

<script>
var app = angular.module("myApp", ["ngRoute"]);
app.config(function($routeProvider) {
$routeProvider
.when("/", {
templateUrl : "main.htm"
})
.when("/red", {
templateUrl : "red.htm"
})
.when("/green", {
templateUrl : "green.htm"
})
.when("/blue", {
templateUrl : "blue.htm"
});
});
</script>
<p>Click on the links to navigate to "red.htm", "green.htm", "blue.htm", or back to
"main.htm"</p>
</body>
</html>

What do I Need?

To make your applications ready for routing, you must include the AngularJS Route module:

<​script​ src​="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular-route.js"><​/script​>

Then you must add the ​ngRoute​ as a dependency in the application module:

var​ app = angular.module(​"myApp"​, [​"ngRoute"​]);

Now your application has access to the route module, which provides the ​$routeProvider​.

Use the ​$routeProvider​ to configure different routes in your application:

app.config(​function​($routeProvider) {

$routeProvider

.when(​"/"​, {

templateUrl : ​"main.htm"

})

.when(​"/red"​, {

templateUrl : ​"red.htm"

})

.when(​"/green"​, {
templateUrl : ​"green.htm"

})

.when(​"/blue"​, {

templateUrl : ​"blue.htm"

});

});

Where Does it Go?

Your application needs a container to put the content provided by the routing.

This container is the ​ng-view​ directive.

There are three different ways to include the ​ng-view​ directive in your application:

Make a Shopping List

Ex.
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">
<body>

<script>
var app = angular.module("myShoppingList", []);
app.controller("myCtrl", function($scope) {
$scope.products = ["Milk", "Bread", "Cheese"];
$scope.addItem = function () {
$scope.errortext = "";
if (!$scope.addMe) {return;}
if ($scope.products.indexOf($scope.addMe) == -1) {
$scope.products.push($scope.addMe);
} else {
$scope.errortext = "The item is already in your shopping list.";
}
}
$scope.removeItem = function (x) {
$scope.errortext = "";
$scope.products.splice(x, 1);
}
});
</script>

<div ng-app="myShoppingList" ng-cloak ng-controller="myCtrl" class="w3-card-2 w3-margin"


style="max-width:400px;">
<header class="w3-container w3-light-grey w3-padding-16">
<h3>My Shopping List</h3>
</header>
<ul class="w3-ul">
<li ng-repeat="x in products" class="w3-padding-16">{{x}}<span
ng-click="removeItem($index)" style="cursor:pointer;" class="w3-right
w3-margin-right">×</span></li>
</ul>
<div class="w3-container w3-light-grey w3-padding-16">
<div class="w3-row w3-margin-top">
<div class="w3-col s10">
<input placeholder="Add shopping items here" ng-model="addMe" class="w3-input
w3-border w3-padding">
</div>
<div class="w3-col s2">
<button ng-click="addItem()" class="w3-btn w3-padding w3-green">Add</button>
</div>
</div>
<p class="w3-text-red">{{errortext}}</p>
</div>
</div>

</body>
</html>

Chapter : Introduction to Node JS

1. What is Node.js?

● Node.js is an open source server environment


● Node.js is free
● Node.js runs on various platforms (Windows, Linux, Unix, Mac OS X, etc.)
● Node.js uses JavaScript on the server

Why Node.js?

Node.js uses asynchronous programming!

A common task for a web server can be to open a file on the server and return the content to
the client.

Here is how PHP or ASP handles a file request:

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


2. Waits while the file system opens and reads the file.
3. Returns the content to the client.
4. Ready to handle the next request.

Here is how Node.js handles a file request:

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


2. Ready to handle the next request.
3. When the file system has opened and read the file, the server returns the content to the
client.

Node.js eliminates the waiting, and simply continues with the next request.
Node.js runs single-threaded, non-blocking, asynchronously programming, which is very
memory efficient.

What Can Node.js Do?

● Node.js can generate dynamic page content


● Node.js can create, open, read, write, delete, and close files on the server
● Node.js can collect form data
● Node.js can add, delete, modify data in your database

What is a Node.js File?

● Node.js files contain tasks that will be executed on certain events


● A typical event is someone trying to access a port on the server
● Node.js files must be initiated on the server before having any effect
● Node.js files have extension ".js"

myfirst.js

var​ http = require(​'http'​);

http.createServer(​function​ (req, res) {


res.writeHead(​200​, {​'Content-Type'​: ​'text/html'​});
res.end(​'Hello World!'​);
}).listen(​8080​);

C:\Users>node myfirst.js

Include Modules

To include a module, use the ​require()​ function with the name of the module:

var​ http = require(​'http'​);

Now your application has access to the HTTP module, and is able to create a server:

http.createServer(​function​ (req, res) {


res.writeHead(​200​, {​'Content-Type'​: ​'text/html'​});

res.end(​'Hello World!'​);

}).listen(​8080​);

Create Your Own Modules

You can create your own modules, and easily include them in your applications.

The following example creates a module that returns a date and time object:

Example

Create a module that returns the current date and time:

exports.myDateTime = ​function​ () {

​return​ Date();

};

Use the ​exports​ keyword to make properties and methods available outside the module file.

Save the code above in a file called "myfirstmodule.js"

Include Your Own Module

Now you can include and use the module in any of your Node.js files.

Example

Use the module "myfirstmodule" in a Node.js file:


var http = require('http');

var dt = require('./myfirstmodule');

http.createServer(function (req, res) {

res.writeHead(200, {'Content-Type': 'text/html'});

res.write("The date and time is currently: " + dt.myDateTime());

res.end();

}).listen(8080);

Notice that we use ​./​ to locate the module, that means that the module is located in the same
folder as the Node.js file.

Save the code above in a file called "demo_module.js", and initiate the file:

Initiate demo_module.js:

C:\Users\​Your Name>​ node demo_module.js

2. Node.js HTTP Module

The Built-in HTTP Module

Node.js has a built-in module called HTTP, which allows Node.js to transfer data over the Hyper
Text Transfer Protocol (HTTP).

To include the HTTP module, use the ​require()​ method:

var​ http = require(​'http'​);

Node.js as a Web Server

The HTTP module can create an HTTP server that listens to server ports and gives a response
back to the client.
Use the ​createServer()​ method to create an HTTP server:

EX.

var http = require('http');

//create a server object:


http.createServer(function (req, res) {
res.write('Hello World!'); //write a response to the client
res.end(); //end the response
}).listen(8080); //the server object listens on port 8080
Add an HTTP Header

If the response from the HTTP server is supposed to be displayed as HTML, you should include
an HTTP header with the correct content type:

Example

var​ http = require(​'http'​);

http.createServer(​function​ (req, res) {

res.writeHead(​200​, {​'Content-Type'​: ​'text/html'​});

res.write(​'Hello World!'​);

res.end();

}).listen(​8080​);

Read the Query String

The function passed into the ​http.createServer()​ has a ​req​ argument that represents the
request from the client, as an object (http.IncomingMessage object).

This object has a property called "url" which holds the part of the url that comes after the
domain name:

demo_http_url.js

var​ http = require(​'http'​);

http.createServer(​function​ (req, res) {

res.writeHead(​200​, {​'Content-Type'​: ​'text/html'​});


res.write(req.url);

res.end();

}).listen(​8080​);

Split the Query String

There are built-in modules to easily split the query string into readable parts, such as the URL
module.

Example

Split the query string into readable parts:

var​ http = require(​'http'​);

var​ url = require(​'url'​);

http.createServer(​function​ (req, res) {

res.writeHead(​200​, {​'Content-Type'​: ​'text/html'​});

​var​ q = url.parse(req.url, ​true​).query;

​var​ txt = q.year + ​" "​ + q.month;

res.end(txt);

}).listen(​8080​);

3. Node.js File System Module

Node.js as a File Server


The Node.js file system module allows you to work with the file system on your computer.

To include the File System module, use the ​require()​ method:

var​ fs = require(​'fs'​);

Common use for the File System module:

● Read files
● Create files
● Update files
● Delete files
● Rename files

Read Files

The ​fs.readFile()​ method is used to read files on your computer.

Assume we have the following HTML file (located in the same folder as Node.js):

demofile1.html

<​html​>

<​body​>

<​h1​>​My Header​<​/h1​>

<​p​>​My paragraph.​<​/p​>

<​/body​>

<​/html​>

Create a Node.js file that reads the HTML file, and return the content:
Example

var​ http = require(​'http'​);

var​ fs = require(​'fs'​);

http.createServer(​function​ (req, res) {

fs.readFile(​'demofile1.html'​, ​function​(err, data) {

res.writeHead(​200​, {​'Content-Type'​: ​'text/html'​});

res.write(data);

​return​ res.end();

});

}).listen(​8080​);

Create Files

The File System module has methods for creating new files:

● fs.appendFile()
● fs.open()
● fs.writeFile()

The ​fs.appendFile()​ method appends specified content to a file. If the file does not exist, the file
will be created:

Example

Create a new file using the appendFile() method:


var​ fs = require(​'fs'​);

fs.appendFile(​'mynewfile1.txt'​, ​'Hello content!'​, ​function​ (err) {

​if​ (err) ​throw​ err;

console.log(​'Saved!'​);

});

4. Node.js NPM

What is NPM?

NPM is a package manager for Node.js packages, or modules if you like.

www.npmjs.com​ hosts thousands of free packages to download and use.

The NPM program is installed on your computer when you install Node.js

What is a Package?

A package in Node.js contains all the files you need for a module.

Modules are JavaScript libraries you can include in your project.

Download a Package

Downloading a package is very easy.

Open the command line interface and tell NPM to download the package you want.

I want to download a package called "upper-case":

Download "upper-case":
C:\Users\​Your Name​>npm install upper-case

Now you have downloaded and installed your first package!

NPM creates a folder named "node_modules", where the package will be placed. All packages
you install in the future will be placed in this folder.

My project now has a folder structure like this:

C:\Users\​My Name​\node_modules\upper-case

Using a Package

Once the package is installed, it is ready to use.

Include the "upper-case" package the same way you include any other module:

var​ uc = require(​'upper-case'​);

Create a Node.js file that will convert the output "Hello World!" into upper-case letters:

Example

var​ http = require(​'http'​);

var​ uc = require(​'upper-case'​);

http.createServer(​function​ (req, res) {

res.writeHead(​200​, {​'Content-Type'​: ​'text/html'​});

res.write(uc.upperCase(​"Hello World!"​));

res.end();

}).listen(​8080​);
5. Node.js Events

Node.js is perfect for event-driven applications.

Events in Node.js

Every action on a computer is an event. Like when a connection is made or a file is opened.

Objects in Node.js can fire events, like the readStream object fires events when opening and
closing a file:

Example

var​ fs = require(​'fs'​);

var​ rs = fs.createReadStream(​'./demofile.txt'​);

rs.on(​'open'​, ​function​ () {

console.log(​'The file is open'​);

});

Events Module

Node.js has a built-in module, called "Events", where you can create-, fire-, and listen for- your
own events.

To include the built-in Events module use the ​require()​ method. In addition, all event properties
and methods are an instance of an EventEmitter object. To be able to access these properties
and methods, create an EventEmitter object:

var​ events = require(​'events'​);

var​ eventEmitter = ​new​ events.EventEmitter();


The EventEmitter Object

You can assign event handlers to your own events with the EventEmitter object.

In the example below we have created a function that will be executed when a "scream" event
is fired.

To fire an event, use the ​emit()​ method.

Ex
var events = require('events');
var eventEmitter = new events.EventEmitter();

//Create an event handler:


var myEventHandler = function () {
console.log('I hear a scream!');
}

//Assign the eventhandler to an event:


eventEmitter.on('scream', myEventHandler);

//Fire the 'scream' event:


eventEmitter.emit('scream');

Node.js MongoDB

Node.js can be used in database applications.

One of the most popular NoSQL database is MongoDB.

Node.js MongoDB Create Database

reating 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.
Example

Create a database called "mydb":

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

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:

Run "demo_create_mongo_db.js"

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

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

6. Node.js MongoDB Create Collection

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


Creating a Collection

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

Example

Create a collection called "customers":

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"​);

dbo.createCollection(​"customers"​, ​function​(err, res) {

​if​ (err) ​throw​ err;

console.log(​"Collection created!"​);

db.close();

});

});

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

Run "demo_mongodb_createcollection.js"
C:\Users\​Your Name​>node demo_mongodb_createcollection.js

Which will give you this result:

Collection created!

Node.js MongoDB Insert

Insert Into Collection

To insert a record, or ​document​ as it is called in MongoDB, into a collection, we use the


insertOne()​ method.

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

The first parameter of the ​insertOne()​ method is an object containing the name(s) and value(s)
of each field in the document you want to insert.

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

Example

Insert a document in the "customers" 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"​);

​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();

});

});

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

Insert Multiple Documents

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

The first parameter of the ​insertMany()​ method is an array of objects, containing the data you
want to insert.

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

Example

Insert multiple documents in the "customers" 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"​);

​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();

});

});

The Result Object

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

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

The _id Field

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

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

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

Example

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

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

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


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

​if​ (err) ​throw​ err;

​var​ dbo = db.db(​"mydb"​);

​var​ myobj = [

{ _id: 154, name: ​'Chocolate Heaven'​},

{ _id: 155, name: ​'Tasty Lemon'​},

{ _id: 156, name: ​'Vanilla Dream'​}

];

dbo.collection(​"products"​).insertMany(myobj, ​function​(err, res) {

​if​ (err) ​throw​ err;

console.log(res);

db.close();

});

});

7. Node.js MongoDB Find

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

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

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

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

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

Example

Find the first document in the customers collection:

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

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

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

​if​ (err) ​throw​ err;

​var​ dbo = db.db(​"mydb"​);

dbo.collection(​"customers"​).findOne({}, ​function​(err, result) {

​if​ (err) ​throw​ err;

console.log(result.name);

db.close();

});

});

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

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

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

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

Example

Find all documents in the customers 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"​);

dbo.collection(​"customers"​).find({}).toArray(​function​(err, result) {

​if​ (err) ​throw​ err;

console.log(result);

db.close();

});

});

Find Some
The second parameter of the ​find()​ method is the ​projection​ object that describes which fields
to include in the result.

This parameter is optional, and if omitted, all fields will be included in the result.

Example

Return the fields "name" and "address" of all documents in the customers 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"​);

dbo.collection(​"customers"​).find({}, { projection: { _id: ​0​, name: ​1​, address: ​1​ }


}).toArray(​function​(err, result) {

​if​ (err) ​throw​ err;

console.log(result);

db.close();

});

});

8. The Result Object


As you can see from the result of the example above, the result can be converted into an array
containing each document as an object.

To return e.g. the address of the third document, just refer to the third array object's address
property:

Example

Return the address of the third document:

console.log(result[2].address);

Which will produce this result:

Apple st 652

9. Node.js MongoDB Query

Filter the Result

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

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

Example

Find documents with the address "Park Lane 38":

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

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


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

​if​ (err) ​throw​ err;

​var​ dbo = db.db(​"mydb"​);

​var​ query = { address: ​"Park Lane 38"​ };

dbo.collection(​"customers"​).find(query).toArray(​function​(err, result) {

​if​ (err) ​throw​ err;

console.log(result);

db.close();

});

});

12. Filter With Regular Expressions

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

Regular expressions can only be used to query ​strings​.

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

Example

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

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


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

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

​if​ (err) ​throw​ err;

​var​ dbo = db.db(​"mydb"​);

​var​ query = { address: /^S/ };

dbo.collection(​"customers"​).find(query).toArray(​function​(err, result) {

​if​ (err) ​throw​ err;

console.log(result);

db.close();

});

});

13. Node.js MongoDB Sort

Sort the Result

Use the ​sort()​ method to sort the result in ascending or descending order.

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

Example

Sort the result alphabetically by name:


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

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

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

​if​ (err) ​throw​ err;

​var​ dbo = db.db(​"mydb"​);

​var​ mysort = { name: ​1​ };

dbo.collection(​"customers"​).find().sort(mysort).toArray(​function​(err, result) {

​if​ (err) ​throw​ err;

console.log(result);

db.close();

});

});

Sort Descending

Use the value -1 in the sort object to sort descending.

{ name: 1 } // ascending

{ name: -1 } // descending

Example
Sort the result reverse alphabetically by name:

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​ mysort = { name: -​1​ };

dbo.collection(​"customers"​).find().sort(mysort).toArray(​function​(err, result) {

​if​ (err) ​throw​ err;

console.log(result);

db.close();

});

});

Node.js MongoDB Delete

Delete Document

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

The first parameter of the ​deleteOne()​ method is a query object defining which document to
delete.
Note: If the query finds more than one document, only the first occurrence is deleted.

Example

Delete the document with the address "Mountain 21":

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

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

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

​if​ (err) ​throw​ err;

​var​ dbo = db.db(​"mydb"​);

​var​ myquery = { address: ​'Mountain 21'​ };

dbo.collection(​"customers"​).deleteOne(myquery, ​function​(err, obj) {

​if​ (err) ​throw​ err;

console.log(​"1 document deleted"​);

db.close();

});

});

Delete Many

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


The first parameter of the ​deleteMany()​ method is a query object defining which documents to
delete.

Example

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

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

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

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

​if​ (err) ​throw​ err;

​var​ dbo = db.db(​"mydb"​);

​var​ myquery = { address: /^O/ };

dbo.collection(​"customers"​).deleteMany(myquery, ​function​(err, obj) {

​if​ (err) ​throw​ err;

console.log(obj.result.n + ​" document(s) deleted"​);

db.close();

});

});
Node.js MongoDB Update

Update Document

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

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

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

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

Example

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

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

var​ url = ​"mongodb://127.0.0.1:27017/"​;

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

​if​ (err) ​throw​ err;

​var​ dbo = db.db(​"mydb"​);

​var​ myquery = { address: ​"Valley 345"​ };

​var​ newvalues = { $set: {name: ​"Mickey"​, address: ​"Canyon 123"​ } };


dbo.collection(​"customers"​).updateOne(myquery, newvalues, ​function​(err, res) {

​if​ (err) ​throw​ err;

console.log(​"1 document updated"​);

db.close();

});

});

Update Only Specific Fields

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

Ex.

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 myquery = { address: "Valley 345" };

var newvalues = {$set: {address: "Canyon 123"} };

dbo.collection("customers").updateOne(myquery, newvalues, function(err, res) {

if (err) throw err;

console.log("1 document updated");


db.close();

});

});

Update Many Documents

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

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 myquery = { address: /^S/ };

var newvalues = {$set: {name: "Minnie"} };

dbo.collection("customers").updateMany(myquery, newvalues, function(err, res) {

if (err) throw err;

console.log(res.result.nModified + " document(s) updated");

db.close();

});

});

You might also like