Having a node.js website without a database in the backend is going to be pretty limiting! So let’s address that.
There are a whole bunch of databases that we could use, but we’re going to go with a popular choice for Node.js development, MongoDB. In their own words:
MongoDB (from “humongous”) is a scalable, high-performance, open source NoSQL database.
Installing MongoDB on Ubuntu
If you Google how to do this you might get put off, as you’ll find a load of pages with different workarounds to get MongoDB installed correctly, Q&A threads on fixing install errors etc. Fortunately this has all been fixed, and it’s now super easy to install MongoDB on Ubuntu.
Open a terminal window and enter:
sudo apt-get install mongodb
That’s it! As soon as that’s finished downloading and processing you’ll have MongoDB installed.
Testing your MongoDB install
You want to test to make sure that it’s installed correctly? Fair enough. Let’s start it up as an Upstart service (more on Upstart at another time).
Start the MongoDB service
In terminal enter:
sudo service mongodb start
You should now see a confirmation along the lines of
mongodb start/running, process 15251
Using the MongoDB command line shell
MongoDB comes with a command line shell. We’ll use this to verify everything is running correctly.
To enter the MongoDB shell, in terminal simply enter:
This should tell you the shell version and connect you to the ‘test’ database that ships with Mongo. You should see something like this:
The “>” indicator at the start of a new line shows that you are now working in the MongoDB shell, not the Ubuntu command line.
Listing all databases
While we’re here, let’s see what MongoDB database have been created during installation.
In the MongoDB shell, enter this command to list all databases:
You should then see something like this screenshot, showing two databases and their sizes.
Exiting the MongoDB shell
Press Ctrl+D to exit the MongoDB shell and return to the terminal command line interface.
How to install the native MongoDB drivers for Node.js
So having got MongoDB installed, we want to make sure that our Node.js applications will be able to use it. For this we need to install the native driver. Note: there are actually loads of middleware modules to simplify and extend the possibilities which we’ll cover at another time. For now we’ll stick to the basics so that we’ve got a solid foundation to build upon.
To install the native MongoDB drivers we’ll use NPM, so head to terminal and enter:
npm install mongodb --mongodb:native
This will run through the installation process, downloading everything we need to get MongoDB and Node.js talking to each other!
Happy days! Next up we’ll be creating a MongoDB database so that we can actually use it with our Node.js MVC site.