MongoDB Local Installation and Setup

  • Download MongoDB server from the https://www.mongodb.com/download-center  and install. ( i prefer community edition ).
  • For these instructions, let us assume that you have installed MongoDB to C:\ProgramFiles\MongoDB\Server\3.4\.
  • MongoDB requires a data directory to store all data, so lets create a folder and point the data path to that folder.
"C:\Program Files\MongoDB\Server\3.4\bin\mongod.exe" --dbpath d:\test\mongodb\data
  • Now Start the MongoDB. Run the following code in command prompt.
"C:\Program Files\MongoDB\Server\3.4\bin\mongod.exe"

This starts the main MongoDB database process. The waiting for connections message in the console output indicates that the mongod.exe process is running successfully.

  • To connect to MongoDB through the mongo.exe shell, open another Command Prompt.
"C:\Program Files\MongoDB\Server\3.4\bin\mongod.exe"
  • In the Above mongo shell you can run some commands and play through it like ,
    • show dbs – Shows list of database
    • use dbName – Switch to that database
    • db.stats() – Gives the db status
    • show collections – Shows list of collections
    • db.collectionName.find() – List all the data in the collection

For More commands refer https://docs.mongodb.com/manual/mongo/

For Accessing this MongoDB with Local Node ( Refer Link )

Advertisements

CRUD – MongoDB using NodeJs in Local Machine

  • In order to access MongoDB database, we need to install MongoDB drivers. To install native mongodb drivers using NPM, open command prompt and write the following command to install MongoDB driver in your application.
npm install mongodb --save
  • For local Installation of MongoDB ( Refer Link ). Now, start the MongoDB server. (Assuming that your MongoDB database is at C:\MyNodeJSConsoleApp\MyMongoDB folder.)
mongod -dbpath C:\MyNodeJSConsoleApp\MyMongoDB
  • Create a node file and start coding. First Connecting MongoDB, local mongo alway opens connection in port 27017
var MongoClient = require('mongodb').MongoClient;
MongoClient.connect("mongodb://localhost:27017/exampleDb", function(err, db) {
  if(!err) {
     console.log("<------------We are connected------------>");
     //Write databse Insert/Update/Query code here..
  }
});
  • For Create collections,
 db.createCollection("collectionName", function(err, collection) {
     console.log("<------------DB Created------------>");
 });

  • For Insert Data,
var collection = db.collection(collectionName);

var doc1 = {'hello': 'doc1'};
collection.insert(doc1);

var doc2 = {'hello': 'doc2'};
collection.insert(doc2, {w: 1}, function(err, result) { // Using the {w:1} option ensure you get the error back if the document fails to insert correctly.
    console.log("<------------Data Inserted------------>");
});

var lotsOfDocs = [{'hello': 'doc3'}, {'hello': 'doc4'}];
collection.insert(lotsOfDocs, {w:1}, function(err, result) {});

  • For Update data,
 db.collection(collectionName).update({hello:'doc2'},{$set:{hello:"docUpdated",firstName: 'James'}}, {w:1}, function(err, result) {
    console.log("<------------Updated------------>");
 });

  • For Delete Data,
 db.collection(collectionName).remove({hello:'docUpdated'}, {w:1}, function(err, result) {
    console.log("<------------Deleted------------>");
 });

  • For View Data,
 db.collection(collectionName).find().toArray(function(err, items) {
     if(err) throw err;
     console.log(items);
 });

Array in Javascript

An array is used to store a collection of data. In javascript, data doesn’t need to have same type.

var arr = [ 1,"sam", true, {"name":"kumar"} ];

Declaration

Array can be declared in several ways,

Syntax Explanation Result
var myArray = new Array() Creates Empty Array [ ]
var myArray = new Array(3) Creates Array with
Length 3
Value all empty
[ ” “,” “,” ” ]
var myArray = [3] Creates Array with
length 1
Value 3
[3]
var myArray = new Array(1,2,3) Creates Array with
length 3
Value 1,2,3
[1,2,3]
var myArray = [“apples”, “bananas”, “oranges”] Creates Array with
length 3
Value “apples”, “bananas”, “oranges”
[“apples”, “bananas”, “oranges”]

