我想通过mongoskin从mongodb中读取一些数据。但是当我尝试调用localhost:3000 / tasks
时,nodejs会抛出一个错误在我的数据库'todo'中,集合'tasks'中有一些项目。当我启动应用程序时,控制台中的结果正常。
谁能看到我写错了什么?
eroor消息:
500 TypeError: Cannot read property 'tasks' of undefined
at exports.list (/Users/piet/Websites/privat/mongo/routes/tasks.js:7:8) at callbacks (/Users/piet/Websites/privat/mongo/node_modules/express/lib/router/index.js:164:37)
at param (/Users/piet/Websites/privat/mongo/node_modules/express/lib/router/index.js:138:11)
at pass (/Users/piet/Websites/privat/mongo/node_modules/express/lib/router/index.js:145:5)
at Router._dispatch (/Users/piet/Websites/privat/mongo/node_modules/express/lib/router/index.js:173:5)
at Object.router (/Users/piet/Websites/privat/mongo/node_modules/express/lib/router/index.js:33:10)
at next (/Users/piet/Websites/privat/mongo/node_modules/express/node_modules/connect/lib/proto.js:193: 15)
at Object.methodOverride [as handle] (/Users/piet/Websites/privat/mongo/node_modules/express/node_modules/connect/lib/middleware/me thodOverride.js:48:5)
at next (/Users/piet/Websites/privat/mongo/node_modules/express/node_modules/connect/lib/proto.js:193: 15)
at Object.urlencoded [as handle] (/Users/piet/Websites/privat/mongo/node_modules/express/node_modules/connect/lib/middleware/ur lencoded.js:49:37)
我的app.js:
var express = require('express');
var routes = require('./routes');
var tasks = require('./routes/tasks');
var http = require('http');
var path = require('path');
var mongo = require("mongoskin");
var db = mongo.db('localhost:27017/todo?auto_reconnect=true', {
safe:true })
.collection('tasks')
.find()
.toArray(function(error, items){
console.log(items);
})
var app = express();
app.set('port', process.env.PORT || 3000);
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.json());
app.use(express.urlencoded());
app.use(express.methodOverride());
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));
if ('development' == app.get('env')) {
app.use(express.errorHandler());
}
app.get('/', routes.index);
app.get('/tasks', tasks.list);
http.createServer(app).listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port'));
});
/routes/tasks.js下的路径文件
exports.list = function(req, res, next){
req.db.tasks.find({
completed: false
}).toArray(function(error, tasks){
res.render('tasks', {
title: "ToDo list",
name: tasks = tasks || []
})
})
};
答案 0 :(得分:2)
使用28017作为端口ID。您可以在“req.db”中查看您的内容。 Mayb这是未定义的。
答案 1 :(得分:2)
您将需要一个中间件来将收集对象与您的请求挂钩:
var db = mongo.db('localhost:27017/todo?auto_reconnect=true');
var tasks = db.collection('tasks');
...
app.use(function(req, res, next) {
req.db = { tasks : tasks }; // this exposes the collection as `req.db.tasks`
// to your route handlers
next();
});
app.use(app.router);
...
答案 2 :(得分:1)
在您的routes / task.js中,req是Express.js的请求对象。它没有“db”句柄,这就是你收到错误的原因:
500 TypeError: Cannot read property 'tasks' of undefined
在app.js中,这是获取db句柄的错误方法:
var mongo = require("mongoskin");
var db = mongo.db('localhost:27017/todo?auto_reconnect=true', { safe:true })
.collection('tasks')
.find()
.toArray(function(error, items){
console.log(items);
});
db代码应该移动到一个单独的模块中(例如dbConnection.js),这样每次需要db句柄时,你只需要这样做:
var db = require('./dbConnection').getDb();
routes / task.js需要获取db句柄才能进行数据库调用。所以这里是你修改过的app.js,routes / task.js和新的dbConnection.js文件:
dbConnection.js:
var open = function() {
return require('mongoskin').db('localhost:27017/todo?auto_reconnect=true',
{safe: true, strict: false}
);
};
var db = open();
var dbConnection = {
getDb: function() {
if (!db) {
db = open();
}
return db;
}
};
module.exports = dbConnection;
路由/ task.js:
var db = require('../dbConnection').getDb();
exports.list = function(req, res, next){
var tasksCollection = db.collection('tasks');
tasksCollection.find({ completed: false }).toArray(function(error, tasks){
res.render('tasks', {
title: "ToDo list",
name: (tasks || [])
});
});
};
app.js:
var express = require('express');
var routes = require('./routes');
var tasks = require('./routes/tasks');
var http = require('http');
var path = require('path');
var app = express();
app.set('port', process.env.PORT || 3000);
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.json());
app.use(express.urlencoded());
app.use(express.methodOverride());
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));
if ('development' == app.get('env')) {
app.use(express.errorHandler());
}
app.get('/', routes.index);
app.get('/tasks', tasks.list);
http.createServer(app).listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port'));
});