Connecting to a database

MongoDB, the NoSQL database, which is popular for being a part of the MEAN stack (MongoDB, Express, Angular, and Node.js), will be used to persist all of our contact data into our API. Its ability to easily save JSON objects without needing a strict schema setup is great for our purposes.

We will be making use of Mongoose, a popular ODM library, for all of our database interactions. Mongoose manages our interactions with the database, does object schema validation, and also maps objects in our code into their corresponding MongoDB document representations.

Let's update our index.js file, in order to allow our app to connect to the database with Mongoose, as follows:

// ./index.js
// ...

const mongoose = require('mongoose');
mongoose.connect(
'mongodb://localhost:27017/koa-contact',
{ 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 dependency as the mongoose object. Then, we use the mongoose.connect() method to connect our Mongo database. The connect method takes the MongoDB connection URL as its first argument, then an object with connection options as its second. The only option that we specify is for mongoose to use the new URL parser for the mongo connection string.

Next, we define listeners to alert us when there's an error connecting to the DB, and once the database is successfully connected to.

At this point, the complete index.js file should look as follows:

// ./index.js

// require needed dependencies
const Koa = require('koa');
const app = new Koa();

// connect to mongodb with mongoose
const mongoose = require('mongoose');
mongoose.connect(
'mongodb://localhost:27017/koa-contact',
{ useNewUrlParser: true }
);

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

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

Running this, you should see a database connected message on your console or Terminal, right after the server starts.

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

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