我尝试使用express.js在node.js上创建一个简单的CRUD应用程序。我尝试连接到DB,但是我有一个错误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
});
});
};
我认为数据库的实例未设置或在其他文件中不可用。怎么解决这个问题?
答案 0 :(得分:1)
您的app.use
应该在app.get
之前写下来。快递首先调用app.get
。
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