Sunday, November 22, 2015

The Real JavaScript

Hi, In this article i am going to explain the internal architecture of the JavaScript object. After reading this article you have a clear understanding of JavaScript Object, what is __proto__ and prototype chaining in JavaScript.

lets start :)

There are three ways to create an object in JavaScript.

1. Using an object literal

var Person  = {};

2. Using the new keyword

var Person = new Object();

3. Inheriting Object.prototype

var Person = Object.create(Object.prototype);

All of these create same person object.
Here var Person = Object.create(Object.prototype); means that Person object extends from Object.prototype Object.

If you want to add some property to the Person object then this can be added as below.

Person.name = "deepak";

Now Person Object has one property name of type string and has value deepak in it.

So lets understand this simple object by structure.


In the above image you can see the structure of Person Object. Here Person Object extends from Object.prototype Object.

__proto__ provides link between the objects.

For a property it will look into the Object
if unable to find then it will look into the Object.__proto__
if unable to find it will look into the Object.__proto__.__proto__ and so on, until it find null, this is called prototype chaining in JavaScript.

Longer the prototype chain more the access time.

var Person = { name: "Deepak" };
Person.name; // Deepak
Person.hasOwnProperty('name'); // true
view raw object.js hosted with ❤ by GitHub
Here Person object accessing hasOwnProperty() method by prototype chaining.

Wednesday, November 4, 2015

What is IIFE in JavaScript

IIFE means Immediately Invoked Function Expression.
It is just an anonymous function that is wrapped inside of a set of parentheses and invoked immediately.
We use IIFE to place all our code inside of a local scope or to avoid global scope.

Structure of the IIFE

(function () {
// our code goes here
})();
view raw IIFE.js hosted with ❤ by GitHub

Example

var name = 'Deepak';
(function() {
var city = 'Pune';
console.log(city); // Pune
})();
console.log(name); // Deepak
console.log(city)
// "ReferenceError: city is not defined
view raw IIFE.js hosted with ❤ by GitHub

In the above example, the code outside of the IIFE has a global scope and the code inside of the IIFE has a local scope. Any variables declared inside of an IIFE can not be assessed from the outside of that IIFE.
It is one of the best practice of JavaScript to avoid global variables and functions. There are lots of design patterns in which we can avoid global variables and functions, IIFE is one of them.

Link of program
IIFE Program

Saturday, August 1, 2015

Basic Git Commands

What is Git
Git is a revision control system. It keeps track of changes.

1. show all branch
git branch
view raw git.sh hosted with ❤ by GitHub
This git command list down all your local git branch and also highlight the branch name you are currently in.

2. create new branch
git branch newbranchname
view raw git.sh hosted with ❤ by GitHub
This git command create a new branch named 'newBranchName'.

3. switch to another branch
git checkout branchname
view raw git.sh hosted with ❤ by GitHub
This git command switch to 'newBranchName' branch.

4. create a new branch and switch to it
git checkout -b newbranchname
view raw git.sh hosted with ❤ by GitHub

5. delete a branch
git branch -d branchname
view raw git.sh hosted with ❤ by GitHub

6. rename the current branch
git branch -m newname
view raw git.sh hosted with ❤ by GitHub

7. rename the branch which is not your current branch
git branch -m oldname newname
view raw git.sh hosted with ❤ by GitHub

8. status
git status
view raw git.sh hosted with ❤ by GitHub
This git command list the files you have changed and those you still need to add or commit.

9. add single file
git add filename
view raw git.sh hosted with ❤ by GitHub
add one file to staging

10. add all files
git add *
view raw git.sh hosted with ❤ by GitHub
add all files to staging

11. commit changes to head (but not yet to the remote repository)
git commit -am 'message'
view raw git.sh hosted with ❤ by GitHub
12. send changes to the branch of your remote repository
git push origin branchname
view raw git.sh hosted with ❤ by GitHub
13. update from the remote repository
git pull origin master
view raw git.sh hosted with ❤ by GitHub
fetch and merge changes from the remote server(master branch) to your working branch

14. get list of commit id
git log
view raw git.sh hosted with ❤ by GitHub

15. show difference (changes) between two commit id
git diff sourceCommitId targetCommitId
view raw git.sh hosted with ❤ by GitHub

16. show difference (changes) between two branch
git diff sourcebranch targetbranch
view raw git.sh hosted with ❤ by GitHub

17. changes local working directory code to specific commit
git reset --hard commitid
view raw git.sh hosted with ❤ by GitHub

18. show GUI
git gui
view raw git.sh hosted with ❤ by GitHub

19. undo git add for single file
git reset filename
view raw git.sh hosted with ❤ by GitHub

20. undo git add for all files
git reset
view raw git.sh hosted with ❤ by GitHub

21. undo git commit
git reset --soft HEAD^
view raw git.sh hosted with ❤ by GitHub

22. view your remote branches
git branch -r
view raw git.sh hosted with ❤ by GitHub

Saturday, June 20, 2015

Developing MEAN Application Part 2

In the part 1 of making MEAN application, we have done the server side coding. Now in this second part we will do the front-end coding in AngularJS.

So lets start

We are using AngularJS, so we have to install AngularJS through bower. but first we need to add bower.json file in our project. So add bower.json file by typing following command in terminal.

bower init



This will add bower.json file in our project.


Now we can install AngularJS in our project by below command.

bower install angularjs --save

This will add a bower_component directory in our project which has AngularJS library and bower.json file is updated with AngularJS dependency.



Now we will create a index.html file in our project. So the directory structure of our MEAN application become


