Answer the question
In order to leave comments, you need to log in
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'));
});
}
});
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);
})
}
};
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);
});
});
...и тут много роутов
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question