TypeError:无法读取未定义的属性“集合”这里有啥错误?
Posted
技术标签:
【中文标题】TypeError:无法读取未定义的属性“集合”这里有啥错误?【英文标题】:TypeError: Cannot read property 'collection' of undefined what is the mistake here?TypeError:无法读取未定义的属性“集合”这里有什么错误? 【发布时间】:2016-05-17 22:45:49 【问题描述】:var mongodb = require('mongodb');
var MongoClient = mongodb.MongoClient;
var url = 'mongodb://localhost:27017/projectone';
var db1=MongoClient.connect(url, function (err, db)
if (err)
console.log('Unable to connect to the mongoDB server. Error:', err);
if(!err)
console.log('Connection established to', url);
);
exports.findAll = function(req, res)
var collection = db1.collection('student');
collection.find().toArray(function (err, result)
res.send(result);
);
这是我正在使用的示例代码,它在执行下面的代码时抛出错误。谁能解释为什么会这样?
我得到的错误:
TypeError:无法读取未定义的属性“集合” export.findAll (/home/android/student/pro1/route/connect1.js:16:6) 在回调 (/home/android/student/pro1/node_modules/express/lib/router/index.js:164:37) 在参数 (/home/android/student/pro1/node_modules/express/lib/router/index.js:138:11) 通过时 (/home/android/student/pro1/node_modules/express/lib/router/index.js:145:5) 在 Router._dispatch (/home/android/student/pro1/node_modules/express/lib/router/index.js:173:5) 在 Object.router (/home/android/student/pro1/node_modules/express/lib/router/index.js:33:10) 接下来 (/home/android/student/pro1/node_modules/express/node_modules/connect/lib/proto.js:174:15) 在 Object.expressInit [作为句柄] (/home/android/student/pro1/node_modules/express/lib/middleware.js:30:5) 接下来 (/home/android/student/pro1/node_modules/express/node_modules/connect/lib/proto.js:174:15) 在 Object.query [作为句柄] (/home/android/student/pro1/node_modules/express/node_modules/connect/lib/middleware/query.js:43:5)
var express=require('express'),
connect=require('./route/connect3');
var app=express();
app.get('/con',connect.findAll);
app.listen(8081);
console.log('listening to port 8081');
【问题讨论】:
【参考方案1】:试试这个
// connect3.js
var mongodb = require('mongodb');
var MongoClient = mongodb.MongoClient;
var url = 'mongodb://localhost:27017/projectone';
module.exports = MongoClient.connect(url, function (err, db)
if (err)
console.log('Unable to connect to the mongoDB server. Error:', err);
if(!err)
console.log('Connection established to', url);
return db;
);
exports.findAll = function(req, res)
var collection = req.db.collection('student');
collection.find().toArray(function (err, result)
res.send(result);
);
还有你的主文件
var express=require('express'),
const db = require('./route/connect3');
var app = express();
app.use(function(req, res, next)
req.db = db;
next();
)
app.get('/con',connect.findAll);
app.listen(8081);
console.log('listening to port 8081');
【讨论】:
我认为在通用中间件中传递数据库是一种不好的做法,你不觉得吗?以上是关于TypeError:无法读取未定义的属性“集合”这里有啥错误?的主要内容,如果未能解决你的问题,请参考以下文章
nodejs/mongoDB - 类型错误:无法读取未定义的属性“集合”
nodejs/mongoDB - 类型错误:无法读取未定义的属性“集合”