Now write following lines of code in index.html file.

<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
</head>
<body>
<h1>MEAN App</h1>
</body>
</html>
view raw gistfile1.html hosted with ❤ by GitHub
Our server is running at 3000 port so when we hit the URL http://localhost:3000/ then index.html page should be rendered on the browser. But this is not happening right now. For rendering index.html page on browser, we have to write the following code in app.js.

path = require('path');
app.get('/', function(req, res) {
res.sendFile(path.join(__dirname, "/index.html"));
});
view raw gistfile1.js hosted with ❤ by GitHub
Here Above lines of code redirect our server to index.html page and Now when you hit the URL http://localhost:3000/ then this will render index.html in your browser.
We also have to include AngularJS library in index.html page and for that we have to write below code in app.js

app.use('/js', express.static(__dirname));
view raw gistfile1.js hosted with ❤ by GitHub
Now we can include AngularJS library in index.html page.

<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
</head>
<body ng-app="myApp" ng-controller="userController">
<h1>MEAN App</h1>
<script src="/js/bower_components/angularjs/angular.min.js"></script>
</body>
</html>
view raw gistfile1.html hosted with ❤ by GitHub

Now we code AngularJS simple program which display application name in browser. Thus our index.html page modified as follows.

<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
</head>
<body ng-app="myApp" ng-controller="userController">
<h1>{{ appName }}</h1>
<script src="/js/bower_components/angularjs/angular.min.js"></script>
</body>
</html>
view raw gistfile1.html hosted with ❤ by GitHub
Now we create a angular controller file userController.js. So the structure of our application become.


And write following lines of code in userController.js

var app = angular.module('myApp', []);
app.controller('userController', ['$scope', function($scope) {
$scope.appName = 'MEAN App';
}]);
view raw gistfile1.js hosted with ❤ by GitHub
and include userController.js in index.html page

<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
</head>
<body ng-app="myApp" ng-controller="userController">
<h1>{{ appName }}</h1>
<script src="/js/bower_components/angularjs/angular.min.js"></script>
<script src="/js/userController.js"></script>
</body>
</html>
view raw gistfile1.html hosted with ❤ by GitHub
Now hit the URL http://localhost:3000/ in browser and you will see the output as follows


Now we will write AJAX calls for GET Request to get all users, DELETE Request to delete a user, PUT Request to edit a user and POST Request to add a user. We are using $resource service for making AJAX calls. Here is a very good video link of using $resource service https://www.youtube.com/watch?v=X_NZr_-RaLw

Install angular-resource by following command.

bower install angular-resource --save

This will install angular-resource in your project. Now include angular-resource in index.html page.

<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
</head>
<body ng-app="myApp" ng-controller="userController">
<h1>{{ appName }}</h1>
<script src="/js/bower_components/angularjs/angular.min.js"></script>
<script src="/js/bower_components/angular-resource/angular-resource.min.js"></script>
<script src="/js/userController.js"></script>
</body>
</html>
view raw gistfile1.html hosted with ❤ by GitHub


Now we should create a service for handling AJAX Request because this is not the responsibility of controller. So create a service file userService.js. Now final structure of our MEAN application become.


Write following lines of code in userService.js file

app.factory('userService', function($resource) {
var data = $resource('/users/:userId', {userId : '@_id'}, {
update : {
method : 'PUT'
}
});
return data;
});
view raw gistfile1.js hosted with ❤ by GitHub
Now include userService.js in index.html page

<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
</head>
<body ng-app="myApp" ng-controller="userController">
<h1>{{ appName }}</h1>
<script src="/js/bower_components/angularjs/angular.min.js"></script>
<script src="/js/bower_components/angular-resource/angular-resource.min.js"></script>
<script src="/js/userController.js"></script>
<script src="/js/userService.js"></script>
</body>
</html>
view raw gistfile1.html hosted with ❤ by GitHub
Now we will write a GET Request to get all users and display all users in table. for getting all users in controller our userController.js file modifies as follows.

var app = angular.module('myApp', ['ngResource']);
app.controller('userController', ['$scope', '$resource', 'userService', function($scope, $resource, userService) {
$scope.appName = 'MEAN App';
$scope.getUsers = function () {
userService.query(function(users) {
$scope.users = users;
});
};
$scope.getUsers();
}]);
view raw gistfile1.js hosted with ❤ by GitHub
Now we have all users in $scope.users variable and we will use $scope.users variable to display all users in table. So the index.html file become.

<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
</head>
<body ng-app="myApp" ng-controller="userController">
<h1>{{ appName }}</h1>
<table>
<tr>
<th>Count</th>
<th>Name</th>
<th>Edit</th>
<th>Delete</th>
</tr>
<tr ng-repeat="user in users">
<td>{{ $index + 1 }}</td>
<td>{{ user.name }}</td>
<td><button>Edit</button></td>
<td><button>Delete</button></td>
</tr>
</table>
<script src="/js/bower_components/angularjs/angular.min.js"></script>
<script src="/js/bower_components/angular-resource/angular-resource.min.js"></script>
<script src="/js/userController.js"></script>
<script src="/js/userService.js"></script>
</body>
</html>
view raw gistfile1.html hosted with ❤ by GitHub
Now if you hit the URL http://localhost:3000/ then you will see the all users in table.


There is only one user in my database that is why it is showing only one user in table. Now we will add some css so that this table look better. so add following lines of css in index.html page

<style>
table, th, td {
border: 1px solid black;
border-collapse: collapse;
padding: 8px;
}
</style>
view raw gistfile1.css hosted with ❤ by GitHub

