- android - 多次调用 OnPrimaryClipChangedListener
- android - 无法更新 RecyclerView 中的 TextView 字段
- android.database.CursorIndexOutOfBoundsException : Index 0 requested, 光标大小为 0
- android - 使用 AppCompat 时,我们是否需要明确指定其 UI 组件(Spinner、EditText)颜色
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: Cannot read property 'collection' of undefined at exports.findAll (/home/android/student/pro1/route/connect1.js:16:6)
at callbacks (/home/android/student/pro1/node_modules/express/lib/router/index.js:164:37) at param (/home/android/student/pro1/node_modules/express/lib/router/index.js:138:11) at pass (/home/android/student/pro1/node_modules/express/lib/router/index.js:145:5) at Router._dispatch (/home/android/student/pro1/node_modules/express/lib/router/index.js:173:5) at Object.router (/home/android/student/pro1/node_modules/express/lib/router/index.js:33:10) at next (/home/android/student/pro1/node_modules/express/node_modules/connect/lib/proto.js:174:15) at Object.expressInit [as handle] (/home/android/student/pro1/node_modules/express/lib/middleware.js:30:5) at next (/home/android/student/pro1/node_modules/express/node_modules/connect/lib/proto.js:174:15) at Object.query [as handle] (/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');
最佳答案
试试这个
// 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');
关于node.js - 类型错误 : Cannot read property 'collection' of undefined what is the mistake here?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35266812/
我是一名优秀的程序员,十分优秀!