I
I
Ivan-P2017-10-03 02:25:23
MongoDB
Ivan-P, 2017-10-03 02:25:23

How to split routes into files in Express and pass them a MongoDB connection?

Now the whole application is in one file, but it has grown a lot, I decided to break it into pieces.
Here is the result:
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);
  });
});

...и тут много роутов

I wanted to split the routes by files and make a connection to the database when the application starts, but something goes wrong - I get 500 'TypeError: db.collection is not a function'

Answer the question

In order to leave comments, you need to log in

1 answer(s)
I
Ivan, 2017-10-03
@LiguidCool

What did the database forget in the routes?
And on the topic - create a folder with routes, there is an index file that loads the boards from the folder.
But I strongly recommend that you read the guides on the node and on MVC in general.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question