Quick introduction to MongoDB

MongoDB is a so-called NoSQL-Database (in contrast to SQL-Databases like MySQL). Unlike traditional databases these don’t require fixed table relations or a pre-defined schema which makes them more flexible to work with.
While NoSQL is not out there to replace SQL there are use cases where they’re better suited for the job.
Using MongoDB with NodeJS is great because it works extremely well with JavaScript. Entries in a MongoDB-Database are called ‘documents’ which are JSON-Objects in binary form (called BSON). This makes exchanging data between code and database almost seemless. A document to store a user might look like this:

Copy to Clipboard

Documents are grouped in collections, so we can have a collection ‘users’ containing all the… well… users^^
The flexible, schema-less nature of MongoDB enables us to simply add another attribute (e.g. ‘interests’) to one document without affecting all other documents. In MySQL this would require a migration and potential downtime of the entire database.
In MongoDB it’s perfectly okay for documents to have a varying set of attributes, which is just not possible in MySQL.

MongoDB allows for easier mapping of real world objects to a database-entry because related information is stored together, which is especially great for object oriented programming:

Copy to Clipboard

For a more in-depth introduction to MongoDB as well as a comparison between MongoDB and MySQL, check out this great article!

Setting up MongoDB

First we need the linux-packages

Copy to Clipboard

This will install the MongoDB-Server as well as a client to be able to check our database from the command line

Then we start the server

Copy to Clipboard

Install the node-package

Copy to Clipboard

Using MongoDB

This is the code we add to our server.js to connect to the Mongo-Database:

Copy to Clipboard

Seems like a lot of code, but it’s not that complicated. This is a good example of MongoDB integrating well with JavaScript. Passing a JSON-object that JavaScript understands to the database is just super easy.

Querying documents is not exactly rocketscience either:

Copy to Clipboard

Aside from code it’s sometimes nice to have some sort of ‘direct’ access to our database, e.g. for degugging. To do this, we open another terminal window and connect to the MongoDB-Server

Copy to Clipboard

We tell the server that we want to access our ‘node_tutorial’ database

Copy to Clipboard

Inside this database we can now more or less use the same command that we used in JavaScript to get our newly inserted user:

Copy to Clipboard

For more information about querying MongoDB, check out the documentation

If you’re coming from a MySQL background, you will find this mapping of SQL-commands to MongoDB to be helpful.

We’ve covered the most basic way NodeJS can communicate with MongoDB and it works perfectly fine. But as it can get a little verbose and we love clean code, we choose to do it slightly different…