so the index.html page become

<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
<style>
table, th, td {
border: 1px solid black;
border-collapse: collapse;
padding: 8px;
}
</style>
</head>
<body ng-app="myApp" ng-controller="userController">
<h1>{{ appName }}</h1>
<table>
<tr>
<th>Count</th>
<th>Name</th>
<th>Edit</th>
<th>Delete</th>
</tr>
<tr ng-repeat="user in users">
<td>{{ $index + 1 }}</td>
<td>{{ user.name }}</td>
<td><button>Edit</button></td>
<td><button>Delete</button></td>
</tr>
</table>
<script src="/js/bower_components/angularjs/angular.min.js"></script>
<script src="/js/bower_components/angular-resource/angular-resource.min.js"></script>
<script src="/js/userController.js"></script>
<script src="/js/userService.js"></script>
</body>
</html>
view raw gistfile1.html hosted with ❤ by GitHub

Now when you hit the http://localhost:3000/ URL then you will see the below output in table.


Now we will implement the functionality of adding a user. So first we will write a html code for adding a user. Now our index.html page modifies as below.

<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
<style>
table, th, td {
border: 1px solid black;
border-collapse: collapse;
padding: 8px;
}
</style>
</head>
<body ng-app="myApp" ng-controller="userController">
<h1>{{ appName }}</h1>
<div>
<input type="text" ng-model="newUserName" placeholder="Enter User Name">
<button ng-click="addUser()">Add User</button>
</div><br>
<table>
<tr>
<th>Count</th>
<th>Name</th>
<th>Edit</th>
<th>Delete</th>
</tr>
<tr ng-repeat="user in users">
<td>{{ $index + 1 }}</td>
<td>{{ user.name }}</td>
<td><button>Edit</button></td>
<td><button>Delete</button></td>
</tr>
</table>
<script src="/js/bower_components/angularjs/angular.min.js"></script>
<script src="/js/bower_components/angular-resource/angular-resource.min.js"></script>
<script src="/js/userController.js"></script>
<script src="/js/userService.js"></script>
</body>
</html>
view raw gistfile1.html hosted with ❤ by GitHub
And now we will write the controller code. So the controller code modifies as below.

var app = angular.module('myApp', ['ngResource']);
app.controller('userController', ['$scope', '$resource', 'userService', function($scope, $resource, userService) {
$scope.appName = 'MEAN App';
$scope.getUsers = function () {
userService.query(function(users) {
$scope.users = users;
});
};
$scope.getUsers();
$scope.addUser = function() {
var user = new userService();
user.name = $scope.newUserName;
user.$save(function (user) {
$scope.getUsers();
$scope.newUserName = '';
});
};
}]);
view raw gistfile1.js hosted with ❤ by GitHub

Now when you refresh the http://localhost:3000/ then you will see the below output


When you enter the user name in the input box and click on the add user button then a user is created. for example if you write the user name deepak and click on the add user button then the output would be


Now we will implement the edit functionality of user. So the index.html page modifies as below.

<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
<style>
table, th, td {
border: 1px solid black;
border-collapse: collapse;
padding: 8px;
}
</style>
</head>
<body ng-app="myApp" ng-controller="userController">
<h1>{{ appName }}</h1>
<div>
<input type="text" ng-model="newUserName" placeholder="Enter User Name">
<button ng-click="addUser()">Add User</button>
</div><br>
<div>
<input type="text" ng-model="editUserName">
<button ng-click="changeUserName(editUserName)">Edit User</button>
</div><br>
<table>
<tr>
<th>Count</th>
<th>Name</th>
<th>Edit</th>
<th>Delete</th>
</tr>
<tr ng-repeat="user in users">
<td>{{ $index + 1 }}</td>
<td>{{ user.name }}</td>
<td><button ng-click="editUser(user)">Edit</button></td>
<td><button>Delete</button></td>
</tr>
</table>
<script src="/js/bower_components/angularjs/angular.min.js"></script>
<script src="/js/bower_components/angular-resource/angular-resource.min.js"></script>
<script src="/js/userController.js"></script>
<script src="/js/userService.js"></script>
</body>
</html>
view raw gistfile1.html hosted with ❤ by GitHub
And the userController.js modifies as below.

var app = angular.module('myApp', ['ngResource']);
app.controller('userController', ['$scope', '$resource', 'userService', function($scope, $resource, userService) {
$scope.appName = 'MEAN App';
$scope.getUsers = function () {
userService.query(function(users) {
$scope.users = users;
});
};
$scope.getUsers();
$scope.addUser = function() {
var user = new userService();
user.name = $scope.newUserName;
user.$save(function (user) {
$scope.getUsers();
$scope.newUserName = '';
});
};
$scope.editUser = function (user) {
$scope.user = user;
$scope.editUserName = user.name;
};
$scope.changeUserName = function (editUserName) {
userService.update({userId : $scope.user._id}, {name : editUserName}, function (res) {
$scope.getUsers();
$scope.editUserName = '';
});
};
}]);
view raw gistfile1.js hosted with ❤ by GitHub

Now when you refresh the http://localhost:3000/ then you will see the below output


When you click on the edit button of respective user then that user name will be display in the edit user name input box. Now you need to change the name of user and click on the edit user button. If the PUT Request is successful then it will reflect in the user table. Now we will implement the delete user functionality. So the index.html page modify as below.

