TypeError:无法调用未定义的方法“get”
我尝试使用express.js在node.js上创build一个简单的CRUD应用程序。 我尝试连接到数据库,但我有一个错误TypeError: Cannot call method 'get' of undefined
。 我的部分代码:
app.js
var mongo = require('mongodb'); var monk = require('monk'); var db = monk('localhost:27017/notepad'); var app = express(); app.get('/users', routes.userlist); // mongoDB app.use(function (req, res, next) { req.db = db; // this is setting up db property to request next(); });
路线/ index.js
exports.userlist = function (req, res) { var db = req.db; var collection = db.get('usercollection'); // error in this line collection.find({}, {}, function (e, docs) { res.render('userList', { "userlist": docs }); }); };
我认为DB的实例没有设置,或者在其他文件中不可用。 如何解决这个问题?
你的app.use
应该写在你的app.get
之前。 app.get
首先被Express调用。
var mongo = require('mongodb'); var monk = require('monk'); var db = monk('localhost:27017/notepad'); var app = express(); // mongoDB // Do all your "pre-route" use() functions first app.use(function (req, res, next) { req.locals.db = db; // this is setting up db property to request next(); }); app.get('/users', routes.userlist);
在你的路线…
var db = req.locals.db; // Instead of req.db
甚至更好…
var mongo = require('mongodb'); var monk = require('monk'); var db = monk('localhost:27017/notepad'); var app = express(); app.locals.db = db; app.get('/users', routes.userlist); // Access it using req.locals.db