All right.
And up next, let's connect to our database.
Now, in order to do that, we need to import mongoose from Mongoose.
It has a method by the name of Connect.
So we go here with Mongoose Dot Connect, and we need to provide that connection string.
Remember the variable we set up a few videos ago and since it's located in dotenv we want to go with
process dot env and then mongo URL.
And it's always my preference to essentially wrap everything in try and catch and right after the mongoose
connect, which returns a promise and that's why we stick await in front of it.
And remember we don't need to create a function anymore.
Now we can just do it without the function we can simply set up await.
And right after that I'll set up my app.listen and all of this is going to be wrapped in try and catch
so that way if there's any issue.
So if I cannot connect to the database, well, there's really no point for my server, correct, since
all of the functionality involves connecting to the database, Hopefully that is clear.
So therefore here in the catch we just go with console log and then we go process dot exit and we pass
in one which stands basically for error.
So now let's navigate to a server like always.
We want to start by importing stuff.
So we're going to go here, Mongoose from Mongoose, and let's keep on moving.
Or here we have the port, Beautiful.
Right after that we'll set up the try and catch.
Like I already said few times, we can right away use the await.
Nothing stops us and then we want to go with process dot env.
And we're looking for Mongo.
Underscore you URL and then we'll move this sucker a little bit up.
So if we're successful.
Yep.
Then let's start our server.
Now, if there's some kind of error, we most likely want to see it.
So we'll go here with console log error and then we're going to go with process dot exit.
So if there is an error, we want to exit and we want to provide one.
So now let's open up our console and let's spin up our server.
So we're going to go over here with NPM run dev and if everything is correct, we'll see over here.
Server running on port 5100.
So that means that we successfully connected to the database.
Now before we move on, let me just show you a typical error you might get if, let's say your password
is wrong.
Let me go here.
Let me remove one character.
Remember, we do need to pretty much restart everything.
And now you'll see a big, massive, giant error in the console.
Basically, we have bad auth.
And again, if you see this type of error and notice it even says mongo server error and all that,
that means you need to double check your connection string.
So again, let me go back over here.
Then let me restart NPM run.
So if you don't see any errors, you're in good shape and we can move on to the next step.