As in the Express split of ranting on the files and give them a connection to MongoDB?

Now the entire application in one file, but it has expanded greatly, decided to break it into pieces.
Here's what happens:

index.js
// BASE SETUP
// =============================================================================
const express = require('express');
const app = express();
const bodyParser = require('body-parser');
const cors = require('cors');
const db = require('./app/db');

// configure app to use bodyParser()
// this will let us get the data from a POST
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());
app.use(express.static('public'));
app.use(cors());

app.set('port', (process.env.PORT || 3000));

// ROUTES FOR OUR API
// =============================================================================
/*const router = express.Router(); // get an instance of the express Router*/
const router = require('./app/router'); // get an instance of the express Router

app.use('/', router);

// Connect to Mongo on start
db.connect(mlabUrl, function(err) {
 if (err) {
 console.log('Unable to connect to Mongo.')
process.exit(1)
 } else {
 app.listen(app.get('port'), function () {
 console.log('Node app is running on port', app.get('port'));
});
}
});


db.js
let MongoClient = require('mongodb').MongoClient;

let state = {
 db: null,
};

exports.connect = function (url, callback) {
 if (state.db) {
 return callback();
}

 MongoClient.connect(url, function (err, db) {
 if (err) {
 return callback(err);
}

 state.db = db;
callback();
});

}


exports.get = function () {
 return state.db;
};


exports.close = function (callback) {
 if(state.db) {
 state.db.close(function(err, res) {
 state.db = null;
 state.mode = null;
callback(err);
})
}
};


router.js
const express = require('express');
const router = express.Router();
const ObjectID = require('mongodb').ObjectID;

let db = require('./db');

router.get('/items', (req, res) => {
 db.collection('items').find().toArray((err, results) => {
Res. send(results);
});
});

...and there's a lot of ranting


Wanted to break ranting about files and connect to the database to do when the application starts, but something goes wrong - get 500 'TypeError: db.collection is not a function'
June 14th 19 at 20:46
1 answer
June 14th 19 at 20:48
What do DB forgot in ranting?
And on the topic - create a folder with the ranting, there is an index file that loads the Board from a folder.
But I highly recommend that you read the guides for node and MVC in General.

Find more questions by tags Express.jsMongoDBNode.js