- [Instructor] With all the credentials in place,
we will now make MongoDB available to Express.
For that, we will use Mongoose.
Mongoose is an object data modeling laboratory for MongoDB.
It's very commonly used, lets us create schemas
and makes working with Mongoose
from NodeJS generally easier.
On the flip side it comes with some performance overhead.
So if your applications are heavy on database reads
and writes and you run into performance issues,
Mongoose might be an optimization target.
Let's install Mongoose now, for that,
I type, npm install --save and my project wrote.
And I want to isolate everything that has to do
with the database connection in a model on its own.
For that I create a new folder in server called, lib.
And in lib I create the new file, db.js
and here on line one I will,
add const mongoose = require('mongoose')
And further down I add, module.exports
and I want to export a function connect
and this function is asynchronous,
and takes a database connection string dsn
and it will then simply call,
mongoose.connect with I think even dsn as argument.
Additionally I also want to add a configuration property,
called useNewUrlParser
because if you omit this right now you would get some,
deprecation warnings when MongoDB starts up.
So I want to write that.
So I add useNewUrlParser is true.
Mongoose is smart enough
to maintain a global database connection.
So as soon as we connected to the database once,
we don't have to pass the connection object around.
Given that it would theoretically not matter
where we create the database connection.
I will create it in, bin www
which is our main startup script.
I do this because if we scroll down here on line 42,
we see that we are calling server.listen
which makes the application accept new HTTP requests.
And I want to make sure that the database connection,
is already set up before the application accepts requests.
So for that I will now up here after app required,
the application I will add on line nine,
const db = require('../server/lib/db')
next I will add back to line 42.
And there I will now add, db.connect(config.database.dsn)
because we already have the configuration object in place
inside this current file and then I call .then.
So if the connection was established I will now,
first log out, console.log('Connected to MongoDB')
and next I will start listening on the HTTP port,
means accepting new requests
and I also want to handle errors
and for that I add .catch((err)
and if an error occurs I will, simply console.error
means letting the user know what went wrong.
For now we can ignore those screen warning indicators.
We will take care of that later in this course.
Now let's try this out by starting the application.
So I run, npm start and as you see we get connected
to MongoDB first and this is then followed
by the information that the servers listening.
This means we won't accept requests,
unless the database is already setup and in place.