Q:

How to export database connection string node / node.js

I am trying to turn the following database connection string into a module:
require('dotenv').load();
var knex = require('knex')({
    client: 'pg',
    connection: {
        host: 'localhost',
        user: process.env.DB_USER,
        password: process.env.DB_USER_PASSWORD,
        database: process.env.DB_NAME
    },
    pool: {
        min: 0,
        max: 7
    }
});

So far I tried:
require('dotenv').load();
module.exports = {
knex : require('knex')({
    client: 'pg',
    connection: {
        host: 'localhost',
        user: process.env.DB_USER,
        password: process.env.DB_USER_PASSWORD,
        database: process.env.DB_NAME
    },
    pool: {
        min: 0,
        max: 7
    }
})

}

In my app.js file:
var knex = require('./models/database');
knex.select().table('users').then(function(result) {
    result.forEach(function(value) {
        console.log(value.first_name);
    });
});

This returns the error 'knex' is undefined. I think the way my module is being exported is incorrect... can someone help?
Thank you!

A:

It's because you're exporting an object containing knex.
Either add knex to the require:
var knex = require('./models/database').knex;

or change your export to
module.exports = require('knex')({ ... })