<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
<style>
table, th, td {
border: 1px solid black;
border-collapse: collapse;
padding: 8px;
}
</style>
</head>
<body ng-app="myApp" ng-controller="userController">
<h1>{{ appName }}</h1>
<div>
<input type="text" ng-model="newUserName" placeholder="Enter User Name">
<button ng-click="addUser()">Add User</button>
</div><br>
<div>
<input type="text" ng-model="editUserName">
<button ng-click="changeUserName(editUserName)">Edit User</button>
</div><br>
<table>
<tr>
<th>Count</th>
<th>Name</th>
<th>Edit</th>
<th>Delete</th>
</tr>
<tr ng-repeat="user in users">
<td>{{ $index + 1 }}</td>
<td>{{ user.name }}</td>
<td><button ng-click="editUser(user)">Edit</button></td>
<td><button ng-click="deleteUser(user)">Delete</button></td>
</tr>
</table>
<script src="/js/bower_components/angularjs/angular.min.js"></script>
<script src="/js/bower_components/angular-resource/angular-resource.min.js"></script>
<script src="/js/userController.js"></script>
<script src="/js/userService.js"></script>
</body>
</html>
view raw gistfile1.html hosted with ❤ by GitHub
And the userController.js modify as below.

var app = angular.module('myApp', ['ngResource']);
app.controller('userController', ['$scope', '$resource', 'userService', function($scope, $resource, userService) {
$scope.appName = 'MEAN App';
$scope.getUsers = function () {
userService.query(function(users) {
$scope.users = users;
});
};
$scope.getUsers();
$scope.addUser = function() {
var user = new userService();
user.name = $scope.newUserName;
user.$save(function (user) {
$scope.getUsers();
$scope.newUserName = '';
});
};
$scope.editUser = function (user) {
$scope.user = user;
$scope.editUserName = user.name;
};
$scope.changeUserName = function (editUserName) {
userService.update({userId : $scope.user._id}, {name : editUserName}, function (res) {
$scope.getUsers();
$scope.editUserName = '';
});
};
$scope.deleteUser = function (user) {
var user = userService.delete({userId : user._id}, function(res) {
$scope.getUsers();
});
};
}]);
view raw gistfile1.js hosted with ❤ by GitHub

Now when you refresh the http://localhost:3000/ then you will see the below output


Now if you click on the delete button of respective user then that user is deleted and our user table changes accordingly.
We are done with our MEAN Application. You can also find code of this MEAN application on my Github account. Here is the link

Resources

Saturday, June 6, 2015

Developing MEAN Application Part 1

MEAN stands for MongoDB, Express.js, AngularJS and Node.js. By using MEAN stack we can make end-to-end web application.

MongoDB    -    Database, used to store data

Express.js    -    Node.js web application framework, framework for Node.js so that
                          we do not have to deal with core Node.js

AngularJS    -    Frond-end framework

Node.js        -     Application Server, by using Node.js we can write back-end code in
                          JavaScript

I am considering that you have basic knowledge of each MEAN technologies. Here we are making end-to end web application using MEAN stack. In the part 1 of this tutorial we are doing server side coding that is Node.js, Express.js and MongoDB and test all our CRUD operation in Postman - REST Client. In the part 2 of this tutorial we will do the front end coding in AngularJS.

What we are making
We are making a very simple web application.
As you can see from the image, we can create user, edit user, delete user and get users. And these CRUD operation goes end-to-end. When we talk about end-to-end it means when we create user then it created a user entry in mongoDB database and when we delete user it also delete user from mongoDB database. Similarly on edit it edit user to mongoDB database and on refreshing the page it gets all users from mongoDB database.

So lets start

Open your IDE or editor you are using and create a new project and name it as MEAN_App.
Create a file app.js in your project.


you have to install express.js and mongodb npm package in your project. first create a package.json file. Open terminal and write command

     npm init

press enter 2-3 times and it will create a package.json file in your project.


Now you can install express.js in your project by below command.

npm install express --save

And mongodb npm package by below command.

npm install mongodb --save

This will install express.js and mongodb npm package in your project and you can see that, express and mongodb are added to your package.json file.


Now your project has 2 files and 1 directory


Now we can write code. First we create a connection to mongoDB database and write POST request.

write following lines of code in app.js

var express = require('express'),
app = express(),
mongodb = require('mongodb'),
mongoClient = mongodb.MongoClient,
url = 'mongodb://localhost:27017/MEAN_Demo',
port = 3000;
mongoClient.connect(url, function(err, db) {
if(err) {
console.log('error in connecting to mongoDB ', err);
} else {
_db = db;
console.log('connected to mongoDB');
app.listen(port, function() {
console.log('listening for requests on localhost:%s', port);
});
}
});
view raw gistfile1.js hosted with ❤ by GitHub

The above code does not create a database to mongoDB. It just create a connection to mongoDB database. We have to write a POST request for creating a database. And when POST request execute it create a database named MEAN_Demo and make a user entry to collection.

Now you have to start your mongoDB by tying below command in terminal.

mongod

Your mongoDB is started. Now you can run server by typing below command

node app



If node app command runs successfully then you will see the above output in terminal.

Now we will write a POST request. but before writing a POST request install body-parser npm package by typing below command in terminal.

npm install body-parser --save

This will install a body-parser npm package in your project. And you can see that in package.json file. Now we can write a POST request.

write below lines of code in app.js for POST request.

var bodyParser = require('body-parser');
app.use(bodyParser.json());
app.post('/users', function(req, res) {
var user = req.body;
var users = _db.collection('users');
users.save(user, function(err, users) {
res.json(users);
});
});
view raw gistfile1.js hosted with ❤ by GitHub
We have updated app.js file so we have to start the server again to see the changes.
So terminate node app process and run it again by typing node app command in terminal.

