What is connect module and how it works in Node.js

Hey guys,

I hope you are good, I am fantastic today 🙂  I got my first mechanical keyboard, I feel awesome about it 🙂

Today I have very interesting topic for you. I will show you how to work with connect module and how to process response and request. I hope you enjoy it 🙂

 

 

 

Advertisement

How can Install MongoDB and Create Database?

Hey Guys,

Now it is time to do some fantastic thing, normally connecting to database and retrieving data from database or writing into database is quite interesting if you are working with new platform and tools. Today I want to show you how to connect to the MongoDB and retrieve data (of course I will teach you how to insert first), for a few seconds forget about node.js and focus on MongoDB, in order to create a database in MongoDB we need to follow the below steps:

  1. MongoDB is an open source database which can be downloaded from the: http://www.mongodb.org . So please open the link and download it. For this tutorial we need MongoDB version Windows 64-bit 2008 R2+
  2. If you cannot do it please close the website and turn off your pc and do something else as you are not qualified for developing. (Just kidding) if you have difficulty to download or install, please click here to see the video which I uploaded on my YouTube channel.
  3. After you install, you need to run your MongoDB server, it is very easy.
    1. Please make sure that you created Data folder in your node folder, I created something like this : E:\node\nodetest1\data
    2. Now we want to create database and copy necessarily files into the data folder. Open command prompt and go to the MongoDB bin folder, (if you watch video you can see how I moved to bin folder). For those lazy people that do not want watch video you can find Bin folder in this address:

C:\MongoDB\Server\3.0\bin

After you moved to this folder key in the below command:

mongod –dbpath E:\node\notetest1\data

Note:  dbpath is the address of data folder, so maybe your data folder address is different from mine, please change it accordingly.

Note: In some cases I saw that mongod does not work, so for this case you need to key in the full address of mongod.exe, actually mongod is exe file in bin folder!!!!

Note: it may take a few seconds to a few minutes for command to be finished so please be patient.

  1. After you ran the command you could see a few files and folders are created in Data folder and also in your command prompt window you can see MongoDB is waiting for connection.
  2. It means you are in a right direction and your MongoDB is waiting for connection.
  3. Something like this:
  4. Be default mongoDB is connected to the test database and even you can see the name of test on your screen once you copy all the necessarily  files to the data folder, but do not worry about it, we can always switch to our own database, for this purpose you need to run the MondoShell, to run MondoShell you need to run the below command:

C:\MongoDB\Bin\mongo.exe

After you press enter you can see something like this:

MongoDB Wating for connection

To change the database you can type this command:

Use [name of you database]

Connect to Differtent Database

Mongo DB uses Json data structure to keep data, so before we go further I want to show you how Json format looks like:

{“name”:”Mehran”,”code”:”123”}

{“name”:”Arash”,”code”:”234VF”}

{“name”:”Arman”,”code”:”EDRng”}

Basically json format is very simple and understandable for human.

How can we add record to our database?

In order to add records to your database you can use the below command:

db.insert.testcollection.insert({“name”:”Arman”,”code”:”EDRng”})

In the above command, testcollection is a user defined name for the collection. It means you can change it as you want. This collection looks like and array and keep all the records. Above command must be ran in mongo shell. (Same as step 5).

How can we retrieve records?

In order to retrieve data you can run the below command:

db.testcollection.find ().pretty ()

Then result is something like this:

{

“_id” : ObjectId(“55d1b2028f5be420d8a167fc”),

“name” : “Mehran”,

“code” : “123”

}

MongoDB use

in the next post I will teach you how to retrieve data from MongoDb and show it Html file by using Node.js.

bye bye 🙂

How can retrieve data from Json source and show them on the page?

Maybe it is very difficult for you to connect to the Json file and retrieve data, today I want to make it easy for you 🙂 Lets start.

Follow these steps:

  1. We need a Json file for the source that produces Json data for us. To make a Json file please follow these steps :
    1. Make a new  text file and copy this information to the file
"one": "Singular sensation",

"two": "Beady little eyes",

"three": "Little birds pitch by my doorstep"
    1. Change the file extension to the Json
    2. Now you have Json file that contains data , please copy the file in your project ( I assumed you are working in Visual studio )
    3. There two types of instructions that you can follow to read a Json file , Today I want to use $.getJSON (This a JQuery function)
<script>

    $(document).ready(function () {

        $.getJSON("Data/info.Json.", function (data) {
        var items = [];
        $.each(data, function (key, val) {
            items.push("<li id='" + key + "'>" + val + "</li>");
        });

        $("<H1>", {
            "class": "my-new-list",
            html: items.join("")
        }).appendTo("body");
    });
    })

</script>

GetJSON hast two parameters

  • Source of JSON , it could be URL or the address of JSON file
  • The function that gets data from JSON source

        $.getJSON("Data/info.Json.", function (data) {

4.  Then we should add data to the array


        $.each(data, function (key, val) {
            items.push("<li id='" + key + "'>" + val + "</li>");
        });

</script>

5.  And in the last step we should add the HTLM codes that we generated in the previous step to the body tag.


        $("<H1>", {
            "class": "my-new-list",
            html: items.join("")
        }).appendTo("body");
    });

And do not forget to add JQuery reference to your code , it coule be like this :

<script src="~/Scripts/jquery-ui-1.8.20.js"></script>
<script src="~/Scripts/jquery-1.7.1.js"></script>

What is JSON ?

JSON (JavaScript Object Notation) is a lightweight data-structure format for data interchange, JSON could be read by human and it is easy for machine to generate and pars it.

When should we use JSON?

Assume you want create a service that retrieve data from DataBase and send them to the client. What will happen if your client use different type of machines and platform same as Smart phone, PHP website, ASP.net Website, different type of operating system. There are two solutions:

  1. Create different services for different machines and platforms (is it economic?)
  2. Create a service that produces a global output that is readable by different machines and platforms.

I am sure you are agree with me that the second solution is more logical.

In my opinion WebAPI could be a good choice for our scenario because, it can produce JSON output that is readable by all machines and platform and also it uses HTTP to transfer data that, also this protocol is well known for all.

Today I am just going to show you how you can create a simple JSON data structure but, In the future I will show you how create a WebAPI and call it by JQuery.

This is simple JSON sample, I declare an employee array that can carry different employees’ data.

{
"employees": [
{ "firstName":"Mehran" , "lastName":"JN" }, 
{ "firstName":"Arman" , "lastName":"Nas" }, 
{ "firstName":"Farzam" , "lastName":"ABS" }
]
}

I am going to do it in a JavaScript code:

<!DOCTYPE html>
<html>
<body>
<h2>JSON Object Creation in JavaScript</h2>

<p>
Name: <span id="Name"></span><br>  
Family: <span id="Family"></span><br> 

</p>  

<script>
var JSONObject = {
  "Name":"Mehran",
  "Family":"Jan"};
document.getElementById("Name").innerHTML=JSONObject.Name  
document.getElementById("Family").innerHTML=JSONObject.Family 

</script>

</body>
</html>