Properties

Topics Syntax Explanation Result
Length var arr = [5,6,7];
arr.length;
returns number – Length of the array 3
Prototype Array.prototype.myUcase = function() {
for (i = 0; i < this.length; i++) {
this[i] = this[i].toUpperCase();
}
};
var fruits = [“Banana”, “Orange”, “Apple”, “Mango”];
fruits.myUcase();
Prototype is the concept of creating/modifing objects method.

In our case we created a method “Ucase”, which convert all the values in array to uppercase

[BANANA,ORANGE,APPLE,MANGO]

Methods

Topics Syntax Explanation Result
Concat
var a = [1,2,3];
var b = [4,5,6];
var c = a.concat(c);
This method adds two array [1,2,3,4,5,6]
var d = [].concat(a); For coping array to new variable, if we use like ( var var d = a; ) , ‘a’ don’t copy to ‘d’, instead it got refered. which means if u change any one of the array others get the change too.

So can use “Concat” to copy array to other variable.

d = [ 1,2,3 ]
Filter var age = [12,34,56,23];
var voter = age.filter(function(value, index){
return value > 18
});
Filter return a array with value which ever passes the given condition.

Returns array

voter = [34,56,23]
ForEach var a = [2,3,4];
a.forEach(function(val, index){
console.log(index+” : “+val);
});
Its a loop by which we can get all the values of the array one by one 0 : 2
0 : 3
0 : 4
Join var a = [2,3,4,5];
a.join(“/”);
Join convert array to string in which it concatinate all the array value with given symbol

Returns: string

“2/3/4/5”
Map var a = [2,3,4];
var b = a.map(function(val, index){
return val*val;
});
Map can change each value of the array

Returns array

[4,9,16]
Push var a = [2,3,4];
a.push(5);
Insert value to the array at last a = [2,3,4,5]
Pop var a = [2,3,4];
a.pop();
Remove value to the array at last a = [2,3]
UnShift var a = [2,3,4];
a.unshift(5);
Insert value to the array at First a = [5,2,3,4]
Shift var a = [2,3,4];
a.shift();
Remove value to the array at First a = [3, 4]
Splice var a = [1,2,3,4];
a.splice(2,1,7,8);
Splice add & remove value from the array
1st argument – Index – “where to start”.
2nd argument – delete – “how many value to be deleted”
from 3rd to “N” – “values to be added”array.splice( index , howManyToDelete, add1,.., addN)Returns Deleted value as array
Slice var a = [1,2,3,4];
var b = a.slice(1,3);
Slice select part of the array and form new array

Returns array

[2,3]
IndexOf var a = [2,3,4,5,6,4,7];
a.indexOf(4);
a.indexOf(6);
Return the first index value of specified item in the array

If not present returns “-1”

Returns: Number

2 \\ index of 4
-1 \\ since not present
LastIndexOf var a = [2,3,4,5,6,4,7];
a.lastIndexOf(4);
a.lastIndexOf(9);
Return the last index value of specified item in the array

If not present returns “-1”

Returns: Number

5 \\ index of 4
-1 \\ since not present
isArray var a = [1,2,4,3,4];
var b = “sam”;
typeof a;
Array.isArray(a);
Array.isArray(b);
If you try “typeof” for an “array”, it will return “Object”, thats where “isArray” comes. Finds whether the variable is array or not

Returns Boolean

“object” \\ result of “typeof”
true \\ for “a”
false \\ for “b”
Reverse var a = [1,2,3,4];
var b = a.reverse();
Reverse the order of the value in the array

Returns reversed array also changes the original array

