Book Image

Learning Node.js for Mobile Application Development

Book Image

Learning Node.js for Mobile Application Development

Overview of this book

Table of Contents (21 chapters)
Learning Node.js for Mobile Application Development
Credits
About the Authors
About the Reviewers
www.PacktPub.com
Preface
14
Creating an E-Commerce Application Using the Ionic Framework
Index

MongoDB


In order to store data related to your app and users, your server will need a database—a piece of software that is dedicated solely to data storage and retrieval.

Databases come in many variants. In this book, our focus is NoSQL databases, which are so named because they don't use the traditional table-oriented SQL data access architecture that is used by the more well-known relational databases, such as Oracle, MySQL, and PostgreSQL. NoSQL databases are very novel in their design and features and excellent for the tackling of the challenges that one may face in modern app development.

The NoSQL database that we will use throughout this book is MongoDB (it is often abbreviated as MDB or simply Mongo). MongoDB is a document-oriented database that which stores data in documents, which are data structures that are almost identical to the standard JSON format.

Let's have a look at how to install and get MongoDB running. If you have used a more traditional DB system, you may be surprised at how easy it is.

Installation of MongoDB on different Operating System

MongoDB comes in the form of a package for most major OS and versions.

Windows

MongoDB ships with a complete MSI for installation on Windows systems. To download it, go to the project's official website, www.mongodb.org, navigate to Downloads, and select the Windows tab. You will be offered the following three choices to download:

  • Windows 64-bit R2+: Use this if you are running Windows Server 2008, Windows 7 64-bit, or a newer version of Windows

  • Windows 32-bit: Use this if you have a 32-bit Windows installation that is newer than Windows Vista

  • Windows 64-bit legacy: Use this if you are using Windows Vista 64-bit, Windows Server 2003, or Windows Server 2008.

Note

MongoDB does not run on Windows XP at all.

After you have downloaded the MSI, run it with administrator privileges in order to perform the installation. The installation wizard will give you a default location where MongoDB will be installed—C:/mongodb/. You can change this if you desire, but it is recommended that you keep it as we will assume that this is the location where MongoDB resides for the remainder of the book.

After the installation has finished, the next step is to configure a data directory where MongoDB can store the data that we will feed it with. The default location for this directory is /data/db. We will need to make sure that this directory exists and is writeable before we start our MongoDB instance for the first time. So, fire up the command prompt with administrator privileges and issue the md/data/dbcommand. After doing so, we are good to start the database server itself. To do so, stay in the command prompt and issue the following command:

C:/mongodb/bin/mongodb.exe

You should receive a confirmation that MongoDB is now running and listening for connections. All is set!

Linux

On Linux, you will find MongoDB ready-packaged on most major distributions. However, we strongly recommend that you use the project's own repositories in order to make sure that you always have access to the most current security and stability updates.

Ubuntu

First off, you will need to enable the official MongoDB repository. To do so, open a terminal and first import the project's public GNU Privacy Guard (GPG) key as follows:

sudo apt-key adv --keyserverhkp://keyserver.ubuntu.com:80 --recv7F0CEB10

Once this is done, create a listing for the repository itself by issuing the following command:

echo 'deb http://downloads-distro.mongodb.org/repo/ubuntu-upstart dist10gen' | sudo tee /etc/apt/sources.list.d/mongodb.list

Your repository listing is now active. Let's make Advanced Package Tool (APT) aware of it in order to install MongoDB, as follows:

sudo apt-get update

Finally, issue the following command to install MongoDB:

sudo apt-get install mongodb-org

Fedora/RHEL/CentOS

Our first order of business here is to enable the official MongoDB repository. To do so, first make sure that you have the nano text editor installed by opening a terminal and issuing the following command:

sudo yum install nano

After this is done, add the repository by issuing the following command:

sudonano /etc/yum.repos.d/mongodb.repo

Nano will open a new, blank text file. Copy and paste the following into the file:

[mongodb]
name=MongoDB Repository
baseurl=http://downloads-distro.mongodb.org/repo/redhat/os/x86_64/
gpgcheck=0
enabled=1

Save and close the file by pressing Ctrl+O, followed by the Enter key. This is followed by Ctrl+X.

Finally, carry out the installation by issuing the following command:

sudo yum install mongodb-org

Starting MongoDB

After the installation of MongoDB, you will need to start MongoDB as a service in order to get it running. To do so (on all the distros that were previously mentioned), open a terminal and run the following command:

sudo service mongodb start

It is important that if you have SELinux running, you must make sure that it allows MongoDB to access its default port. To do so, issue the following before you issue the preceding command:

sudosemanage port -a -t mongod_port_t -p tcp 27017

Mac OS X

The easiest way to both install and stay up to date with MongoDB on OS X is by using the Homebrew package manager. Even if we just use it to install MongoDB here, you will most likely find it useful later for the installation of other software packages that you may need for your own projects after you finish this book.

Installing Homebrew is simple; just open a terminal and issue the following command:

ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"

When this finishes, make sure that the Homebrew package database is up to date, as follows:

brew update

Finally, install MongoDB by simply issuing the following command:

brew install mongodb

When the install has finished, we will need to define a data directory in order to give a location for MongoDB to store its data. By default, this directory will be at /data/db. So, unless you specify something else, you will need to make sure that this directory exists and is both writeable and readable by the user running your MongoDB instance. For example, if the user running MongoDB on your system is john, you will have to issue the following commands:

sudomkdir -p /data/db
sudochmod 0755 /data/dbsudochownmongod:mongod /data/db

Now that this is done, it is time to start up MongoDB. To do so, make sure that you are logged in as john, open a terminal, and simply issue the following command:

mongodb

That's it! You should receive a notification that MongoDB has started and is listening for a connection. Your instance is ready to go!

Connecting to MongoDB

In order to read and write from the MongoDB instance, we will first need to connect to it. In fact, MongoDB acts as a server in its own right. It exposes its functionality via a network port on which clients can then connect either through the local machine, or even over the Internet.

Note

Since this functionality is disabled by default due to it being a shoddy security practice, it will require a special configuration of the operating system that MongoDB is running on. We will not discuss this functionality as it falls outside the scope of this book, but we will refer to the MongoDB documentation for several helpful examples of how to achieve it for a variety of OS.

To connect to a MongoDB instance, you will need at least the following information:

  • The IP address of the instance: If you are accessing an instance on your local machine, this will be local host by default.

  • The port on which MongoDB is listening: Unless you configure a custom value, this will always default to port 27017.

  • The database that you are trying to connect to: Don't confuse this with the MongoDB instance itself. Each MongoDB instance can contain any number of databases, with each belonging to different users. The instance simply manages access to them.

Alternatively, you may also need the following:

  • A username and its associated password to grant you access to the instance and any databases therein that you are authorized to interact with.

A very easy way to try out this connectivity yourself and verify that MongoDB works as expected is by using the MongoDB shell, a tool that comes installed with MongoDB itself using the methods that we have described previously. How you access the shell varies depending on your OS. I will show each method in the following section and then give an example of how to use the shell itself since this will be the same on all platforms.

Windows

First, make sure that MongoDB is running by following the process that was outlined previously. After this, issue the following command in your command prompt:

C:\mongodb\bin\mongo.exe

Linux and OS X

First, make sure that MongoDB is running. Then, open a terminal and issue the following command:

mongo

Now that our shell is running, let's verify that everything works by creating a database and adding some data to it.

To create a database, issue the following command to the shell:

use Fruits

This will create a database named Fruits, to which we can immediately start adding data. (What, you were expecting more overhead? Not in MongoDB!)

We will not add a collection to our database. A collection is simply a basket of data entries, which are grouped based on some logical characteristic. For example, let's suppose that we want a collection of chewy fruits. We then issue the following command:

db.createCollection("Chewy")

The shell should respond with the { "ok" : 1 } JSON response that tells us that everything went well. Now, let's add some chewy fruits to our collection, as follows:

db.Chewy.insert({"name" : "pear"});
db.Chewy.insert({"name" : "apple"});

Even if the naming makes it intuitively clear what is going on in the preceding code, don't worry if you do not understand all the details yet. We will get to this in due course.

Finally, let's make MongoDB show us the chewy fruits that we stored. Issue the following command:

db.Chewy.find();

The shell will respond with something like the following:

{ "_id" : ObjectId("54eb3e6043adbad374577df9"), "name" : "apple" }
{ "_id" : ObjectId("54eb4036cdc928dc6a32f686"), "name" : "pear" }

The _id numbers will be different on your system, but you will find that the names are the same. All the fruits are where we want them to be.

Congratulations, you now have a fully working MongoDB setup ready for action!