Now open Postman - REST Client


Click the image to see it in bigger size. By this POST request database named MEAN_Demo is created in mongoDB database. A user entry in user collection is also created. You can see that in Robomongo.


You just created a database and make a user entry. Similarly we can add another user to database using Postman - REST Client.


Now you can see in Robomongo, there will be two users.


Now we will write a GET request to get all users from database.

Write following lines of code in app.js for GET request.

app.get('/users', function(req, res) {
var users = _db.collection('users');
users.find({}).toArray(function (err, users) {
if(err) {
console.log('error in fetching users ', err);
} else {
res.send(users);
}
});
});
view raw gistfile1.js hosted with ❤ by GitHub
We have updated app.js file so we have to start the server again to see the changes.
So terminate node app process and run it again by typing node app command in terminal.

Now go to Postman - REST Client


We have created a GET request and get all users from database in Postman - REST Client. Now we will write a PUT request to edit a user.

Write below lines of code in app.js

var ObjectId = require('mongodb').ObjectID;
app.put('/users/:userId', function(req, res) {
var userId = req.params.userId,
newName = req.body.name;
var users = _db.collection('users');
users.updateOne({"_id": new ObjectId(userId)}, { 'name' : newName }, function (err, user) {
res.send(user);
})
});
view raw gistfile1.js hosted with ❤ by GitHub
Above code update a user by _id. So we have to give user id in URL param and new name in request body.
We have updated app.js file so we have to start the server again to see the changes.
So terminate node app process and run it again by typing node app command in terminal.

Now go to Postman - REST Client



In above PUT request we are passing id of user in URL param and new name in body. Here we have updated the name of user deepak to piyush and you can see that in Robomongo.


As you can see from above image we have updated the user name deepak to piyush. Now we will write a DELETE Request to delete a user.

Write below lines of code in app.js

app.delete('/users/:userId', function(req, res) {
var userId = req.params.userId;
var users = _db.collection('users');
users.removeOne({"_id": new ObjectId(userId)}, function (err, user) {
res.send(user);
});
});
view raw gistfile1.js hosted with ❤ by GitHub
We have updated app.js file so we have to start the server again to see the changes.
So terminate node app process and run it again by typing node app command in terminal.

Now go to Postman - REST Client



We have deleted the user named piyush and we can see it in Robomongo.


As you can see from above image, we have deleted the user named piyush and there is only one user named chetan in mongoDB database.

We have completed all the CRUD operations that is create user, get users, update user and delete user. In the second part of this tutorial we will do the front end coding in AngularJS. Here is the link of second part http://nothingbeyondjavascript.blogspot.in/2015/06/developing-mean-application-part-2.html

Tuesday, May 19, 2015

MVC in AngularJS

Angular JS supports MVC style of application design. MVC means Model-View-Controller. Lets understands each of this in Angular JS.

Controller

Controller responsibility is to wire up the $scope (which holds your models) to your view. Angular Model lives inside a controller, you use $scope inside a controller as a glue between controller and view.
Controller contains business logic behind the application to decorate the scope with functions and values.

Example : controller creation

var app = angular.module(‘firstApp’, []);
app.controller(‘MyController’, function($scope) {
});
view raw gistfile1.js hosted with ❤ by GitHub

Model

A model in angular can be a primitive type such as string, number, boolean or a complex type such as object. In short model is just a plain javascript object.
Model lives inside a controller.
Scope is an object and models are the properties of a scope

Example : model creation

var app = angular.module(‘firstApp’, []);
app.controller(‘MyController’, function($scope) {
// model called ‘name’ which is a string
$scope.name = “Deepak Sisodiya”;
});
view raw gistfile1.js hosted with ❤ by GitHub
Here name is model of type string and name is the property of $scope object.

View

View is what the users see, in angular view is HTML

Example : view creation

<!DOCTYPE html>
<html ng-app="firstApp">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js"></script>
</head>
<body ng-controller="MyController">
<p>Hello {{ name }}</p>
</body>
</html>
view raw gistfile1.html hosted with ❤ by GitHub

Lets combine all components that is Model-View-Controller

<!DOCTYPE html>
<html ng-app="firstApp">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js"></script>
</head>
<body ng-controller="MyController">
<p>Hello {{ name }}</p>
<script>
var app = angular.module('firstApp', []);
app.controller('MyController', function($scope) {
$scope.name = "Deepak Sisodiya";
});
</script>
</body>
</html>
view raw gistfile1.html hosted with ❤ by GitHub

model contains your data and with the help of $scope in controller, your model data will be available to your view

Link of Model-View-Controller example

Resource
http://mrbool.com/mvc-in-angularjs/28962

Saturday, May 9, 2015

Convert the local time to another time zone in JavaScript

In JavaScript, Date() object get time from your local system. And what, when you deploy your website to server and your server is in the Germany then it get time according to the Germany time zone And you want Indian time whatever your server location.

I recently face this situation. I am working on a website which runs only 8PM to 4AM according to the Indian time zone. So I found a solution for this on the internet which i am writing here.

before that you have to understand the offset, In JavaScript we can get offset by getTimezoneOffset() method of Date object and it gives the difference between UTC time and your local time.

For Example
Your server has Singapore time zone and you want indian time.

var d = new Date();
var time = d.getTime();    // time in milliseconds

var offset = d. getTimezoneOffset();      // gives -480

This is the offset of Singapore and tells that Singapore is ahead of UTC time by 480 minutes
-(minus) specify ahead of UTC time and +(plus) specify behind of UTC time.
Like, if UTC time is 1 PM then Singapore time is 9 PM