[4, 3, 2, 1]
Sort var a = [3,2,4,1];
a.sort(function(a,b){ return a-b; });
a.sort(function(a,b){ return b-a; });
Sorts the array. it changes the original array.

Return the sorted array

[1, 2, 3, 4] \\ ascending
[4, 3, 2, 1] \\ decending

Disable Right Click and Show Div

To do this we need 2 node, One is the div which the right click is to be disabled and the other is the div which going to show instead of “contextmenu”.

 var rClickDisabledDiv = document.getElementsByClassName("rightClickDisabled")[0];
 var showDivNode = document.getElementsByClassName("showDiv")[0];

The key here is how to disable the right click.

  rClickDisabledDiv.addEventListener("contextmenu",function(e){
      showDivNode.style.display = "block";
      showDivNode.style.top = e.pageY+"px";
      showDivNode.style.left = e.pageX+"px";
      e.preventDefault();
  });

Rest will be piece of cake 🙂

function divOnRightClick(rClickDisabledDiv, showDivNode){
  rClickDisabledDiv.addEventListener("contextmenu",function(e){
      showDivNode.style.display = "block";
      showDivNode.style.top = e.pageY+"px";
      showDivNode.style.left = e.pageX+"px";
      e.preventDefault();
  });
  document.body.addEventListener("click",function(){
    showDivNode.style.display = "none";
  });
  showDivNode.addEventListener("click",function(e){
    e.stopImmediatePropagation();
  });
}

Demo

Decalation of Array in Javascript

An array is used to store a collection of data. In javascript, data doesn’t need to have same type.

var arr = [ 1,"sam", true, {"name":"kumar"} ];

Declaration

Array can be declared in several ways,

Syntax Explanation Result
var myArray = new Array() Creates Empty Array [ ]
var myArray = new Array(3) Creates Array with
Length 3
Value all empty
[” “,” “,” “]
var myArray = [3] Creates Array with
length 1
Value 3
[3]
var myArray = new Array(1,2,3) Creates Array with
length 3
Value 1,2,3
[1,2,3]
var myArray = [“apples”, “bananas”, “oranges”] Creates Array with
length 3
Value “apple”, “banana”, “orange”
[“apple”, “banana”, “orange”]

Get Postal code using latitude and longitude

Working Demo.

$(function() {
    var lat = 13.0826802;
    var longt = 80.27071840000008;
    var keyVal = "AIzaSyDm6BvPpVO0Fc2JRcXuRuafyX6mBr31nwM";
    $.ajax({
        url: 'https://maps.googleapis.com/maps/api/geocode/json?latlng=' + lat + ',' + longt + '&key=' + keyVal,
        type: "GET",
        dataType: 'json',
        async: false,
        success: function(data) {
            var results = data.results;
            var postalCode = getPostalCode(results);

            alert(postalCode);
        }
    });

    function getPostalCode(place) {
        for (var k = 0; k < place.length; k++) {
            for (var i = 0; i < place[k].address_components.length; i++) {
                for (var j = 0; j < place[k].address_components[i].types.length; j++) {
                    if (place[k].address_components[i].types[j] == "postal_code") {
                        return place[k].address_components[i].long_name;
                    }
                }
            }
        }
    }
});

Hoisting in javascript

Hoisting is JavaScript’s default behavior of moving declarations to the top.

function hoistTest(){
   x = 5;            // Assign "5" to x - now x is a global variable
   console.log( x ); // returns "5"
   var x;            // Declare x - now x is a local variable
}
hoistTest();
console.log( x ); // returns undefined

In the above example we assigned value for “x” without declaring it and declared it at last of function. But once javascript runs the declaration moved to top and “x” becomes the local variable. Hence outside the function it becomes undefined. This is how the “x” declaration in hoisted.

If not declared, “x” stays as global variable.

function hoistTest(){
   x = 5;            // Assign 5 to x - now x is a global variable
   console.log( x ); // returns "5"
}
hoistTest();
console.log( x ); // returns "5"