MongoDB驱动程序未被识别

我正在构build一个使用MongoDB作为后端的快速应用程序,但是当我在应用程序的其他部分向数据库发出请求时,它不被识别。

这是我有:

APP.JS(使用Paul的答案):

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; 

当我通过这样的路线调用数据库时:

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

我得到以下错误:

 TypeError: Cannot read property 'find' of undefined 

当我做一个console.log(req.db)我在我的控制台中得到以下内容:

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] } 

       

网上收集的解决方案 "MongoDB驱动程序未被识别"

通过npm上的文档 ,我可以看到要访问一个特定的集合,这是你必须做的:

  1. select您要执行操作的集合
  2. 执行操作

这是代码示例:

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

好的,所以在声明第一个需要连接的路由之前,你需要连接你的中间件来为请求分配数据库连接。 在发送响应之后再次释放资源可能是一个好主意,除非您使用连接池。

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

希望有所帮助。

尝试像这样使用它

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

});

希望能帮助到你。

你需要移动你的db init代码(在你的路由定义之前),并将包含mongodb驱动程序的中间件添加到req对象中。 就像是:

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

db.formulas不存在,这是来自mongo REPL的简短手段。

在Node.js中,您需要先使用该集合

db.collection('name')

这意味着,而不是做db.formulas.find你可以做:

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

你也可以做:

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

但是最好不要添加“魔术码”