Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDB Driver Not Being Recognized

I'm building an express app that uses MongoDB for its back end but when I make a request to the database in other parts of the app it's not being recognized.

Here's 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 through a route like this:

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 a console.log(req.db) I get the following in 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] }
like image 557
Jonathan Bechtel Avatar asked Jan 29 '17 22:01

Jonathan Bechtel


People also ask

Does Mongoose use MongoDB driver?

mongoose is built on top of the mongodb driver to provide programmers with a way to model their data.

How does MongoDB driver work?

The official MongoDB Node. js driver allows Node. js applications to connect to MongoDB and work with data. The driver features an asynchronous API which allows you to interact with MongoDB using Promises or via traditional callbacks.

What is MongoDB driver legacy?

“The MongoDB Legacy driver mongodb-driver-legacy is the legacy synchronous Java driver whose entry point is com. mongodb. MongoClient and central classes include com. mongodb. DB , com.


2 Answers

Going by the documentation on npm, I can see that to access a particular collection, this is what you have to do:

  1. Select the collection on which you want to perform the operation
  2. Perform the operation

Here is the code example:

router.get('/formula-list', function(req, res) {

  // Select the collection on which you want to perform an operation
  var formulas = req.db.collection('formulas');

  // Perform that operation
  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'
    });
  });
});
like image 52
Soubhik Mondal Avatar answered Nov 14 '22 22:11

Soubhik Mondal


OK, so before declaring the first route that needs the connection, you'll want to wire up your middleware to assign the db connection to the request. Probably a good idea to release the resource again after the response is sent as well, unless you're using connection pooling.

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(); });
});

Hope that helps.

like image 31
Paul Avatar answered Nov 14 '22 23:11

Paul