- Web Development with MongoDB and Node(Third Edition)
- Bruno Joseph D'mello Mithun Satheesh Jason Krol
- 674字
- 2021-07-08 10:32:42
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 that 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 by 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, 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 if the data related to the records that 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.
- ASP.NET Web API:Build RESTful web applications and services on the .NET framework
- 碼上行動:零基礎學會Python編程(ChatGPT版)
- Python編程完全入門教程
- Python數據分析(第2版)
- Monitoring Elasticsearch
- JavaScript動態網頁開發詳解
- Scientific Computing with Scala
- 劍指Java:核心原理與應用實踐
- Apache Spark 2.x for Java Developers
- Python+Tableau數據可視化之美
- Clojure for Machine Learning
- 單片機原理及應用技術
- 零基礎學C語言(升級版)
- 跟戴銘學iOS編程:理順核心知識點
- Python Programming for Arduino