官术网_书友最值得收藏!

Adding the application code

Now, let's write the simple application code to test things out. This app is going to basically connect to our locally running MongoDB server, insert a few records as seed data, and then provide the output on whether or not the data was inserted properly into MongoDB.

You can download a Gist of the code via the URL: http://bit.ly/1JpT8QL.

Using your editor of choice, create a new file named app.js and save it to the application root, which is the testapp folder. Just copy the content of the above Gist on to the app.js file.

Understanding the code

Now, let's go through and explain what each section of the code is doing.

//require the mongoClient from mongodb module 
var MongoClient = require('mongodb').MongoClient;

The preceding line requires the MongoDB Node driver that we installed via npm. This is the required convention used in Node.js for bringing in external file dependencies to the current file in context. We will explain more about this in the coming chapters.

//mongodb configs 
var connectionUrl = 'mongodb://localhost:27017/myproject', 
    sampleCollection = 'chapters';

In the preceding code, we declare the variables for the database server information and collection we want to work with. Here, myproject is the database we want to use and chapters is the collection. In MongoDB, if you reference and try to use a collection that doesn't exist, it will automatically be created.

The next step would be to define some data that we can insert into MongoDB to verify whether everything is fine. So, we create an array of chapters here, which can be inserted into the database and collections we set up in the previous steps:

//We need to insert these chapters into mongoDB
var chapters = [{ 
    'Title': 'Snow Crash', 
    'Author': 'Neal Stephenson' 
},{ 
    'Title': 'Snow Crash', 
    'Author': 'Neal Stephenson' 
}];

Now, we can take a look at the rest of the code where we insert this data into the MongoDB database:

MongoClient.connect(connectionUrl, function(err, db) {   
  console.log("Connected correctly to server");    
  // Get some collection 
  var collection = db.collection(sampleCollection);  
  collection.insert(chapters,function(error,result){    
    //here result will contain an array of records inserted 
    if(!error) { 
      console.log("Success :"+result.ops.length+" chapters inserted!"); 
    } else { 
      console.log("Some error was encountered!"); 
    }    
    db.close();   
  });   
});

Here, we initiate a connection with the MongoDB server, and if the connection was proper, the db variable will have the connection object that we can use for further operations:

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

Look at the preceding code closely, do you remember something that we learned in Chapter 1, Welcome to JavaScript in the Full Stack. We are using a callback for the connection call that we are making here. As discussed in the first chapter, this function will be registered as a callback to trigger once the connection attempt is completed. Upon connection completion, this will be triggered with either an error or a db object depending on whether we were able to make proper connectivity or not.

So, if you look at the code in the callback function, we are not checking whether any error was raised in the connection attempt before logging connected correctly to the server. Now, that's your task to add and check while we try to run this app! Take a look at the following code block in this section:

var collection = db.collection(sampleCollection);
collection.insert(chapters,function(error,result){

This does nothing but use the db object we got in the connection call and get the collection named chapters. Remember that we set that value to sampleCollection at the beginning of the code. Once we get the collection, we make an insert call to put the chapters we have defined in the array chapters. As you can see, this insert call is also done via an asynchronous call by attaching the callback function. This callback function will be triggered once the insert operation is completed by the code residing inside the MongoDB native client, which we required as a dependency.

Next, we will take a look at the code inside the callback function, which we passed to the insert function call.

if(!error) { 
  console.log("Success :"+result.ops.length+" chapters inserted!"); 
} else { 
  console.log("Some error was encountered!"); 
}    
db.close();

Here, we process the values passed via the callback to find out whether the insert operation succeeded or not and the data related to the records which have been inserted. So, we check whether there was an error, and, if not, proceed to print the number of records that got inserted. Here, the result array will contain the records that we inserted into MongoDB, if the operation was a success.

Now we can go ahead and try to run this code, as we have understood what it does.

Launching the sample app

Once you have the complete code saved to app.js, it's time to execute it and see what happens. However, before you can launch an app that clearly relies on a connection to MongoDB, you need to first boot up the MongoDB daemon instance:

$ mongod

Note

In Windows, if you haven't set a PATH variable for mongod, you may need to use the full path while executing MongoDB, which is c:\mongodb\bin\mongod.exe. For your needs, the remainder of this book will refer to the mongod command, but you may always need to execute the full path in each instance.

Now, to launch the app itself, execute the following command after moving to the root folder where app.js is located:

$ node app.js

When the app first executes, you should see the following:

Connected correctly to server
Success :2 chapters inserted!

Checking the actual database

Let's take a quick look at the database itself to see what happened during the execution of the app. Since the server is currently up and running, we can connect to it using the Mongo shell—a command line interface to the MongoDB server. Execute the following commands to connect to the server using Mongo and run a query against the chapters collection. As you can see in the upcoming code, Mongo shell connects to a default database named test initially. We need to manually specify the database name to switch to, if its something other than test:

$ mongo
Mongod shell version: 2.4.8
connecting to: test
> use myproject
> show collections
chapters
system.indexes
> db.chapters.find().pretty()

Note

Here pretty is used as part of the command to format the result from the find command. This is used only in a shell context. It does more of a prettification task for the JSON.

You should see something similar to the following output.

{ 
    'id' : ObjectId("5547e734cdf16a5ca59531a7"),
    'Title': 'Snow Crash', 
    'Author': 'Neal Stephenson' 
},
{ 
    'id' : ObjectId("5547e734cdf16a5ca59531a7"),
    'Title': 'Snow Crash', 
    'Author': 'Neal Stephenson'
}

Note

If you run the Node app again, the records will be inserted into the Mongo server again. So, if you repeat the command multiple times, the result will have more records in the output. We are not handling this case in this chapter as we intend to have only specific code, which will be simple enough to understand.

主站蜘蛛池模板: 泊头市| 林西县| 巴林右旗| 宜州市| 浑源县| 城口县| 太谷县| 义乌市| 丰都县| 泽普县| 昌平区| 库车县| 肥西县| 峨眉山市| 南江县| 礼泉县| 克拉玛依市| 三明市| 新余市| 乐清市| 泰兴市| 扶沟县| 星子县| 汤原县| 晋城| 勐海县| 怀仁县| 旬阳县| 呈贡县| 桐庐县| 景泰县| 华蓥市| 肥东县| 麻江县| 龙海市| 邢台县| 罗甸县| 荆州市| 尼玛县| 临江市| 同仁县|