TypeError:无法调用未定义的方法"get"

TypeError:无法调用未定义的方法

问题描述:

我尝试使用express.js在node.js上创建一个简单的CRUD应用程序.我尝试连接到DB,但是出现错误TypeError: Cannot call method 'get' of undefined.我的部分代码:

I try to make a simple CRUD application on node.js using express.js. I try to connect to DB, but I have an error TypeError: Cannot call method 'get' of undefined. Part of my code:

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

routes/index.js

routes/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
    });
});
};

我认为数据库的实例未设置或在其他文件中不可用.该如何解决?

I think the instanse of DB is not setted or it's not available in other file. How to solve this?

您的app.use应该写在app.get之前. app.get首先由Express调用.

Your app.use should be written before your app.get. The app.get is called first by 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