Connecting to the database

We will define our MongoDB connection in a ./db.js file. This will help keep our index.js file neat and allow us to keep our configurations modular.

To connect to our database, if you haven't already, create a db.js file in the root directory as given:

touch db.js

Then, insert the following into the file:

// ./db.js

const mongoose = require('mongoose');

module.exports = () => {
mongoose.connect(
'mongodb://localhost:27017/koa-blog',
{ useNewUrlParser: true }
);

const db = mongoose.connection;
db.on('error', error => {
throw new Error(`error connecting to db: ${error}`);
});
db.once('open', () => console.log('database connected'));
};

In the preceding code block, first, we require the mongoose ODM library, then we export a simple function that creates a connection to our database using the mongoose.connect(dbUrl, [options]) method. We are creating a connection to the koa-blog database.

It should also be noted that we set up listeners in our database connection function. The db.on('error') listener is for when an error occurs when a connection is trying to be established. The db.on('open') listener is called when a successful connection occurs.

Now that we have exported our database connection function, we can make use of it in the index.js file as seen here:

// ./index.js

// ...
const initDb = require('./db');

// initialize database
initDb();

// ...

The complete index.js file will now look like this:

const Koa = require('koa');
const initDb = require('./db');

// initialize database
initDb();

// create app instance
const app = new Koa();

// start server
const port = process.env.PORT || 3000;
app.listen(port, () => console.log(`Server running on http://localhost:${port}`));

The next time our application starts, we should see messages similar to this one:

Server running on http://localhost:3000
database connected

This indicates that the connection to the database was successful.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.149.213.209