我正在构建一个使用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] }
答案 0 :(得分:3)
好的,所以在声明需要连接的第一个路由之前,您需要连接中间件以将db连接分配给请求。除非您使用连接池,否则在发送响应后再次释放资源可能是个好主意。
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(); });
});
希望有所帮助。
答案 1 :(得分:3)
通过documentation on npm,我可以看到要访问特定的集合,这就是你必须要做的事情:
以下是代码示例:
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'
});
});
});
答案 2 :(得分:3)
尝试像这样使用
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'
});
});
希望它有所帮助。
答案 3 :(得分:1)
您需要移动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); ...
答案 4 :(得分:1)
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');
然而,最好不要添加"魔术代码"