- [Instructor] We will now extend
our maxcoin sample application
to connect to the MongoDB server that we just installed.
For that, I will change into the maxcoin directory
on my integrated terminal here
and I will also open the maxcoin directory
here on the left menu bar.
All databases have some communication channel
that can be used programmatically
and database drivers provide us with an API
to perform operations on the database using this channel.
For MongoDB, there is an official npm module called MongoDB
and we can install it by simply typing npm install MongoDB.
And if we look into package.json,
we see that it now installed MongoDB
and its diversion in my keys no 3.6.2.
To know how to use this driver,
there is of course an API documentation.
So if I head into my browser,
I can look for MongoDB node.js api, and there.
I end up on a page and there you see
a list of different drivers and links to the Reference
and to the API Documentation.
The Reference gives you tutorial-like guidance
on how to use this driver
and the API Documentation shows you, really,
how to use those different objects
that are provided by this driver.
So let's add the logic needed to connect to MongoDB.
For that, I open services,
and there I have a direct backend.
And in there, there is already a file for MongoDB,
my SQL and Redis,
and I open the MongoBeckoned.js file.
And, as you see here,
we already have some scaffold in this class
and we will now start to implement the connect function.
But to use this driver,
we of course have to refile it first.
So I will start with const and there I used curly brackets,
MongoClient equals require mongodb.
So this will now get the MongoClient object
from the MongoDB module.
In the constructor, I now add a few member variables.
First, I define the Mongo URL.
So this is the URL to the server.
So at this.mongoUrl equals mongodb localhost
and then colon the port and we know that we are on 37017.
And then I can basically very freely select
which database I want to use.
So if it does not exist, it will be just created in my case.
So we will now use and create a database maxcoin.
Additionally, I will also already define this.client.
So this will be the MongoDBClient.
I will set it to null for now.
And also this.collection
and I will set this to null as well.
So this will all make sense in a few moments.
Now we will implement connect.
And for that, I will now type,
const mongoClient equals new MongoClient.
So we are now creating a new instance of the MongoClient
and its arguments we pass in this.mongoUrl,
so that's the URL to connect to.
And we also add a config object,
and there I now add useUnifiedTopology
and the IntelliSense should already help you with that
and accept this to true.
I will explain this in a second.
And useNewUrlParser and accept this to true as well.
So, luckily, Prettier already helps us
with doing the line breaks here.
So we need these options because the MongoDB driver works
with different versions of MongoDB.
And this, we are now on a very new version of MongoDB.
We have to switch this toggles.
Otherwise, we would get deprecation warning,
so it would still work but we will get warnings.
With these toggles, we avoid that
and the MongoClient uses the new syntax
or new functionality of the MongoDB server.
Next, we want to actually connect to the server
and we do that by first typing this.client
because we want to get the client object back
and store it this member variable, and then I type await
because that's an asynchronous operation
mongoClient, so that's the MongoClient
we just created before, .connect.
So with that, we have a MongoDB connection.
Next, I will also already create an object
that references the collection we will work with.
So add this.collection equals this.client.db
and the database name is maxcoin.
So though we used it in the URL before,
they have to explicitly now tell the driver
that we're using this database.
And in this database, we use the collection values.
And again, we store this collection as a member variable
as you see here.
In the end, we will just return this.client.
Of course, we also now have to call this connect method.
And for that, let's look into that max method
here on line 33
because max will be the method that will be called then
from our main script to get the maximum value.
And in there, I will now first log out some info
that says connecting to MongoDB,
just for us that we know that everything is working fine.
And then, I use console.time.
Console.time can be used to kind of profile operations
within no chairs and that's pretty handy
to see how long different operations take.
Because when working with databases,
of course, performance is important.
Knowing the cost of operations gives you
at least a little bit of an insight
into the performance of your application.
For console.time, you just define some key.
In this case, mongodb-connect,
so that's the operation we are doing.
And then, I will add const client,
so this is the client object equals await this.connect,
and in the next line, I will add some error handling.
So let's see, if client, then there is a method
provided on this client object that it's called isConnected.
And you see how handy the intelligence
of Visual Studio Code is here
because it already gives us this option when I start typing.
isConnected is a function so I have to have parenthesis.
I will output console.info
successfully connected to MongoDB.
And else, so if something went wrong here,
we throw a new error,
and there I will, there is a new error message connecting
to MongoDB failed.
And for the timing I know at console.timeEnd
I use the same key again, MongoDB-connect
let's copy paste that.
And this will then give us the timing on the console.
Of course, we now have to wire up this inner test file.
So open, main.js
and I can remove this require for the coinAPI.
And instead I will now add
const MongoBackend equals require
and this is in services/Backend/MongoBackend.
And in the run function, I add now
const MongoBackend now lower cases
because we're creating an instance
of this object, new MongoBackend.
And then we remove everything else we have there
because we will just return MongoBackend
and there the max method.
Okay, let's try this out.
So I run into him start
and we get successfully connected to MongoDB, and we see
that the MongoDB connect to around 40 milliseconds.
In my case, it might look different on your machine
but also you see this undefined.
This is because we are right now returning nothing
for MongoBackend.max.
So result in line nine is undefined
and console log will then log out undefined.
But what we also see now is
that the script just keeps running
but this should not be the case
because it should just do its job and then terminate.
So it's more of a batch script in this case.
This is because we still have an open connection to MongoDB.
So what we will add next is a way to disconnect
from the MongoDB server once the work is done
so that the script can terminate.
For that I go back into MongoBackend
and they already have the mess that disconnect in line 27.
And there, I just add now, if this.client
just making sure that there is a client object
when we call this.connect and if there is one
I return this.client and there is a SLOs method
that will close the database connection.
Otherwise I will return false.
And of course, we also have to call this now.
So I will just copy paste now 39 to 41
because it's very similar.
So after this console.timeEnd
I now add the first three lines
in and I will just change it to disconnecting from MongoDB
then I will add MongoDB-disconnect as console.time key it,
then I will call await this.disconnect.
And in the end, I will add console.timeEnd disconnect.
So I'm lazy, I'm just copy pasting stuff now
from the connection function
but this should be it basically.
So let's stop this running script
and now run npm start again.
And we now see that we connect to MongoDB.
The connection functional took around 50 milliseconds
and then we disconnect
and this took around eight milliseconds.
One last thing I want to do is I want to check
if the error handling works properly and for that
I would just change the URL of MongoDB now real quick.
And I will just use some random port, let's see, 47017
to see what happens when the connection fails.
So I now, again, run npm start and let's see what happens.
And this can take a little bit
because now MongoDB tries to connect
and likely disconnection has some time out on there.
So let's wait a little bit and see what happens.
And now finally, we see
let's make this a little bit bigger.
We see that we get a proper connection
refused error message here.
So this is because disconnect methods, throws an error
and this error is then actually caught
in our main.js file here in the catch block here.
And this console locked then right afterwards.
So this is exactly what I wanted to see
because error handling is very important
in case something goes wrong.
For instance, the MongoDB server is not running.
So I can now change this back.
Don't forget this to the right port again, 37017.