Now just as with MySQL and NodeJS
in order to connect to the MongoDB database
from inside our NodeJS code,
we wanna use a third-party package,
so that we don't need to manage the technical details
of establishing and holding such a connection on our own.
And for this you can search for NodeJS MongoDB,
and you'll find your official MongoDB Node Driver.
So a package created by the MongoDB team,
which is meant for exactly this use case
that you wanna connect to MongoDB from inside NodeJS.
Now, if you'd click on Quick Start there,
you'll learn how you can set up a project
and how you can install this MongoDB driver.
It's this simple command.
So we can copy this command.
And then quit does running nodemon server here
for the moment,
and then run npm install mongodb
to install this third-party package,
which therefore was also added as a dependency
to the package.json file.
And then we can restart our node server.
Now this alone, of course doesn't connect to the database,
it just gives us a package that helps with the connection.
And to manage the connection,
I'll create a new folder in this project,
the data folder with a database.js file.
And in there, I wanna manage that connection
so that in the other files
where I wanna use that connection,
I can just reach out to the single file.
And I don't have to establish a new connection
in every file where I wanna work with the database.
Now, there are various ways of implementing
such a connection and of managing such a connection,
but here's a very common pattern which you can use
in such a global database management file like this
when working with MongoDB.
We first start by importing this MongoDB package,
which we just installed.
By requiring mongodb like this
in this database.js file here.
Then as a next step, we can get the Mongo client
by accessing mongodb.MongoClient.
That's the actual thing that we need from the package
to establish a connection.
Now, this Mongo client can be used
to call the connect method to then
do exactly what the name suggests,
to create a connection to a MongoDB server.
So in this case to the server,
which is running locally on our machine.
So here we can call connect.
And connect needs some information
on how to establish this connection.
Therefore we can pass and parameter values.
And the first parameter value which we can pass
is a URL that points to the MongoDB server.
Now the format of this URL might look a bit weird,
but it is a format understood
by this third-party package here.
It looks like this, you type mongodb://
and then localhost:27017,
since that is the address that will be used
by that MongoDB server on our local system.
Now, you know this from the official docs.
For example, if you look at them
or of course by simply believing me here.
This year might look a bit strange,
but it's simply telling the MongoDB driver
that it should connect to this server
with a special protocol, so to say.
Which are some low level details
we don't have to worry about.
In the end, this will be the URL pointing
to our locally running MongoDB server.
That's the port number that's being used
by that server out of the box by default.
And therefore, this should establish such a connection.
You'll also find this here in the official documentation.
If you have a look at their example,
they are using a slightly different URL here
because they are connecting to a cluster.
But if you have a look at connect to localhost,
you see exactly this address I showed you
a couple of seconds ago.
So that's how we can connect to our MongoDB server here.
We'll come back to connecting to such a cluster here
later in the course, once we talk about deployment
and about running a database for a real website,
that's being exposed to users.
But for development, this local host solution
is absolutely fine.
Now this would establish such a connection,
and it actually establishes such a connection
by returning a so-called promise.
And we learned about promises in this more advanced
JavaScript course section a couple of hours ago.
And we also already used promises
when we worked with MySQL.
So I'm not going to explain them in depth here,
instead of check out those earlier course sections
to understand what promises are.
In the end, promises allow us
to work with asynchronous code.
So code that can take a little bit longer
to execute, so to say.
And here establishing such a connection
can take a bit longer,
therefore this is actually returning such a promise.
And therefore what I'll actually do here
is I'll create a new function.
Connect could be the name.
And I'll turn this into an async function
with the async keyword,
and then move this line of code into this function,
and then use the await keyword
to wait for this operation to finish.
And then when using does await keyword,
this will eventually give us the database client,
which we now have.
So which now gives us access to the connected database.
So now whenever we call the connect function
from anywhere in our code, which we're not doing yet,
but which we will do soon,
will establish such a connection and get such a client.
Now, as a side note, this connection,
which is established here,
will actually automatically be a connection pool,
which is managed by the MongoDB package.
So multiple connections will be established.
And whenever you then need to run a query,
you will automatically get an open connection,
which you can use.
And the MongoDB package will manage
all those connections for us, which is very convenient.
So we don't have to worry about that.
Hence, we get this client,
which would allow us to interact
with the connected database,
but I don't wanna run my queries and commands
from inside this file.
I wanna run those commands from inside another file.
And therefore what I'll do here
is I'll add a new variable.
Database, could be the name.
And actually I will set database equal to client.db here.
And db is a method that we can execute
to connect to a specific database on the server
because here we only establish a connection
to the server as a whole.
Now we can call the db method to actually talk
to the blog database on that server.
And that is the database we worked with
a couple of minutes ago in the MongoDB shell.
And the result of calling db is an access to exactly
that database on the MongoDB server
and that stands for what I store in this database variable,
which is deliberately created
outside of this connect function
so that it can be used in this whole file,
and not just in this connect function.
Because my goal is to make this variable
available outside of this file as well now.
Simply by adding another function,
getDb could be the name
where I simply return database,
like this.
And we could even check if databases may be not set
if it's falsey,
and if that's the case, we could throw an error
where we say "Database connection not established!"
Just to ensure that we're not trying to work
with that database before we actually have it.
So that connect must've been called
before we try to use the database.
That's a little security check for ourselves,
which we can add here.
It's not mandatory, but also not a bad idea.
And now as a last step here,
I will add the module.exports statement
and export an object here.
And that will be an object
where I expose both these functions to the outside world.
So I'll add connectToDatabase as a key here
and point at the connect function like this.
And then as a second property in this exported object,
I'll add getDb as a key and point at getDb.
So the things on the right side of the colons
are these function names we have here in this file.
And by just pointing at them and not executing them,
so by not adding parentheses,
we make sure that they are not executed yet,
but that instead they can be executed in our files,
which import this file,
which is exactly what I wanna achieve.
This file should just be a utility file.
The functions should actually be executed
from somewhere else in our code.
And then for now with this file added here,
we can go back to another place
where I do wanna establish this connection.
And what could be a good place for doing that?
Well, actually it would be app.js,
where we start this overall node-express server
and where we initialize all our settings
and all our middlewares, that's a great place
for actually also connecting to the database.
And I wanna connect to the database here,
once all the other set up was done.
So here at the bottom, maybe.
There, I wanna connect to my database.
And actually I only wanna start listening here
on port 3000 if that database connection was established.
And to ensure that this is the case,
I'll import my database,
or my db file
by requiring ./data/database like this,
that will actually require this database file.
And then with that here, we can call connectToDatabase,
this one function we're exporting.
And that will then return a promise.
And here we can't necessarily use await,
since we're not inside of an async function here.
Hence, what we can do here is we can use the then method,
which you also learned about in an earlier course section,
which takes a function,
in this case, for example, an anonymous function
that will be executed once this promise resolved,
so once this promise is done.
And then I'll move app.listen inside of this function,
so that app.listen 3000 only executed
once the database connection was established.
Simply to ensure that we only start this web server,
if we have an active database connection.
Now we could also handle the connection in different cases.
We could establish it differently,
and we could also, for example, check if the server crashes
or anything like that.
And in that case, shut down our database connection,
but I don't wanna make things too complex here.
And therefore, for the moment,
I'll stop my running nodemon server
by pressing control + C in this terminal,
and I'll save all files
and then restart this all with npm start.
And since it now is running again,
and I can visit my blog again,
it looks like everything works.
And it looks like indeed we do have
this active connection now.
And therefore, now we established a connection
as a next step.
We can now make sure that we actually query our authors
so that we can pre-populate this dropdown
on the create post page with the author's data.