var offset = offset * 60 * 1000;

So for getting UTC time

var UTC = time + offset;
This is the actual UTC time which is located in London at Greenwich from where all other country time is calculated.

Now we have UTC time, for getting Indian time we have to know the offset of the India. and Indian offset is +5.5 hours, it means india is 5.5 hours ahaed of UTC time, thus by adding this to UTC time we can get the Indian time

var indianOffset = 5.5 * 60 * 60 * 1000;    // in milliseconds

var IndianTime = UTC + indianOffset;

var nd = new Date(IndianTime);

// this nd is indian time.

Resource
http://www.techrepublic.com/article/convert-the-local-time-to-another-time-zone-with-this-javascript/

Saturday, May 2, 2015

Introduction to mongoDB database

In MongoDB

Collection    :   Table
Document    :   Row
Field            :   Column

1. Find all documents of items collection
1. db.items.find();
view raw gistfile1.js hosted with ❤ by GitHub

2. Find documents of items collection whose price is 10
db.items.find({ price : 10 });
view raw gistfile1.js hosted with ❤ by GitHub

3. Find documents of items collection whose price is greater than 20
db.items.find( { price : { $gt : 20 } });
view raw gistfile1.js hosted with ❤ by GitHub

4. Find documents of items collection whose price is greater than 20 and less than 100
db.items.find({ price : { $gt : 20, $lt : 100 } });
view raw gistfile1.js hosted with ❤ by GitHub

5. Loop through all documents of items collection and print JSON
var myCursor = db.items.find();
myCursor.forEach(printjson);
view raw gistfile1.js hosted with ❤ by GitHub

6. Find first two document of items collection
db.items.find().limit(2);
view raw gistfile1.js hosted with ❤ by GitHub

7. Skip first two document of items collection and display others
db.items.find().skip(2);
view raw gistfile1.js hosted with ❤ by GitHub

8. Insert a document in items collection
db.items.insert({
name : 'daal makhni',
itemCode : 'a1',
price : "120",
sellingPrice : "140",
restaurant : "5540ca56d1f925f156a8c33d"
});
view raw gistfile1.js hosted with ❤ by GitHub

9. Find first document of items collection
db.items.findOne(); is same as db.items.find().limit(1);
db.items.findOne();
view raw gistfile1.js hosted with ❤ by GitHub

10. Find all document of items collection where name is ‘daal’ or ‘daal makhni’
db.items.find({ name : { $in : ['daal', 'daal makhni'] } });
view raw gistfile1.js hosted with ❤ by GitHub

11. And condition
db.items.find({ name : 'daal', price : 10});
db.items.find({ $and : [{ name : 'daal', price : 10}] });
db.items.find({ $and : [ {name : 'daal'}, {price : 10} ] });
view raw gistfile1.js hosted with ❤ by GitHub

12. Or condition
db.items.find({ $or : [{name : 'daal'}, {price : 20}] });
view raw gistfile1.js hosted with ❤ by GitHub

13. $and and $or both condition
db.items.find({ type : 'veg', $or : [ { name : 'daal'}, {name : 'rice'} ] });
view raw gistfile1.js hosted with ❤ by GitHub

14. Start mongoDB shell
      This will connect you to running mongod instance
mongo (Enter this in terminal)
view raw gistfile1.js hosted with ❤ by GitHub

15. Show the list of databases
show dbs
view raw gistfile1.js hosted with ❤ by GitHub

16. Show current db
db
view raw gistfile1.js hosted with ❤ by GitHub

17. If database nite-foodie-internal is exist then this command switch to nite-foodie-internal database. If database nite-foodie-internal is not exist then this command create database named nite-foodie-internal
use nite-foodie-internal
view raw gistfile1.js hosted with ❤ by GitHub

18. Deleted all collection of current database
db.dropDatabase();
view raw gistfile1.js hosted with ❤ by GitHub

19. Show all collections of current database
show collections
view raw gistfile1.js hosted with ❤ by GitHub

20. Create collection items in current database
db.createCollection(‘items’);
view raw gistfile1.js hosted with ❤ by GitHub

21. Delete collection items of current database
db.items.drop();
view raw gistfile1.js hosted with ❤ by GitHub

22. Update query
      Update the title
db.COLLECTION_NAME.update(SELECTIOIN_CRITERIA, UPDATED_DATA);
db.items.update({ title : 'first title'}, { $set : { 'title' : 'new title' } });
view raw gistfile1.js hosted with ❤ by GitHub

23. Delete documents where title equal to ‘new title’ of items collection
db.items.remove({title : 'new title'});
view raw gistfile1.js hosted with ❤ by GitHub

24. Delete all documents of items collection
db.items.remove({});
view raw gistfile1.js hosted with ❤ by GitHub

25. Find all documents of items collection and display only name price and type of each document.
In MongoDB when you execute find() method, then it displays all fields of a document. To limit this you need to set list of fields with value 1 or 0. 1 is used to show the field while 0 is used to hide the field.
db.items.find({}, {name:1, price:1,type:1});
view raw gistfile1.js hosted with ❤ by GitHub

26. Sort is used to sort data
      1 is used for ascending order while -1 is used for descending order
db.items.find({}).sort({ 'name' : 1});
db.items.find({}).sort({ 'name' : -1});
view raw gistfile1.js hosted with ❤ by GitHub

