Now that we have created out database, in this exercise we are going to connect our application to our database using the necessary npm packages, that is, knex and mysql:
- On the Terminal, change directory to the root of our project, and run the following command:
npm install mysql knex --save
- Let's create a file db.js and add the following code to it, replacing the user and password appropriately if need be:
const env = process.env.NODE_ENV || 'development';
const configs =
{
development:
{
client: 'mysql',
...
const Knex = require('knex')(configs[env]);
module.exports = Knex;
You can find the complete code from the db.js file at Code/Lesson-3/exercise-a.
- Let's test that we have our configurations right. We will create a test-db.js file:
const Knex = require('./db');
Knex.raw('select 1+1 as sum')
.catch((err) => console.log(err.message))
.then(([res]) => console.log('connected: ', res[0].sum));
- Now, let's go to the Terminal and run the test file:
node test-db.js
You should get the following printed:
connected: 2