MongoDB driver not recognized

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] } 
+6
source share
5 answers

Following the npm documentation , I see that to access a specific collection, this is what you need to do:

  • Select the collection in which you want to perform the operation.
  • Perform an operation

Here is a sample code:

 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' }); }); }); 
+3
source

OK, so before declaring the first route that needs a connection, you will want to connect your middleware to assign a db connection with the request. It is probably a good idea to free the resource again after sending the response if you are not using the connection pool.

 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 this helps.

+3
source

Try using it like this:

 db.collection('collectionName').find({}).toArray(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' }); 

});

Hope this helps.

+3
source

You need to move the db initialization code up (before defining the routes) and add middleware that includes the mongodb driver in the req object. Sort of:

 mongo.connect('mongodb://localhost:27017/formulas', function(err, db){ app.use(function(req, res, next){ req.db = db; next(); }); }); app.use(root); ... 
+1
source

db.formulas does not exist, it is a short hand from mongo REPL.

In Node.js, you need to first get the collection using

db.collection('name')

This means that instead of db.formulas.find you can do:

db.collection('formulas').find({}, {}, function(e, docs){})

You can also do:

db.formulas = db.collection('formulas'); db.another = db.collection('another');

However, it’s always better not to add to the “magic code”

+1
source

Source: https://habr.com/ru/post/1014541/


All Articles