27. This query will loop through all documents of collection items and sum all price of same type
{ "_id" : "egg", "total_price" : 30 }
{ "_id" : "non-veg", "total_price" : 20 }
{ "_id" : "veg", "total_price" : 161 }
db.items.aggregate([ { $group : { _id : "$type", total_price : { $sum :"$price" } } } ]);
view raw gistfile1.js hosted with ❤ by GitHub

28. Create backup
mongodump --collection COLLECTION_NAME --db DB_NAME
mongodump --db nite-foodie-internal
// create backup of nite-foodie-internal database
mongodump --collection items --db nite-foodie-internal
// create backup of items collection of nite-foodie-internal database
view raw gistfile1.js hosted with ❤ by GitHub

29. Restore database nite-foodie-internal to mongoDB
mongorestore dump/nite-foodie-internal
view raw gistfile1.js hosted with ❤ by GitHub

30. Returns the count of documents that would match a find() query
db.items.find({}).count();
view raw gistfile1.js hosted with ❤ by GitHub

31. Apply regex in mongoDB query
db.items.find({ cuisine : new RegExp('^Indian$', 'i') });
view raw gistfile1.js hosted with ❤ by GitHub

32. How to export MongoDB database in CSV format
mongoexport --host localhost --db databaseName --collection collectionName --csv --out fileName.csv --fields commaSeperatedFieldsName
mongoexport --host localhost --db nite-foodie-pro --collection customers --csv --out text.csv --fields number
view raw MongoDB.sh hosted with ❤ by GitHub

Tuesday, April 28, 2015

Regular expression in JavaScript

In JavaScript regular expressions are object. Regular expressions are patterns used to match character combinations in strings.

Example 1
i for case-insensitive search

var str = "DEEPAK SISODIYA";
var pattern = /deepak/i;
pattern.test(str); // true
view raw gistfile1.js hosted with ❤ by GitHub

Example 2

/abc/.test('abcde') // true
/abc/.test('abdre') // false
view raw gistfile1.js hosted with ❤ by GitHub

Example 3
^ indicates the beginning of the string. Using a ^ meta character requires that the match start at the beginning.
\d indicates a digit character and the {5} following it means that there must be 5 consecutive digit characters.
$ indicates the end of the string. Using a $ meta character requires that the match end at the end of the string.

// validation for only 5 digits
/^\d{5}$/.test('12345') // true
/^\d{5}$/.test('123456') // false
/^\d{5}$/.test('1234F') // false
view raw gistfile1.js hosted with ❤ by GitHub

Example 4

// digits only
/\d/.test('11111') // true
/\d/.test('FFFF') // false
view raw gistfile1.js hosted with ❤ by GitHub

Example 5

// digit not allowed
/[^0-9]/.test('111') // false
/[^0-9]/.test('asdasd') // true
view raw gistfile1.js hosted with ❤ by GitHub

Example 6

// characters only
/^[a-zA-Z]+$/.test('abcdes') // true
/^[a-zA-Z]+$/.test('abcdes123') // false
view raw gistfile1.js hosted with ❤ by GitHub

Example 7
Matches end of input.
For example, /t$/ does not match the 't' in "eater", but does match it in "eat"

/t$/.test('eater') // false
/t$/.test('eat') // true
// both for small and capital latter
/[tT]$/.test('eaT') // true
view raw gistfile1.js hosted with ❤ by GitHub

Example 8

// Matches begining of input.
/^t/.test('ate') // false
/^t/.test('tear') // true
/^[tT]/.test('Tear') // true
view raw gistfile1.js hosted with ❤ by GitHub

Example 9

// character and number only
/^[0-9a-zA-Z]+$/.test('abcdes123') // true
/^[0-9a-zA-Z]+$/.test('abcdes123@') // false
view raw gistfile1.js hosted with ❤ by GitHub

Example 10
The \w meta character is used to find a word character.
A word character is a character from a-z, A-Z, 0-9, including the _ (underscore) character.

/\w/.test('abcdes123_') // true
/^[0-9a-zA-Z_]+$/.test('abcdes123_') // true
view raw gistfile1.js hosted with ❤ by GitHub

Example 11
validation password
password can contain digits
password can contain character lower or upper case
password must have length between 5 to 10
password can contain _ (underscore)

/^[a-zA-Z0-9_]{5,10}$/.test('aqsZZ1234_') // true
/^[a-zA-Z0-9_]{5,10}$/.test('aqsZZ') // true
/^[a-zA-Z0-9_]{5,10}$/.test('aqsZ') // false
/^[a-zA-Z0-9_]{5,10}$/.test('aqsZZ@') // false
view raw gistfile1.js hosted with ❤ by GitHub

Example 12
validation password
password can contain digits
password can contain character lower or upper case
password must have length between 5 to 15
password can contain !@#$%^&*_ (special character)

