I am creating an express application that uses MongoDB for its back end, but when I query the database in other parts of the application, it is not recognized.
Here is what I have:
APP.JS (using Paul's answer):
var express = require('express'); var app = express(); var bodyParser = require('body-parser'); var cookieParser = require('cookie-parser'); var passport = require('passport'); var mongo = require('mongodb').MongoClient; var assert = require('assert'); // make mongodb available to the application app.use((req, res, next) => { mongo.connect('mongodb://localhost:27017/formulas', (e, db) => { if (e) return next(e); req.db = db; next(); }); // cleanup req.on('end', () => { req.db.close(); }); }); //define routes var root = require('./routes/index'); var authenticate = require('./routes/authenticate'); var about = require('./routes/about'); var contact = require('./routes/contact'); var formula = require('./routes/formula'); var formulaAPI = require('./routes/api/formula'); var formulaList = require('./routes/formula-list'); var formulaListAPI = require('./routes/api/formula-list'); app.set('view engine', 'ejs'); app.set('views', __dirname + '/views'); app.use(express.static(__dirname + '/public')); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: false })); app.use(root); app.use(about); app.use(contact); app.use(formula); app.use(formulaAPI); app.use(formulaList); app.use(formulaListAPI); app.use(authenticate); app.listen(3000, function(){ console.log("The server is now listening on port 3000"); }); module.exports = app;
When I call the database along the following route:
var app = require('express'); var router = app.Router(); var data = require('../data/formula.json'); router.get('/formula-list', function(req, res){ var db = req.db; db.formulas.find({}, {}, function(e, docs){ res.render('formula-list', { formulas: docs, title: 'Your Formulas', description: `List of saved user formulas from the formula generator`, ID: 'formula-list', keywords: 'formula generator, health kismet, nutraceutical formula builder' }); }); });
I get the following error:
TypeError: Cannot read property 'find' of undefined
When I do console.log(req.db)
, I get the following on my console:
req.db:
EventEmitter { domain: null, _events: {}, _eventsCount: 0, _maxListeners: undefined, s: { databaseName: 'formulas', dbCache: {}, children: [], topology: EventEmitter { domain: null, _events: [Object], _eventsCount: 7, _maxListeners: undefined, clientInfo: [Object], s: [Object] }, options: { readPreference: [Object], promiseLibrary: [Function: Promise] }, logger: { className: 'Db' }, bson: {}, authSource: undefined, readPreference: { _type: 'ReadPreference', mode: 'primary', tags: undefined, options: undefined }, bufferMaxEntries: -1, parentDb: null, pkFactory: undefined, nativeParser: undefined, promiseLibrary: [Function: Promise], noListener: false, readConcern: undefined }, serverConfig: [Getter], bufferMaxEntries: [Getter], databaseName: [Getter] }