01 Project – Node.js / Express / MongoDB – Part 00 – Creating the development environment

Every web development project require you to create the environment in which you will work. We need to do the following six things first:

1. Installing Node.js and npm (Node Package Manager)
2. Installing MongoDB
3. Creating the project folder
4. Creating the package.json file
5. Installing the MongoDB client for Node.js
6. Verifying the set up

You have to make sure that you have administrator privileges since it is required when installing Node.js and MongoDB. You should be fine with whatever operating system you want to use (Windows, Mac, or Linux). I use Linux, so all the examples and screen shots will be from a Linux machine.

As a text editor I use Atom but any other editor will do just fine. You might want to try Sublime, Notepad++, or Brackets, which are all very popular. You will also need access to the command line via the Terminal program.

1. Installing Node.js and npm

First you have to make sure that you have Python installed in your machine. You can check that by typing in the terminal the following command:

python - -version

If it is not installed then you can install it via terminal by typing the following command:

apt-get install python-software-properties python g++ make

Node.js and npm are installed in my machine from the previous projects I completed. However, you can install Node.js on your machine very easily via terminal by typing the following command:

apt-get install nodejs

The npm should come with Node.js via the installation process. You can check if it is installed by typing in the terminal the following command:

npm --version

If it is not installed then just type in the terminal the following command:

apt-get install npm

Once the installation is finished you can check again for the version.

Note:
You might need to type sudo before typing the actual command (Example: sudo apt-get install nodejs).

Below is a screen shot of my terminal:

Install Node.js and npm

2. Installing MongoDB

As with Node.js, MongoDB can be easily installed via the terminal by typing the following command:

sudo apt install mongodb-server

Below is a screen shot of my terminal:

Install MongoDB

Once the installation is finished you can check if the installation was successful by typing the following command in the terminal:

mongod --version

3. Creating the project folder

Our application needs a folder where all the files will be stored. I have created one folder and I named it ProjectOne (within Documents folder). All our project files will be stored in the ProjectOne folder.

4. Creating the package.json file

We have to create a file that will store the necessary data regarding our application, such as: version, name, description, development, dependencies etc.

In order to do that you have to switch to your project folder in the terminal by typing the following command:

cd Documents/ProjectOne

Note:
The cd is the command used for changing directory.

Next, we need to type in the terminal the following command:

npm init

Initialize package.json file

Right now you just need to press “Enter” (about 9 times I believe) until it asks you “Is this ok?”. Type “y” then click enter.

Note:
I have completed two of the fields: description and author.

Initialize the package.json file

Now, if you go to your project folder, you will see inside a package.json file. It is the file that we have just created with the init command.

Go ahead, and open the package.json file.

package.json file

5. Installing the MongoDB client for Node.js

One of the first module we need is the MongoDB client for Node.js. Node.js needs to connect to MongoDB so this is what we are going to test by installing this module via npm.

Open the terminal and type the following command:

npm install mongodb --save

Now, in your project folder you can see a new folder named node_modules and it contain one folder named mongodb.

Our package.json file is also updated with one more field:

{
  "name": "projectone",
  "version": "1.0.0",
  "description": "My first Node.js project",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "Dan Dumitrache",
  "license": "ISC",
  "dependencies": {
    "mongodb": "^2.2.28"
  }
}

6. Verifying the set up

In order to verify the set up we need to create a file and write some code in it. The file will be used just for testing. The code we are going to write in it will connect the MongoDB database, insert a couple of records in it, and give us the feedback on whether or not the data was inserted properly or not.

I have created a file named test.js. Below is the code written for testing purpose.

// Section 1
var MongoClient = require('mongodb').MongoClient;

// Section 2
var connectionUrl = 'mongodb://localhost:27017/projectone',
    sampleCollection = 'articles';

// Section 3
var articles = [{
    'Title': 'Article1',
    'Author': 'Me - Dan'
},{
    'Title': 'Article2',
    'Author': 'You - a stranger'
}];

// Section 4
MongoClient.connect(connectionUrl, function(err, db) {
  console.log("Connected correctly to server");
  var collection = db.collection(sampleCollection);
  collection.insert(articles,function(error,result){

    if(!error) {
      console.log("Success :"+result.ops.length+" articles inserted!");
    } else {
      console.log("ERROR!");
    }
    db.close();
  });
});

I have divided the code into 4 sections which I am going to explain.

Section 1

var MongoClient = require('mongodb').MongoClient;

In Node.js, this is how you bring an external file dependencies into the current file in use. It is the required convention in Node.js.

Section 2

var connectionUrl = 'mongodb://localhost:27017/projectone',
    sampleCollection = 'articles';

We declare a variable for the database server information and collection we want to work with. The sampleCollection is a prototype method in MongoDB. You can learn more about it on MongoDB website. The projectone is the database and articles is the collection.

Note:
In MongoDB, if a collection does not exist and you want to use it then MongoDB creates that collection automatically.

Section 3

var articles = [{
    'Title': 'Article1',
    'Author': 'Me - Dan'
},{
    'Title': 'Article2',
    'Author': 'You - a stranger'
}];

I have created an array of articles (two articles) that are going to be inserted into the database.

Section 4

// Section 4
MongoClient.connect(connectionUrl, function(err, db) {
  console.log("Connected correctly to server");
  var collection = db.collection(sampleCollection);
  collection.insert(articles, function(error, result){

    if(!error) {
      console.log("Success :" + result.ops.length + " articles inserted!");
    } else {
      console.log("ERROR!");
    }
    db.close();
  });
});

First line of code is the initialization of connection with MongoDB.
We use an anonymous function as a callback which takes in two parameters: err (which is error) and db variable which will have the connection object that can be used for further operations.

Once the connection is established the callback function will be triggered with either an error or a db object.

Next two lines of code var collection = db.collection(sampleCollection); and collection.insert(articles, function(error, result){ use the db object to get the collection named articles. The insert call puts the articles in the database.

All this process is made asynchronous using again a callback function. When the insert operation is completed the callback function is triggered. If there is no error then a message is displayed. If there is an error then another message is displayed.

Now, let’s go and launch the application.
First you have to start the MongoDB by typing in the terminal the command mongod.
Next you have to launch the application by typing in the terminal the command node test.js.

Inserting data into the MongoDB database

Now, using Mongo shell (a command line interface to the MongoDB server) we can actually take a look inside the database.

Open the terminal and type the following commands:

mongo
use projectone
show collections
db.articles.find() .pretty()

Note:
I run Node app twice so I have four articles in the database.

Checking the database via terminal with Mongo shell

This is all for the set up. Everything works properly so we can go ahead and start the actual project.

Leave a Reply