/^[a-zA-Z0-9!@#$%^&*_]{5,15}$/.test('aqsZZ_!@#$%^&*') // true
view raw gistfile1.js hosted with ❤ by GitHub

Example 13
validation password
password should contain atleast one digit
password should contain atleast one special character
password can contain character lower or upper case
password must have length between 5 to 15

/^(?=.*[0-9])(?=.*[!@#$%^&*_])(?=.*[A-Z])[a-zA-Z0-9!@#$%^&*_]{5,15}$/.test('ase123@A') // true
view raw gistfile1.js hosted with ❤ by GitHub

Example 14
validation password
password should contain atleast one digit
password should contain atleast one special character
password should contain atleast one upper case latter
password can contain character lower or upper case
password must have length between 5 to 15

/^(?=.*[0-9])(?=.*[!@#$%^&*_])(?=.*[A-Z])[a-zA-Z0-9!@#$%^&*_]{5,15}$/.test('ase123@A') // true
view raw gistfile1.js hosted with ❤ by GitHub

Example 15
validation
atleast one number
atleast one lower case latter
atleast one upper case latter
must have more than 5 length

/^(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z]).{5,}$/.test('1aAsdf') // true
/^(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z]).{5,}$/.test('1aA sdf') // true
// with no spaces (spaces not allowed)
/^(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z])(?!\S).{5,}$/.test('1aA sdf') // false
view raw gistfile1.js hosted with ❤ by GitHub

Wednesday, April 22, 2015

Adding an existing project to GitHub

1. Go to the project directory and run the command 'ls -al' to see .git directory exist in your project or not, if it is not exist then run the below command.

git init

You can see .git directory is created in your project directory.

2. Then by running 'git status' command, you can see the files. You have to add these files to git

git add .

3. then you have to commit

git commit -am "my first commit"

4. Now you have to add remote to your project but first you need to create repository in Github.
Go to Github and create repo.

5. Now you have to add a remote, you can see the remote by 'git remote -v' command.

git remote -v
// display empty result

You can add remote by following command.

git remote add origin address_of_remote_repo

Now run

git remote -v
// you will see the remote url

6. Now you need to pull master from your project.
Run below command

git pull origin master

7. Last you need to push your files to Github repo.

git push -u origin master

Sunday, April 19, 2015

$http service in AngularJS

$http service in AngularJS is used to send AJAX request.

var promise = $http(config);

Here the config parameter is a JavaScript object which can contain the following properties

1. Method
2. URL
3. Params
4. Headers
5. Data
6. Timeout
7. Cache
8. TransformRequest
9. TransformResponse
10. Withcredentials

1. Method : The method property can be GET, POST, PUT, DELETE. The method property type is String.

2. URL : URL of AJAX call. The URL property type is String.

3. Params : The Params property is used to set any additional request parameters to be appended to the URL query string. The Params property is a JavaScript object.

4. Headers : The header property is used to set any additional HTTP headers you want to sent to the server. The header property is a JavaScript object.

5. Data : The data property contains data to be sent to the server. Only PUT and POST request contains data property. The data property type is a object.

6. Timeout : The timeout property is used to set the timeout  for the AJAX call, when the timeout limit is reached, the AJAX call is aborted. The timeout is specified in milliseconds

7. Cache : The cache property is used to enable XHR GET request caching.

8. TransformRequest : The transformRequest property is used to set a function which can transform the request object before it is sent to the server.

9. TransformResponse : The transformResponse property is used to set a function which can transform the response sent back from the server, before it is passed to your application.


$http(config) return a "promise" object. This promise object has two functions success() and error(). Each of these two functions take a callback function as parameter. If the AJAX request succeeds, the callback function passed to the success() function is executed. if the AJAX request fails, the callback function passed to the error() function is executed.

Both functions take the following parameters :

1. Data
2. Status
3. Headers
4. Config

1. Data : The data parameter is the JSON object returned by the server.

2. Status : The status parameter is the HTTP status code returned by the server.

Format is

$http({
method : string, // GET, POST, PUT, DELETE etc
url : string, // URL of resource being requested
params : object, // Query parameters
headers : object,
data : object,
timeout : number,
cache : boolean,
transformRequest : function,
transformResponse : function,
withCredentials : boolean
})
.success(function(data, status, headers, config) {
// success
})
.error(function(data, status, headers, config) {
// error
})
view raw gistfile1.js hosted with ❤ by GitHub
GET Request Example

$http({
method : 'GET',
URL : '/getAddress'
param : { addressId : '55140073de3ae69038514625' }
})
.success(function(data, status, headers, config) {
$scope.address = data;
})
.error(function(data, status, headers, config) {
console.log('error in fetching address');
})
view raw gistfile1.js hosted with ❤ by GitHub
PUT Request Example

$http({
method : 'PUT',
URL : '/updateAddress/' + addressId
data : {
building: 'tower 18',
houseNo: '1202',
landmark: 'civic center',
society: 'amanora',
};
})
.success(function(data, status, headers, config) {
console.log('address updated successfully');
})
.error(function(data, status, headers, config) {
console.log('error in updating address');
})
view raw gistfile1.js hosted with ❤ by GitHub
POST Request Example

$http({
method : 'POST',
URL : '/createAddress/'
data : {
building: 'tower 18',
houseNo: '1202',
landmark: 'civic center',
society: 'amanora',
};
})
.success(function(data, status, headers, config) {
console.log('address created successfully');
})
.error(function(data, status, headers, config) {
console.log('error in creating address');
})
view raw gistfile1.js hosted with ❤ by GitHub

DELETE Request Example

$http({
method : 'DELETE',
URL : '/deleteAddress/' + addressId
})
.success(function(data, status, headers, config) {
console.log('address deleted successfully');
})
.error(function(data, status, headers, config) {
console.log('error in deleteing address');
})
view raw gistfile1.js hosted with ❤ by GitHub

Sunday, March 15, 2015

Difference between == and === in JavaScript

== converts the operands to the same type before checking for quality.
== checks only for same value.

Example

0 == false // true
2 == "2" // true
null == undefined // true
view raw gistfile1.js hosted with ❤ by GitHub

=== does not converts the operands to the same type before checking for quality.
=== checks for same value + same type. 

Example

0 === false // false
2 === "2" // false
null === undefined // false
view raw gistfile1.js hosted with ❤ by GitHub

Link of Examples
== Comparison Operator
=== Comparison Operator