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:无法读取属性'集合'未定义的 exports.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');
答案 0 :(得分:0)
试试这个
// 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');