Series: Introduction to the MEAN Stack
So far our server has only returned static data: files from the hard drive or texts stored in the source code. In order to integrate data dynamically, the NoSQL database MongoDB is used in the MEAN stack . In today’s article I explain to you the term NoSQL and how you use MongoDB with Node .
The definition of a NoSQL database is somewhat spongy. The “No” is not for “not”, but for “Not only”, “Not only SQL databases”. The term was introduced with this meaning in 2009 by Johan Oskarsson to describe all non-relational databases. However, the architecture of non-relational databases can be very different, requiring further subdivision. MongoDB belongs to the group of document-oriented databases . Here are documents whose structure can be freely determined, the data are stored in the database. (By comparison, MySQL stores data in tables.)
The MongoDB documents are stored in the so-called BSON format, a JSON-like binary format. Queries to the database are executed in JavaScript. MongoDB is, by the way, the most common NoSQL database .
While MongoDB can also be controlled via the terminal, this article series skips this step and shows the use of MongoDB with Node without any detours. We only need the terminal once to start MongoDB:
1
|
$ mongod
|
After MongoDB is initialized, we install in a new project folder Express together with the official MongoDB driver for Node. To download multiple modules at once with npm, you need to list several module names:
1
|
$ npm install express mongodb
|
Now Express and the MongoDB driver are installed. For the following example – we wrote everything back into a server.js
file – we split the source code into two parts. In the first part, we create a connection to our MongoDB database and create a collection . A collection is a group of related documents. In our example we want to save the visits of our website, so we call the collection visitsCollection
:
1
2 3 4 5 6 7 8 |
var MongoClient = require ( ‘mongodb’ ) . MongoClient ;
var visitsCollection ; MongoClient. connect ( ‘mongodb: // localhost 27017 / first-db’ , function ( err , db ) { if ( err ) . console log ( err ) ; else visits collection = db. collection ( ‘visits’ ) ; } ) ; |
In the first line, we load the module mongodb
from which we MongoClient
need it. In the second line, we declare the previously mentioned variable visitsCollection
, which we will need later. We then MongoClient
connect to our database via a link. The URL mongodb: // localhost: 27017 / is the default URL for a local MongoDB installation. The suffixfirst-db
the name is our database. Moment! We have not yet created a database with this name. How should we connect to this? This is not a problem. MongoDB automatically creates a database with this name the first time it is requested. After the URL, a callback is passed as the second parameter. You can recognize a typical pattern of Node: Callbacks often pass two parameters, the first parameter being an error object and the second parameter being the actual result . It is then possible to quickly check whether an error has occurred in order to output and intercept it accordingly. The actual result of this callback is adb
Object that exposes an API to our database. If no error has occurred, we would like to db
receive an access to our collection visits
, which we visitsCollection
store in the variable . Also applies to collections: We do not have to visits
create a collection with the name before , MongoDB automatically creates one, if not already exists.
What do we want to do visits
next with the collection ? You should save the visitors of our website. For this purpose we will create a new document, ie a new database entry, which contains the requested URL and the time of the visit. All previous visits are to be displayed. To achieve this, we need the second part of our server, which we create with Express:
1
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
var express = require ( ‘express’ ) ;
express ( ) . get ( ‘*’ , function ( req , res ) { var visit = { url : req. url , time : Date. Now ( ) } ; visits collection. insert ( visit , function ( err , doc ) { visitsCollection. find ( ) . toArray ( function ( err , docs ) { var log = ” ; . docs forEach ( function ( doc , index ) { log + = ‘Visited’ + doc. url + ‘on’ + doc. time + ‘in. ‘ ; } ) , res. send (log ) ; } ) ; } ) ; } ) . listen ( 1337 , ‘127.0.0.1’ ) ; |
Our server consists of a single middleware, which *
is valid for the route . One *
is a special placeholder for Express, which is internally converted into a regular expression. In this case, stands *
for any URL! No matter what URL the server is addressed, the following middleware is always running. At the beginning of the middleware, we create a visit
-Object with the URL and the time of the visit. This is stored later exactly in the database. The URL requested by the user can be queried via . Using the method of the object, thereq.url
insert
visitsCollection
visit
Object. As a second parameter, the method expects a callback with the signature of an error and a result object. After the save, the method of find
the visitsCollection
object is used to retrieve all stored visits, store them in a string named log
formatted, and then print them over . This is also true for any URL, because we are still in the same middleware.res.send
If you now visit http://127.0.0.1:1337/ you get as output “Visited / server on 1380190257203.”, whereby with you the time will be different. Tests various URLs like http://127.0.0.1:1337/test/ or http://127.0.0.1:1337/sddasd/ . You can also use a different browser or restart the Node server. The data will be retained and expanded on each visit. You may also notice the URL “/favicon.ico”, which you probably never entered yourself. This is a URL, which most browsers call independently to download the so-called favicon of a page. Your result should look something like this:
The use of the MongoDB driver is very simple and intuitive. Sometimes you want to have more control over the structure of your documents. For this purpose, you can use the Mongoose framework , which I will present to you in the next article.
1 Comment
How To Install MongoDB On Ubuntu - Virtono Community · April 13, 2023 at 12:39 PM
[…] can also configure other settings in the MongoDB configuration file, such as storage options, logging, and security. Refer to the MongoDB documentation for more […]